$A \times A = A + D +D $ in category of irreflexive graphs

Question: In p.223 of Conceptual Mathematics, 2nd ed., by Lawvere and Schanuel, Exercise 21 asks:

If $A, D$ denote the generic arrow and the naked dot in $S^{\Downarrow}$, show that
$$ A \times A = A + D +D $$
Hint: Besides counting the arrows and dots of an arbitrary graph $X$ (such as $X = A \times A$) via maps $A \rightarrow X$, $D \rightarrow X$, the actual internal structure of $X$ can be calculated by composing these maps with the two maps $s,t: D \rightarrow A$.

For context:
$S^{\Downarrow}$ is the category of irreflexive graphs, whose objects are two sets $X$ (the set of arrows) and $P$ (the set of points) with maps $source: X \rightarrow P$ and $target: X \rightarrow P$. A map between graphs is a structure-preserving morphism with respect to these two graphs.
$A$ the generic arrow is the graph that looks like * -> *.
$D$ the naked dot is the graph that looks like *.
This problem appears in the section for the distributive law which states the following maps are isomorphisms:
$$ (A \times B) + (A \times C) \rightarrow A \times (B + C) $$
$$ 0 \rightarrow A \times 0 $$
My interpretation of the hint is that any graph map $A \rightarrow X$ is equivalent to a graph map $D \rightarrow X$ defined as the arrow map pre-composed with either the $s$ or $t$ map, since every arrow must have either a source or target. Beyond that I have been having trouble figuring this out.. I assume the use of the distributive law is needed at some point.. maybe using something like
$$ A \times A = A \times (A + 0) $$
or
$$ A + D + D = A + (D \times (1 + 1)) $$
Any guidance would be appreciated.
Answer: Call $a,b$ the vertices of $A$, i.e. $A$ is the graph $a\to b$.
Then the vertices of $A\times A$ are $(a,a),\ (a,b),\ (b,a),\ (b,b)$, and we have only one arrow $(a,a)\to (b,b)$ and thus $(a,b)$ and $(b,a)$ are isolated points.

We can formulate then a proof according to the hint, purely categorically, as follows:
We have to prove that $B:= A+D+D$ (depicted as $\left[\matrix{a&d_1\\d_2&b}\right]$ with an arrow $a\to b$) is a product of $A$ and $A$.
Consider the graph homomorphisms $\pi_1:a,d_1\mapsto a;\ d_2,b\mapsto b$ and $\pi_2:a,d_2\mapsto a;\ d_1,b\mapsto b$, and prove the universal property.
Comment: Ahh that's interesting and certainly makes sense. I am curious how one can formulate this answer in terms of the distributive law?
Comment: I'm not sure the distributive law is used here (maybe this will be needed in proving that). But you still have some work to prove the universal property plainly by following the hint..
Comment: Hmm alright, you've certainly given me a good starting point. Will think through proving the universal property, thanks!
Comment: Alright so I think I have it. There are 4 maps $D \rightarrow A \times A$, namely $\{, , ,  \}$. These maps correspond to mapping $D$ to $d_{1}$, $a$, $d_{2}$, and $b$, respectively. From there any pair of graph maps $f,g: G \rightarrow A$ can be translated into maps into $A + D + D$ by seeing how each dot of $G$ is mapped by $f$ and $g$ (e.g. to the source or target of each $A$) and using the appropriate map $D \rightarrow A + D + D$ shown above. Is that right?


sql parent child tree with sort order

Question: Assuming this table
ParentId    ChildId    SortOrder
---------------------------------
0           1          0
1           2          1
2           3          1
2           4          2
2           6          3
1           7          2
1           9          3
9           10         1
9           12         2

how would i write a simple CTE (or another type of query) that would return them parent/child relationships at any level but keeping the sort-order for all child-items below the parent.
basically, this would be a simple tree-view with sub-items ordered by a specific sort-order.
sql server 2008 is the db
update:
there can be infinite parent/child levels - i tried some examples from other stack question/answers but none included a sortorder at the child level.
an example result should be:
parent (sort 0)
    child (sort 1)
    child (sort 2)
    child (sort 3)
        child-child (sort 1)
    child (sort 4)
        child-child (sort 1)
        child-child (sort 2)

etc.
hope this makes sense - maybe i'm looking at this wrong and this sort of result is better to be constructed within the mid-tier?
anyway, any feedback is greatly appreciated
Comment: Can you give an example of what the results are meant to look like?
Answer: Recursive CTE with special sort override. Note the sort override in the children of 2 (I modified the source table slightly to test this ability)
declare @relations table(ParentID int, ChildID int, SortOrder int, treeID int);

insert into @relations values
(0,1,0,0), (1,2,1,0), (2,3,2,0), (2,4,1,0), (2,6,3,0), (1,7,2,0), (1,9,3,0), (9,10,1,0), (9,12,2,0) --tree 0
, (0,1,0,1), (1,2,1,1), (2,3,2,1), (2,4,1,1), (2,6,3,1), (1,7,2,1), (1,9,3,1), (9,10,1,1), (9,12,2,1) --tree 1

; with cte(ParentId,ChildId,SortOrder,depth,agg,treeID) as (
    select null,ParentId,SortOrder,0
    , right('0000000'+CAST(treeID as varchar(max)),7)
        +right('0000000'+CAST(SortOrder as varchar(max)),7)
    , treeID
    from @relations where ParentId=0
    union all
    select cte.ChildId,r.ChildId,r.SortOrder,cte.depth+1
    , cte.agg
        +right('0000000'+CAST(r.treeID as varchar(max)),7)
        +right('0000000'+CAST(r.SortOrder as varchar(max)),7)
        +right('0000000'+CAST(r.ChildId as varchar(max)),7)
    , r.treeID
    from cte
    inner join @relations r on r.ParentID=cte.ChildId
    where cte.depth<32767
    and r.treeID=cte.treeID
)
select
tree=case depth when 1 then cast(ParentID as varchar(30))+' (sort '+cast(SortOrder as varchar(30))+')'
    else REPLICATE(CHAR(9),depth-1)
        + cast(ChildId as varchar(30))+' (sort '+cast(SortOrder as varchar(30))+')'
    end
from cte
where depth>0
order by agg
option (maxrecursion 32767);

Result:
tree
--------------------------------------------------
0 (sort 0)
    2 (sort 1)
        4 (sort 1)
        3 (sort 2)
        6 (sort 3)
    7 (sort 2)
    9 (sort 3)
        10 (sort 1)
        12 (sort 2)
0 (sort 0)
    2 (sort 1)
        4 (sort 1)
        3 (sort 2)
        6 (sort 3)
    7 (sort 2)
    9 (sort 3)
        10 (sort 1)
        12 (sort 2)

Comment: Hi Andre. Looks like you like challenging problems:)
This may be bit of a contrivance, but I added a 0-based treeID to allow for multiple matching roots. I modified the above solution to show two outwardly identical trees that are distinguished only by their treeIDs.
Comment: wow - this is going to take a bit of time to study :) thanks for the great answer
Comment: Hey John - using your example here and struggling with something (probably trivial). How would I modify this statement so that I can store multiple trees in the table? meaning, this currently works great if I only have ONE master root (where parentid = 0), what if i wanted to store a seperate tree (parentid = 0 as well) and get the three below it using "from @relations where ParentId=0 and childid = 45) - currently this does not seem to work with this statement? hope this makes sense
Answer: sounds almost identical to another I answered here  You'll have to alter the order by a little.

sql parent child tree with sort order


std::string optimization?

Question: Someone want to explain me which code is faster ? and what is the best way to optimise a string assignment ?
code 1 :
std::string result;

int main()
{
   for(int i=0;i<1000;i++)
   {
   /*some code*/
   result = stringVar;
   /* some code using result */
   }
}

code 2 :
int main()
{
   for(int i=0;i<1000;i++)
   {
   /*some code*/
   std::string result = stringVar;
   /* some code using result */
   }
}

And to assigne value :
std::string var;

var.assign("value");
//or
var="value";

And it's possible to release memory used by the value before to add a new one ?
Thank if you can help me to understand that :)
Comment: Measure it and find out.
Comment: @user1765211: Then you should focus on developing those skills.
Comment: Which is faster? Check the disassembly.
Comment: I believe it's called an "assignment".
Comment: chris, it's out of my skill :(
Comment: Ed S. it's for that i ask some questions on stackoverflow ^^
Answer: In the case of:
for (...)
    std::string result = blah;

the compiler must construct and destruct result each time through the for loop, probably requiring heap allocation and deallocation calls.
In the case of:
std::string result;
for (...)
    result = blah;

the string implementation might be able to optimize some heap allocation and deallocation away by only reallocation when blah is to big to fit in result's current buffer.
var=x and var.assign(x) should result in the same code; I would not expect a substantial difference either way.
Answer: The first is probably somewhat faster, because it can re-use the allocated memory from the previous pass; the second one destroys the string at the end of each pass through the loop, so frees the storage for the content of the string. An optimizer that keeps the object around, despite it being defined in the loop body, is violating the language rules.
Answer: In Code 1, operator= will be called, this is usually implemented by creating a temp object (using copy constructor) and then swapping the guts of the temp object with the lhs object. So a copy constructor, a swap, and a delete of the temp object (when the method operator=() exits) is done in code 1.
In Code 2, a copy constructor is called, and finally the object will be deleted when the for loop pass ends.
So Code 1 has the extra step of swapping the guts of the string class. Although the implementation of operator= might be not as described above for some string libs and so the best advise is to test it for your environment.

std::string optimization?


Under bathroom sink piping (exposed)

Question: We are looking at setting up the piping for under our wall mounted sink (no vanity, ie, piping will be exposed). And after our contractor finished putting the wall we noticed that the hole from the wall is not going to be aligned with the hole from the sink (faucet is wall mounted and cannot be moved, so we need to deal with the way it is).
We would like to use the below p-trap (purchased already, but can be returned if it is not going to work).

We have sketched below our layout with some dimensions.  If anyone has any suggestions as to what sort of pipes (ideally chrome finish to match the p-trap) we can use to get, somehow, an acceptable result.

Suggestions are welcome
Thanks
PS: We cannot break the wall and re-route the drain pipe as there are pipes on the way, so whatever we do has to be outside the wall (ie.: visible), we will likely put a shelf for towels below that could help cover a bit the piping.
Answer 1 layout:
Thank you bcworkz for your answer, can you let me know if the below is what you are suggesting? Also, what sort of adapters would you use for the joints (at the wall top end and around the hole in the wall).  Thanks again

Final Product
Hi guys, first wanted to thank you bcworkz for your answer. Find below the final product. We might end up putting up a small shelf that will fill with spare towels to cover that extra piping the back.
Comment: That first picture you included is not a P trap..
Comment: What is the question? Do you need help installing the pipes, designing the layout, or something else?
Comment: I'm asking for suggestions on pipe sections that i could use, in conjunction with that p-trap and my layout.
Comment: ... and I guess designing the layout.
Comment: What are the dimensions of the trap?
Comment: Apologies, not sure how you call that sort of trap, on their website they call it P-Trap and Pop-Up drain (http://www.kraususa.com/parts/bathroom-sinks/pt-50-pu-10ch-p-trap-and-pop-up-drain-chrome-1.html#box-Specifications)

The dimensions are: lenght 15in, depth 7in.  I am not home at the moment, but i am guessing 15 in is the measure from hole of the sink to bottom of the trap.
Answer: That's a drum trap, not a P-Trap. Be sure it's listed to comply with your code requirements. Looks slick anyway. You'll need a 45 degree chrome compression ell and maybe some extra pipe. You'll end up with the trap arm out of the drum running at a 45 degree horizontal angle to the wall. It will be cut quite short before it enters the ell. Upon exiting the ell, it should be a straight shot to the wall connection. The remaining trap arm you cut off may or may not be long enough for this. It then ties into the wall pipe with the same adapter fitting you would normally have used.
The trap arm runs entirely horizontal, despite the ell, with just enough slope to drain (1/4" per foot). The only significant vertical drop is in the tail piece that drops straight down from the sink. If you prefer the 45 degree segment to be closer to the wall, you could do a variation using two 45 degree ells, such that the trap arm out of the drum goes straight back for a distance before making a dog leg to the wall drain.
Comment: I have modified my question to include what I understand your layout is.  what adapters do you recommend I use for the other joints (top wall and around the hole on the wall)
Comment: Also, i have just noticed that i can rotate the trap so that the horizontal pipe that comes out of it can be at an angle. Knowing this, what pipe join connectors to you suggest we use for: 1. join the pipe that is in the hole in the wall and 2. the join of the horizontal pipe and the pipe that comes straight up from the hole. Thx

Under bathroom sink piping (exposed)


Refresh Angular JS Factory without page Re-load

Question: I'm accessing data stored in local storage through factory in angularjs. On page load the factory loads and accesses data from local storage and stores them in variables. I'm able to call that factory and fetch the value in the variables.
However whenever I call the factory after localstorage values have been changed the factory returns the old value instead of the new value. Is there a way to refresh the factory so that it again fetches the local storage values without refreshing the entire page?
Javascript Code..
headerApp.factory('userFactory', ['$rootScope', function($rootScope){
    var dataFactory = {};
    dataFactory.user = localStorage.getItem("valueA");
    dataFactory.userName = localStorage.getItem("valueB");
    dataFactory.userAccessToken = localStorage.getItem("valueC");
    return dataFactory;
}]);

On calling userFactory.user, userFactory.userName after a function changes localstorage values returns old values instead of new ones. Please Help
Comment: As long as your local storage value gets changed and later whenever you try to access that values through factory/service its suppose to be take newly updated values. If its not theb I'm not sure I understood your point completely.
Comment: And yeah you could store your local storage value whenever its change and set it into factory and then try to access
Comment: Well, you can have an update method in factory which gets the latest data from local storage and update variables. You can call this method whenever you update local storage.
Comment: Why do you update the data directly through localStorage, not through the service?
Answer: How about moving the code where you are pulling info from your local storage into a function in the factory, and then any time you update any of the local storage, you call that function to update the dataFactory too?
headerApp.factory('userFactory', ['$rootScope', function($rootScope){
  var dataFactory = {};

  this.updateUser();
  this.updateUserName();
  this.updateAccessToken();

  updateUser () {
    dataFactory.user = localStorage.getItem("valueA");
  }

  updateUserName () {
    dataFactory.userName = localStorage.getItem("valueB");
  }

  updateUserAccessToken () {
    dataFactory.userAccessToken = localStorage.getItem("valueC");
  }

  return dataFactory;
}]);

And then at any point, say the user name got changed on the local storage end, you can call this.userFactory.updateUserName(); to update dataFactory.userName.


Run Time Estimate/Big O Notation for Nested For Loop

Question: I'm having trouble understanding the meaning of a function f(x) representing the number of operations performed in some code.
<code>int sum = 0; // + 1
for (int i = 0; i < n; i++)
    for (int j = 1; j <= i; j++)
        sum = sum + 1; // n * (n + 1) / 2
</code>
(Please note that there is no 2 in the numerator on that last comment, but there is in the function below.)
Then my notes say that f(x) = 2n(n + 1) / 2 + 1 = O(n^2)
I understand that because there are two for loops, that whatever f(x) is, it will be = O(n^2), but why is the time estimate what it is? How does the j<= i give you n*(n+1)? What about the 2 in the denominator?
Answer: Think about, across the entire execution of this code, how many times the inner loop will run. Notice that

when i = 0, it runs zero times;
when i = 1, it runs one time;
when i = 2, it runs two times;
when i = 3, it runs three times;
...; and
when i = n - 1, it runs n - 1 times.

This means that the total number of times the innermost loop runs is given by

0 + 1 + 2 + 3 + 4 + ... + (n - 1)

This is a famous summation and it solves to

0 + 1 + 2 + 3 + 4 + ... + (n - 1) = n(n - 1) / 2

This is the n - 1st triangular number and it's worth committing this to memory.
The number given - n(n + 1) / 2 - seems to be incorrect, but it's pretty close to the true number. I think they assumed the loop would run 1 + 2 + 3 + ... + n times rather than 0 + 1 + 2 + ... + n - 1 times.
From this it's a bit easier to see where the O(n2) term comes from. Notice that n(n - 1) / 2 = n2 / 2 - n / 2, so in big-O land where we drop constants and low-order terms we're left with n2.
Comment: @willywonkadailyblah Mostly just trying to help out! This is the sort of thing that looks totally mysterious if you don't know where it comes from and don't know what to Google.
Comment: still trying to earn those small reps eh template :D


Titanium memory leak in master/detail demo application

Question: I had little experience with titanium. Basically I need master/detail application same as demo version available at git or in sample titaniumstudio
Here is the part which i think has leak
masterView.addEventListener('itemSelected', function(e) {
    //create detail view container
    var detailView = new DetailView();
    var detailContainerWindow = Ti.UI.createWindow({
    title:'Product Details',
    navBarHidden:false,
    backgroundColor:'#ffffff'
    });
    detailContainerWindow.add(detailView);
    detailView.fireEvent('itemSelected',e);
    detailContainerWindow.open();
});

Logically Every time when the table row click,a detailview should be created and will destroy on back button press. But as tested on android device .. on every click of tableview memory taken by this application was increased. I think titanium taking new detailview every time but not destroying the old one which is keep running in backend.
please tell me if is it a bug or i had mistaken something.
Comment: Can't you create a window outside the event and create/add detail view inside the event?
Comment: @Muhammad Zeeshan Yes I had tried for it. Because its great to use same window every time. but it gives me another strange behavior.. It runs for the first time but from the next time it is showing the blank window. If we put the alert in handling event. it fired the alert but application is still blank.
Comment: Are you closing the window on back button event?
Comment: No, I had used only the sample application code. there is no back button event code.
Answer: I have found the solution for all my memory problems with this:
var memPool = Ti.UI.createWindow();
memPool.open();
memPool.hide();
memPool.add(yourTrashView);
memPool.close();

Explained here:
http://developer.appcelerator.com/question/116867/this-is-a-solution-to-your-memory-woes
Comment: hey Mike thanks for the Answer.. I had seen this link before..
I need to Open 2 windows which will swap focusing on each other with an event occurrence ..on Swap, emulator showing new resources are loading which I think real reason for this memory increased. Ending Up with your solution which includes quite delay in app.. hope it resolve in new mobilesdk version..
Comment: I use this solution in the same situation (with some webviews in the detailView) and I dont have problems with delay. I think you should try.


Automatonyous state machine, generate graph from code

Question: I'm using Automatonyous state machines in my c# project.
I'm wondering if there is a way to automatic obtain the graph of coded state machines.
Comment: https://github.com/MassTransit/Automatonymous/tree/master/src/Automatonymous/Graphing ??
Comment: Yes, it seems that this code could generate an object representing the state machine graph. Now, for me, the question is: does exist an example that explain how to use this object representing the state machine graph to obtain a drawing of this graph?
Answer: You can generate a GraphViz .dot file from the state machine using the Visualizer assembly.
https://github.com/MassTransit/Automatonymous/blob/master/src/Automatonymous.Tests/Visualizer_Specs.cs#L30
UPDATE
With MassTransit v8, this has moved into the MassTransit.StateMachineVisualizer NuGet package.
And the unit test is here.
Comment: Thank you very much! This is exactly what I searched for!
Comment: in case someone else stumbles here, the updated link is https://github.com/MassTransit/Automatonymous/blob/bc03484ac2cef256c711817569260a22d454522c/tests/Automatonymous.Tests/Visualizer_Specs.cs


Multiplayer survival on PS4?

Question: This month, Killing Floor 2 is part of the PS+ game of the month.
I grabbed it and liked the solo play, and wanted to play survival with friends.
However, whatever options I try (public/private, all maps/selected map, difficulty...), the matchmaking server will never find a session, and it seems it doesn't create one either.
On the other hand, Survival VS work almost instantly.
How do I create a private session and play survival (not VS) with one or two friends on PS4?
Edit:
The questions is not "How do I create a multiplayer match", but why is the normal Survival mode is bugged, and if there is a workaround to this bug. Or where to find, if available, information about that bug, since KF2 website doesn't reference that bug.
Comment: I've heard that matchmaking for KF2 (at least on PS4) can be buggy.
Answer: It's pretty straightforward actually.

Hit online matchmaking.
Go to permissions and hit friends only.
Go to the right hand side and invite, or invite via PS4 menus.

If you want a reference, watch this video.
Comment: @DrakaSAN unless something has changed since I played KF2 on my PS4 months ago, this should be correct. I can go and verify this answer later if you'd like.
Comment: That bit work well on Survival VS, and I can invite in Survival too, but the game will never start. My question was more about why the normal Survival doesn't work, and where/if there is information about how/when it will be fixed, since it seems to come from the server side
Comment: I'm not sure otherwise what you mean, Survival VS and Survival normal? This works for both modes
Answer: After more research on fan forums, I found out that due to the PS+ offer, the European and American servers are overloaded.
A solution proposed was to select Australian server, wich are playable, however, the ping is awful.
Comment: Which doesn't make sense because when you're playing with friends and setting the permissions to friends only you're essentially assuming control of the server and hosting. As far as I understood. Maybe I missed something.
Comment: I don't understand either why it doesn't work on private party, but well, I at least have a workaround.
Comment: @n_palum you can choose zu host  (I dont remember how the option is called) but that is not the default and even if you select it, you probably wont be able to find a server for your self hosted Lobby. As far as I know, you still use the actual game servers to host a game.

Multiplayer survival on PS4?


Python GTK/threading/sockets error

Question: I'm trying to build a Python application using pyGTK, treads, and sockets. I'm having this weird error, but given all the modules involved, I'm not entirely sure where the error is. I did a little debugging with some print statements to narrow things down a bit and I think the error is somewhere in this snippet of code:
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.connect(("localhost", 5005))
    self.collectingThread = threading.Thread(target=self.callCollect)
    self.collectingThread.daemon = True
    self.collectingThread.start()

def callCollect(self):
    gobject.timeout_add(500, self.collectData)

def collectData(self):
    print "hello"
    try:
        print self.sock.recv(1024)
    except:
        print "except"
    print "return"
    return True

So basically what I'm trying to do is setup a socket, connect to a "server" script (which is really just another python script running locally), and create a separate thread to collect all incoming data from the server script. This thread is set to run the collectData method every 500 milliseconds.
After inserting the print statements into the collectData method here is what I notice when running the program:
-Initially the GUI is fully functional
-then the following is printed in the terminal:
hello
**all data received from server script and printed here**
return
hello

-after the text is printed in the terminal, the GUI becomes completely nonfunctional (buttons cant be pressed, etc.) and I have to force quit to close the application
What seems to be happening is that the thread prints "hello", prints the data from the server, and prints "return". 500 milliseconds later, it runs the collectData method again, prints "hello", then tries to print data from the server. However, because there is no data left it raises an exception, but for some unknown reason it doesn't execute the code in the exception block and everything just hangs from there.
Any idea on what is going wrong?
Answer: timeout_add is scheduling the action to happen on the main thread -- so the recv just blocks the main thread (when it's just waiting for data) and therefore the GUI, so, no exception unless you put a timeout or set the socket to non-blocking.
You need to delegate the receiving to the thread from the scheduled action rather than viceversa to get the effect you're after: have the thread e.g. wait on an event object, and the scheduled action signal that event every 500 milliseconds.
Comment: It's "timeout_add", not "timeout_call".
Comment: How exactly would I explicitly tell the secondary thread to wait on an event object and its corresponding signal? I checked the pyGTK tutorial for different events but couldn't find anything on sockets. Sorry, I'm very new to pyGTK.
Comment: @pythonBOI, I was thinking of Python's `threading` module, not GTK -- see http://docs.python.org/library/threading.html#event-objects -- make a global event object `x` with `x = threading.Event()` before creating the subthread, have the subthread block waiting for `x` by calling `x.wait()`, have the main thread wake up the subthread via `x.set()` (then put the event object back to rest state by calling `x.clear()`).  No necessary connection w/sockets or with GTK, just general-purpose Python threading stuff!
Answer: No, obviously the sock.recv call blocks because the socket wasn't closed yet and socket receives are blocking by default. Make sure you close the connection at some point.
It would make more sense to run the receive call in a new thread, or else it might block the GUI because your current implementation runs the recv call in the GUI thread (using timeout_add). The way you're currently doing it only makes sense if the answer is received very fast and/or you have to access widgets.
By the way, creating a new thread for calling gobject.timeout_add is totally unnecessary. timeout_add() and idle_add() register the specified callback function and return immediately. The GTK event loop then automatically executes the callback after the timeout (or on idle status for idle_add).
Comment: Would it be enough to just set the socket to non-blocking and leave everything in the same thread? And could I leave the socket open (so it could continue to receive data) and close it when the user attempts to close the window?
Comment: @pythonBOI: That would be more of a hack, but works if you don't have a lot of sockets like that. You cannot open an infinite number of sockets, so you should close the socket at some point. I don't know which communication protocol you're using so I can't help you with that.

Python GTK/threading/sockets error


Originate command with originate_retries in Freeswitch

Question: While executing the below command on Freeswitch, I got the 4 times retry to 1002 while I set it to only 2 times.
originate {ignore_early_media=true,originate_continue_on_timeout=true,originate_timeout=30,originate_retries=2,originate_retry_sleep_ms=60000}user/1002 &bridge(user/1005)
Can anyone suggest me about this problem?
Comment: What happens if you set the retried to 1?
Comment: it will not retries.
Comment: @suren did the given answer solved your problem..!
Answer: originate_continue_on_timeout will reset your timeout, so remove it from global variable. Probably what you want is

{ignore_early_media=true,originate_timeout=30,originate_retries=2,originate_retry_sleep_ms=60000}user/1002
  &bridge({originate_continue_on_timeout=true,originate_timeout=30}user/1005)

Not tested it but should work
Comment: so i mentioned in answer that dont use it  ```globaly```...```[]``` is used to define variable ```locally```. You can either use ```[]``` or define variable with each ```leg```. Anyways happy that you solved your problem... :)
Comment: its working for if no answer by the extension on retry but it should also work on retry on busy.if call is busy then it again retry more then retries.
Comment: @suren ```originate_continue_on_timeout``` primary purpose is to dial next extension(user) if cant connect to current one...I would suggest you to try with 2 3 extension(user), and to check if other user is getting connected in case of first one got timeout.
Comment: thanks for your information but solution is done by myself.basically what i was doing using currly braces to set origination_retries but there should be square bracket. and our concern was not about originate_continue_on_timeout.


wiring a fan to an existing switch that also controls an outlet

Question: I have an existing switch that controls the lower half of an outlet we use for a floor lamp.  no other lights or fan in the room.
If I use a triple rocker how can I wire the switches to control a fan light combo on the ceiling?
Can I draw power from the switch?
How do I maintain the switch control of the outlet but also use the same box??
I would run 14/3 from the switches to the light and fan.  But and unsure what wires go where and get pigtailed ect.  A diagram would be appreciated
Comment: If your plan is to run wires to the ceiling fan/light unit from the existing switch box you need to first ensure that there is a neutral conductor available in the switch box. Older homes often have only "hot" and "switched hot" conductors in the switch box, no neutral. If you do not understand this... you need to do some basic study of common household electrical circuits before attempting this job, or hire an electrician.
Comment: Turn off the power at the breaker. Remove the switch cover plate. Remove the switch mounting screws, and gently pull the switch out of the box.  Take some photos, or draw a diagram depicting the wiring within the box. Then post the photos/diagram here.
Comment: hope the photo helps tester101
Answer: You currently have two cables in the box. One is the power source, and has just a black (hot), a white (neutral) and a bare (ground) wire. The second cable has a black (hot), a red (hot), a white (neutral) and a bare (ground).
As currently wired, the incoming black is attached to the outgoing black and to the switch via a pigtail. This makes the unswitched half of the outlet always live and provides a hot connection to the switch. The red wire is attached to the other side of the switch and provides a switched hot to the second part of the outlet. The neutrals are connected together in the box and the white wire at the outlet itself covers both halves of the switch (only the hot side has separate connections).
Adding other switched lines is fairly straightforward (this assumes that you have sufficient amperage to cover the additional fan and light).
As you surmised, you need a three wire (plus ground) cable. The new white is connected to the existing whites. If you pick a triple switches with a common hot terminal (most are configured this way), just move the existing hot pigtail from the old switch to the common terminal on the new switch. This provides hot to all three switch units. Then attach the red wire for the outlet to one of the other switch terminals, and the new red (from the fan or light) to another switch terminal and the new black (light or fan) to the last terminal. You can swap these three wires to assign whichever switch unit you want to each device.
Connect all ground wires together.
You are good to go.
[I will try to add a diagram later if I have time.]


Opacity in Hex colors of CSS

Question: How to apply opacity in Hex colors ?
I am working with CSS Hex colors. I am trying to apply opacity in Hex colors. I need #78909c with opacity 0.2.
Answer: The hex representation of colors supports the alpha channel to set opacity.
so, take any color in hex e.g. #ffffff and append 00 to ff (in hexadecimal representation) for opacity, i.e. #ffffff00 - #ffffffff
for your color: #78909c33
20% implies 33 in hex
Here is a demo
Reference: Hexadecimal notation
Comment: Since its hex it does not ends at 99 it ends at FF, and its not a decimal basis value.
Comment: Your welcome, yes it's totally accurate now.
Comment: Thanks @CihanUygun, I have updated the answer, I hope it's accurate now.
Answer: HEXA - #RRGGBBAA
There's a relatively new way of doing transparency, it's called HEXA (HEX + Alpha). It takes in 8 digits instead of 6. The last pair is Alpha. So the pattern of pairs is #RRGGBBAA. Having 4 digits also works: #RGBA
I am not sure about its browser support for now but, you can check the DRAFT Docs for more information.

§ 4.2. The RGB hexadecimal notations: #RRGGBB The syntax of a
 is a  token whose value consists of 3, 4, 6,
or 8 hexadecimal digits. In other words, a hex color is written as a
hash character, "#", followed by some number of digits 0-9 or letters
a-f (the case of the letters doesn't matter - #00ff00 is identical to
#00FF00).
8 digits The first 6 digits are interpreted identically to the 6-digit
notation. The last pair of digits, interpreted as a hexadecimal
number, specifies the alpha channel of the color, where 00 represents
a fully transparent color and ff represent a fully opaque color.
Example 3 In other words, #0000ffcc represents the same color as
rgba(0, 0, 100%, 80%) (a slightly-transparent blue).
4 digits This is a shorter variant of the 8-digit notation, "expanded"
in the same way as the 3-digit notation is. The first digit,
interpreted as a hexadecimal number, specifies the red channel of the
color, where 0 represents the minimum value and f represents the
maximum. The next three digits represent the green, blue, and alpha
channels, respectively.

For the most part, Chrome and Firefox have started supporting this: enter image description here

Opacity in Hex colors of CSS


JavaScript: Use Join to Make Array a String Using Input Argument as Separator Btw Words --> Replace Error

Question: I have the following code:

function myJoin(array, separator) {

  let newStr = array.join(separator).replace("\", "")

    return newStr

  }

  myJoin(['let\'s', 'make', 'a', 'list'], ' ');

I expect the output to be: "let's make  a list" but instead it gives me an error.
evalmachine.<anonymous>:21
  let newStr = array.join(separator).replace("\", "")
                                                   ^^
SyntaxError: Invalid or unexpected token

What's wrong with my replace method?
Comment: `array.join(separator).replace("\\", "")`
Answer: The problem is with "\". The backslash escapes the end quote, meaning the string is unclosed. It should be "\\" instead.
Here's a code example:

function myJoin(array, separator) {
  const newStr = array.join(separator).replace('\\', '')
  return newStr
}

const result = myJoin(['let\'s', 'make', 'a', 'list'], ' ')
console.log(result)

If you're interested, here's an article on escape characters.
Comment: @PineNuts0 No, it doesn't. I just added a console.log, you can run it to check.
Answer: You don't need replace()
The \ in your string isn't really a character — it's part of an escape sequence. As a result, you don't need to replace it unless you are trying to replace actual, literal backslashes in the string. This does what you would expect:

function myJoin(array, separator) {
    return array.join(separator) // you don't need replace here
}

console.log(myJoin(['let\'s', 'make', 'a', 'list'], ' '))

Answer: You are escaping the " inside of your replace, you have to use 2 backslashes, ie: \\. Also, replace() is not a function for arrays, this must be done on a string, so you must also swap put join() before replace().
This will do the trick:

console.log(['let\'s', 'make', 'a', 'list'].join(" ").replace("\\", ""));

It looks like you would like this to be applied to array's  specifically, how about prototypes?

Array.prototype.replace = function(separator = " ") {
  return this.join(separator).replace("\\", "");
};

// Can be called like so
console.log(['let\'s', 'make', 'a', 'list'].replace(" "));
Answer: The problem is "\". Backslash is a quoting character in JavaScript which causes the next character to be treated literally.  You need to write "\\" to create a string of one backslash character.


Map a number to an id in python

Question: Suppose I have a numpy array like: [11, 30, 25]. These numbers represent categories of the objects corresponding to the indices. I know there are just 20 categories but for some reason they are numbered from 11 to 29. I'd like to convert them to numbers in 0:19 and back. What would by a pythonic way to do this? Preferably in bumpy.
EDIT: this is just a small example of a bigger problem, where the number of categories are in the thousands, and some categories are never represented, so the maximum id will be the number of unique existing categories.
Comment: Subtract `11` from them?
Comment: Just to top @Divakar: subtract `my_array.min()` ;)
Comment: Now that you've edited your question, it's no longer trivial. It's unclear instead.
Comment: @Divakar is that only 0~18?
Comment: would an `sklearn` solution be ok?
Comment: any solution would be fine
Comment: the question is, if it is unique, what is compelling you to convert them as zero indexed ? You can always enumerate or figure out another way to iterate
Comment: @karthikr I'm not sure what you mean
Comment: See if this works for you : `np.unique(input_array,return_inverse=True)`. This would ID each category starting from 0 until `N-1`, where `N` is the number of categories.
Comment: @Divakar that does the conversion from the categories to id. How would I go from id to categories?
Comment: This is either getting surreal or I have no idea what is going on.
Comment: say now I have a new array containing categories and a new array containing ids. How do I convert one to the other, given the ```unique``` and ```inverse``` arrays from ```np.unique```?
Answer: Let's say arr is the input array of categories.
Forward Process/Encoding : From categories to IDs
To perform the encoding, use np.unique alongwith its optional return_inverse argument to give us IDs that would have values from 0 to N-1, where N is the number of categories you would have in arr , like so -
unq,idx = np.unique(arr,return_inverse=True)

Backward Process/Decoding : From IDs to categories
To go back to the original categories from the IDs (idx), just index into unique categories saved earlier as unq, like so -
arr_out = unq[idx]

Sample run -
In [40]: arr # Input array of categories
Out[40]: array([7, 1, 1, 3, 8, 2, 7, 7, 0, 2])

In [41]: unq,idx = np.unique(arr,return_inverse=True)

In [42]: idx  # ID array with values from 0 to 5 (6 categories)
Out[42]: array([4, 1, 1, 3, 5, 2, 4, 4, 0, 2])

In [43]: unq[idx] # Get back original array of categories
Out[43]: array([7, 1, 1, 3, 8, 2, 7, 7, 0, 2])

Answer: To be able to easily convert back-and-forth, I would use the sklearn.preprocessing module LabelEncoder:
In [7]: from sklearn.preprocessing import LabelEncoder

In [8]: encoder = LabelEncoder()

In [9]: encoder.fit(range(11,31))
Out[9]: LabelEncoder()

In [10]: encoder.transform([11,30,25])
Out[10]: array([ 0, 19, 14])

In [11]: encoder.inverse_transform([18, 1, 15])
Out[11]: array([29, 12, 26])

Comment: This one is elegant but it makes my ipython notebook kernel die. I have about 10000 categories.

Map a number to an id in python


In a google glass why are past events moved to right of the main menu?

Question: Generally in a time line users would image past events to be on the left, current events in the center and future on their right.But Google glass's timeline seems to be little intriguing as it has past events on the right.Is there any reason behind its design? or is my assumption of a timeline wrong?
Example (or watch a video on youtube):
Answer: I've not used Google Glass but I'd imagine that since the cards feel like a band around the head, then swiping backwards should feel like you're physically swiping the cards into the past (as if to throw them behind you) in order to be able to see what's coming up.
Conversely swiping forwards has to do the opposite.
So it's probably a mistake to see it as a traditional timeline. It's not. Better to see the cards as real interactive content and let them naturally relate to how they are presented and the swipe actions available. Another example of the content is the interface?
Have you used glass? Does it feel wrong? I doubt it!
Comment: Yeah i have used glass, you need to swipe forward for past events and backward for present and future events which I felt was a little odd..I would always imagine future events to my right..
Answer: I think you're making comparison with how timeline is being presented in real life.
You could ask the same question why Facebook, Google+, or any other timeline based apps, present the latest event at the top and past events below.
First and foremost, in designing how information is being presented to the user, we need to understand what the user is most interested in. In such apps, our user is most interested with latest event, which would then be presented first in the list, be it horizontal or vertical. Past events are usually of second importance level, which would then be listed in reverse chronological order after the first in the list.
Reading top-down and left-right are the most natural way (except for RTL languages). So you'd then present your information from latest to oldest in top-down or left-right manner.
You can definitely refer to how Windows 8 apps present information horizontally.
On a side note, when looking at historical timeline, you're usually more interested to find out how something started and got to the way it is/was eventually. Hence, oldest to latest in left-right or top-bottom manner.
Hope that answers your question.
Comment: Your view is perfectly valid.. What confused me was in usual timelines you l always be on top say the latest and then you move down.. But here you are in the middle..and not with the latest happening..
Comment: May i know what's to the left of the Now card? Is it related information? Or its just something that's totally irrelevant?
Comment: It is relevant information..the current and future events..


What was the Maelström of Chaos before patch 0.9.11?

Question: I've been playing PoE since open beta only, so I'm used to maps as the end-game content. However, from what I read, before maps were introduced in patch 0.9.11, some area called the Maelström of Chaos served as the end-game content. I have also read that it was made from different tilesets, but I cannot find any exact information about it.
So a question to those who played in closed beta: what was the Maelström of Chaos?
Answer: The Maelstrom of Chaos was a series of random areas, with random monsters that increased in difficulty the further in you went.
You can find all the info on how and why it was created straight from GGG here.
Specifically, you are looking for the section marked:

History of Path of Exile's End-Game
we realised that the fourth difficulty
  level was only necessary until we added Act Three, at which point we'd
  reduce it back to three difficulty levels so that we're not forcing
  the player to play through the same static content four times
  back-to-back. Our temporary solution, a month or so before entering
  Closed Beta last year, was to introduce the Maelstrom of Chaos areas.
  These were a sequence of random areas (using tilesets from all over
  the game) with completely random monster packs. Players gained access
  to it when they finished the final difficulty and could play through a
  series of levels that gradually ramped in difficulty.
Comment: I actually haven't played PoE lately, so I haven't done any maps.  MoC was literally "pick an area from the game, pick some enemies".  If you cleared that map, it got harder.  Apparently they changed that and made it so it spawned more bosses instead of getting harder at some point, but I don't remember that.
Comment: Have you played it? Can you compare it with the maps as they stand now?


Is it legal to return by value an object with a deleted copy constructor?

Question: Is it legal to return by value an object with a deleted copy constructor? For example, consider an object with an std::unique_ptr member. Most compilers do not complain when returning such objects by value because in most cases the compiler won't even look for the copy constructor. However, since (N)RVO is not required by the standard, is it okay to say that such programs are legal? Is std::move in the return statement necessary for standard compliance in these cases?
Comment: You might consider this a duplicate: http://stackoverflow.com/questions/32844948/stdmove-and-rvo-optimizations
Comment: And you do not need the move, the result of the function is an r-value anyways.
Answer: If you have a working move constructor, you may delete the copy constructor.
The following program works for me.
struct Foo
{
   Foo() = default;
   Foo(Foo const&) = delete;
   Foo(Foo&&) = default;
};

Foo test()
{
   Foo f;
   return f;
}

int main()
{
   Foo f = test();
   return 0;
}

Comment: @xiver77 Yes, it does.
Comment: @chessprogrammer, I haven't been able to isolate the specific paragraph/sentence in the standard that makes this legal. I suspect it's somewhere there in [12.8 Copying and moving class objects](https://timsong-cpp.github.io/cppwp/n4140/class.copy).
Comment: Does this work without NRVO?
Comment: @xiver77 The compiler must reject any program that would not compile if copy elision were disabled
Comment: I know this is an old question but could you explain why this is legal?


How do I access the global market in SimCity?

Question: I'm unable to find any real documentation if this feature is even released yet as part of SimCity 2013.
Is there a way to access the global market within SimCity World? Apart from just selling commodities though my trade depot I was under the impression there was a way to do analysis and look at trends in market prices.
When I go to SimCity World I only have Leaderboards and Challenges. At least one of my cities in the region has a Trade HQ.
Answer: The global market tab was originally designed to be a part of the Sim City World window next to the "Leaderboards" and "Challenges" tabs but it was removed before release of the game.
Here is a pre-release version of the window:

Currently it appears that prices of goods do not fluctuate on the global market although on release day the prices were fluctuating seemingly randomly so it is likely a feature Maxis is tweaking to reduce server load.
Comment: So I guess it's pretty difficult to see the pricing trend of a particular commodity since this window is removed? Right now oil is around 4.5k per 1k of barrels so getting the daily 160k of petroleum commerce is a task in itself.
Comment: @Matthew you are correct. As far as I know, theres currently no way to see the trends.
Comment: Yes, at the moment there are no trends.
Oil is §4,500 / 1000 barrels, Alloy is §48,375 / 10 tons, and Plastic is §12,003 / 1k crates


Jsfiddle's new UI broke my angular and javascript fiddles

Question: My jsfiddle that was using angular broke with their new UI updated. Can anyone please tell me why it's not working or what it's missing? I am very confused about this.
var shopItems = angular.module('shopItems', []);
var trophyEarns = angular.module('trophyEarns', []);
var app = angular.module('app', ['shopItems', 'trophyEarns']);

shopItems.controller('shopItemController', function($scope) {
  $scope.shopItems = [{
    //id: 01,
    name: 'One',
    //img: '',
    price: '$3.99',
    altprice: '1 mile',
    desc: 'This is a fake description.',
    prog: '50%'
  }, {
    //id: 02,
    name: 'Two',
    //img: '',
    price: '$3.99',
    altprice: '1 mile',
    desc: 'This is a fake description.',
    prog: '50%'
  }];

});

http://jsfiddle.net/galnova/rfg80gye/32/
Comment: Are you saying that *existing fiddles that used to work* broke? That would mean they lost the fact that you'd previously chosen one of the "no wrap" options. If that's the case, you'll want to report it as a bug, it won't just be angular fiddles that break.
Comment: Your initialization code is running in a "load" handler. Change the setting to "No wrap (in body)".
Answer: It's that business of jsFiddle defaulting to the mind-bogglingly-surprising "wrap all of the code in a giant window.onload = function () { ... }; wrapper" setting.
Just click the word JavaScript and select "No wrap - in " (or "No wrap - in ") in the "Load Type" field:

jsFiddle has always had that setting, and onLoad has always (well, at least for several years) been the default for it. It's just moved in the new UI.
Updated fiddle: http://jsfiddle.net/rfg80gye/33/


Placing the Attach Image button

Question: I'm designing a mobile screen (iPhone and Android) for adding a review; my sense is that the 'Attach Image' button is not placed correctly or shouldn't be as big button as 'Submit Review'. Please see the image below.
How can I make this 'Attach Image' button look better?

Capture #1
Capture #2
Answer: I think it's a hierarchy problem, you are creating a couple of subfields for text editing and two CTA buttons at the same level, when one of these buttons belongs to one of the previous areas. Beyond the use of color or size, I suppose the user must have clear that one button is for the general review action while the other only belongs to an internal part of the edition.
An exaggerated example:

A single total edition field

A submit button

There's a place for thumbnails and more photos can be added:

Example 2

A title editing field
A general content editing field
A Submit button
Comment: Thank for you response. I agree and like the 1st image that you uploaded.
Answer: "Attach Image" is machine-speak; it's more or less how engineers talk about the function that your button is doing, and this looks like an app that is enticing consumers to share.
You could try more user-friendly verbiage such as "Upload Photos", or drop the verbiage altogether and use an icon. The bold purple of your Attach Image button is competing with the red Submit button, and it's not as important of a function, so look at ways to subordinate it. Yelp has a good example of this.
Comment: It's also a good idea. Appreciate it for looking and responding.

Placing the Attach Image button


flutter bloc - wrong state is sent from bloc to widget

Question: It seems like bug in bloc v0.11.2
I have the following Event/State:
class DeleteReceipt extends ReceiptEvent {
  final Receipt receipt;
  DeleteReceipt(this.receipt) : super([receipt]);
}

class ReceiptDeleted extends ReceiptState {
  final Receipt receipt;
  ReceiptDeleted(this.receipt) : super();
}

and the following code in bloc:
if (event is DeleteReceipt) {
  var delReceipt = event.receipt;
  await _receiptDao.delete(delReceipt);
  print("deleting: " + delReceipt.snapshot.documentID);
  yield ReceiptDeleted(delReceipt);
}

and my widget I have:
      if (state is ReceiptDeleted) {
        print("delete: "+state.receipt.snapshot.documentID);
        receipts.delete(state.receipt);
      }

and when I do:  _receiptBloc.dispatch(DeleteReceipt(receipt));
the first time I get:
I/flutter (28196): deleting: AzgAzcn5wRNFVd7NyZqQ
I/flutter (28196): delete: AzgAzcn5wRNFVd7NyZqQ

which is correct, but the second time I do _receiptBloc.dispatch(DeleteReceipt(receipt)); on a different receipt, I get:
I/flutter (28196): deleting: d4oUjrGwHX1TvIDr9L2M
I/flutter (28196): delete: AzgAzcn5wRNFVd7NyZqQ

You can see that in the second time the DeleteReceipt event was received with the correct value, but the ReceiptDeleted State was received with the wrong value, and then it just get stuck like this, it never fires ReceiptDeleted State with the correct value, only with the first value.
My app is not trivial, and I have set many events and state in the past, and it worked with no issue (except this one, that probably is related flutter bloc state not received)
Basically I let the user create photos of receipt, that are persistent (using bloc/firestore), and I want to let the user delete them, so when the user click on a receipt, it opens in a new screen:
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) {
      return ReceiptDetailPage(widget.receipt);
    },
  ),

and when the user click on delete, I show a dialog, and delete the receipt if is OK
var result = await showDialog(
  context: context,
  builder: (BuildContext dialogCtxt) {
    // return object of type Dialog
    return AlertDialog(
      title: new Text(AppLocalizations.of(context).deleteReceiptQuestion),
      actions: <Widget>[
        // usually buttons at the bottom of the dialog
        new FlatButton(
          child: new Text(AppLocalizations.of(context).cancel),
          onPressed: () {
            Navigator.of(dialogCtxt).pop("cancel");
          },
        ),
        new FlatButton(
          child: new Text(AppLocalizations.of(context).ok),
          onPressed: () {
            Navigator.of(dialogCtxt).pop("OK");
          },
        ),
      ],
    );
  },
);
if (result == 'OK') {
  Navigator.of(context).pop();
  _receiptBloc.dispatch(DeleteReceipt(receipt));
}

Answer: Solution:
add state/event:
class EmptyState extends ReceiptState {}
class EmptyEvent extends ReceiptEvent {}

after receiving the delete state do:
      if (state is ReceiptDeleted) {
        print("delete: "+state.receipt.snapshot.documentID);
        receipts.delete(state.receipt);
        _receiptBloc.dispatch(EmptyEvent()); // add this line
      }

and add this to your bloc
if (event is EmptyEvent) {
  yield EmptyState();
}

This will cause an empty event and state to be fired and will clear the problem
Explain: I noticed that once I fire a State, the block provider will send that state every time I change a screen, which is strange since the app is receiving a Delete State many time. this is not a problem in my case, since the code will try to delete an element that is already delete and will fail quietly:
  void delete(Receipt receipt) {
    try {
      Receipt oldReceipt = receipts.firstWhere(
          (r) => r.snapshot.documentID == receipt.snapshot.documentID);
      receipts.remove(oldReceipt);
    } catch (e) {
      print(e);
    }
  }

NOTE: this seems to happen with all State that the app is firing, not only the Delete state
So I guest that if I will fire an empty event, it will clear the old Delete state, and will somehow fix the issue, and WALLA...
Note that I didn't had to actually listen to the EmptyState any where in my code
MORE INFO:
I realize that although the bloc seems to loose state, also my design is wrong, because the Data Structure should be updated in the bloc, once the event is received and not in the widget, when the state is received (or not received in this case, which cause the bug)
Initially I used bloc with sembast, but then I wanted the data to be sync with the remote DB, so I replaced sembast with firestore.
but that causes the load time to go from nothing, to more than 2 seconds, and that is a problem since in the original design I load all the data from the DB on every update.
So I tried to update the store and the UI seperatly, ie. instead of reading all the data, I keep a List in my widget and update the widget when the state changes - per update/delete state.
That was a problem, since many state were lost (especially when the user click fast - which cause many events/states to fire)
So I guess a correct solution would be to manage the in-memory Data in a separate Service, and update the Data when the Event is received, and then read all data from the Service instead of the store (when possible)


Python save XLSX to CSV

Question: I am not a python user. However, I am sick of saving Excel files to CSV manually, and everybody hates Perl at this shop. I can't get Spreadsheet::XLSX to work in this work environment. They only use Python.
The python version is 2.4.
 #!/usr/bin/python

import openpyxl
import csv

wb = openpyxl.load_workbook('DailySnapshot.xlsx')
sh = wb.get_active_sheet()
with open('test.csv', 'wb') as f:
    c = csv.writer(f)
    for r in sh.rows:
        c.writerow([cell.value for cell in r])

The DailySnapshot.xlxs is saved in the same directory a the script. It is a one page excel spreadsheet, and the sheet is called 'Table1'. I figured I would name the CSV file test.csv. This is the error it throws.

File "./secondPyTry.py", line 8
      with open('test.csv', 'wb') as f:
              ^ SyntaxError: invalid syntax
Comment: Is it really python 2.4?  That's _ancient_, and precedes the introduction of the with syntax.
Comment: Yep, looking now it seems like context managers were introduced in 2.5
Answer: As it was said in the comments, Python 2.4 does not wupport with. You should open the file like this instead:
f = open('test.csv', 'wb')
c = csv.writer(f)
for r in sh.rows:
    c.writerow([cell.value for cell in r])
f.close()

Python save XLSX to CSV


Busybox: how to quit Busybox and/or shut down computer

Question: I am on a terminal looking ("pre-boot") screen, in a utility/program called Busybox.
By pre-boot, I mean that I am not booted into the GUI of an operating system.  My computer loaded this utility/program instead of booting into the operating system.
How do I exit Busybox and shut down the computer?
Here is a web page that shows the commands:
https://busybox.net/downloads/BusyBox.html
I couldn't find any quit or exit command.
Comment: You can always just tell the linux kernel to shutdown (ie. SysRq command)
Answer: It's poweroff or poweroff -f.
Also, ash does have an exit command, but the resource you mentioned is for the busybox binary, not the shell.
Comment: Thanks.  Was very helpful and to the point.  Put an end to a frustrating day for me.


SyntaxError: missing } after property list showing on jquery code execution

Question: I have written a simple jquery code for shifting a div of buttons to right side. I have wrote a jquery code as this is the code here:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>

  >>

  <button type="button" id="button">Click Me!</button>
  <button type="button" id="button">Click Me!</button>
  <button type="button" id="button">Click Me!</button>
  <button type="button">Click Me!</button>

  <<

When I execute this code this is not executed and show the error
Please help me out...
Answer: Correct your brackets as shown below :
$(document).ready(function() {
   $('#leftscroll').click(function() {
      $('#buttonmove').animate({
        'marginLeft' : '+= 30px'
      });     //<----- here
   });     //<----- here
});     //<----- here

Comment: @user3785854...i think above answer will solve your issue if need more help then comment.


Is it possible to put annotations on return Type

Question: I came across this code
@Override
public @NotNull Class<?> getProviderClass() {
    return this.getClass();
}

and I am wondering if it is the same as the code below:
@Override
@NotNull
public Class<?> getProviderClass() {
    return this.getClass();
}

Note: that the @NotNull annotation is in different positions relative to the accessModifier
Is the annotation on the return type in this case or on the method?
Answer: Java 8 allows type annotations, that is, stuff like @Foo int foo = (@Foo int) var;.
The summary of the specification is that it depends on how the @NonNull annotation is declared, specifically how its @Target is specified.

If it uses ElementType.TYPE_USE, the annotation applies to the return type.
If it uses ElementType.METHOD, it applies to the method declaration.
If it uses both (or none), it applies to both the return type and method declaration.

Either way, the annotation is syntactically a modifier of the method, so its position does not matter.
So for example, if @NonNull is declared as a type annotation, then yes, you are asserting that the returned value of the method should not be null.
9.7.4:

It is possible for an annotation to appear at a syntactic location in a program where it could plausibly apply to a declaration, or a type, or both. This can happen in any of the five declaration contexts where modifiers immediately precede the type of the declared entity:

Method declarations (including elements of annotation types)

Constructor declarations

Field declarations (including enum constants)

Formal and exception parameter declarations

Local variable declarations (including loop variables of for statements and resource variables of try-with-resources statements)

The grammar of the Java programming language unambiguously treats annotations at these locations as modifiers for a declaration, but that is purely a syntactic matter. Whether an annotation applies to a declaration or to the type of the declared entity - and thus, whether the annotation is a declaration annotation or a type annotation - depends on the applicability of the annotation's type:

If the annotation's type is applicable in the declaration context corresponding to the declaration, and not in type contexts, then the annotation is deemed to apply only to the declaration.

If the annotation's type is applicable in type contexts, and not in the declaration context corresponding to the declaration, then the annotation is deemed to apply only to the type which is closest to the annotation.

If the annotation's type is applicable in the declaration context corresponding to the declaration and in type contexts, then the annotation is deemed to apply to both the declaration and the type which is closest to the annotation.

In the second and third cases above, the type which is closest to the annotation is the type written in source code for the declared entity; if that type is an array type, then the element type is deemed to be closest to the annotation.
Answer: The position of the @Annotation relative to the accessModifier does not matter. The annotation is on the method and not on the return type.
I compiled and decompiled this with JD-GUI here are my input and output
INPUT
public @NotNull Class<?> getProviderClass2() {
    return this.getClass();
}

@NotNull
public Class<?> getProviderClass1() {
    return this.getClass();
}

OUTPUT
@NotNull
public Class<?> getProviderClass2()
{
  return getClass();
}

@NotNull
public Class<?> getProviderClass1()
{
  return getClass();
}


Is there any overview/list/details about which CoD Ghosts modes can use which multiplayer maps?

Question: As the title says, is there any overview or list detailing which multiplayer maps can be played with which modes?
Judging by this site there are 14 maps. Can all of these be used with the Safeguard modes, as an example?
I know that when I played one of the earlier CoD games, once when I tried out a new game mode I was dropped into a quarry level with construction buildings and big blockish (sand)stones type of obstructions that I had never played before so I'm, from that experience, assuming that not all the maps can be used with all the modes.
Comment: In previous games, you could play pretty much every game mode on every map in private matches as far as I remember.  You might be better off refining your question to, "Which maps are in which online queues?"
Comment: The site you provided doesn't list a posted date, which could be indicative of a continually building page. I have Free Fall but have yet to play it in multiplayer. I believe the standard maps (I.E. those on disk and NOT DLC) are only in the rotations.
Comment: @ColeBusby Pretty sure the Free Fall map is currently only in the Normal mode Moshpit playlist. So if Hardcore is your thing, you won't see it until Freefall is released to everyone (like Nuketown in Black Ops 2).
Comment: @Lyrical I havent had a ton of playing time (<6 hours) so I can honestly state I've just been in squads and extinction. Cranked has yet to have it show up. I should just join the mostpit then.
Answer: Here is a list of all maps from the Call of Duty Wiki. While every competitive map supports every game mode, the last entry under each major heading (excluding the bonus map) is exclusive to the Extinction game mode.
Standard Maps

Chasm
Flooded
Freight
Octane
Overlord
Prison Break
Siege
Sovereign
Stonehaven
Stormfront
Strikezone
Tremor
Warhawk
Whiteout
Point of Contact

Bonus Maps

Free Fall

Onslaught DLC Maps

Fog
BayView
Containment
Ignition
Nightfall

Devastation DLC Maps

Behemoth
Ruins
Unearthed
Collision
Mayday

Invasion DLC Maps

Pharaoh
Departed
Mutiny
Favela
Awakening

Nemesis DLC Maps

Dynasty
Goldrush
Showtime
Subzero
Exodus


How to parse xml using different parent nodes in android

Question: In my xml file I have two or more parent nodes like:-

      //parent node pizza
      //attributes are 1 Veg Pizza
      //parent node burger
      //attributes are 1 Veg Burger,

Whenever the user clicks on pizza listview item then the user should be able to view only list of pizza items in another activity's listview. I know how to call next activity and so on, but I want to know how I can use different parent nodes in my java class, exactly what are the changes I need to do in my java class, please see this link, I am using this tutorial, but here they are using only one parent node song but I want to add more and I have added in my xml file but don't know what are the changes I need to do in java class.
Comment: I recommend you try and format your question in a more readable fashion. Also, if you can give an example xml file (preferably one that is simple and stripped to the basics so we can easily understand your problem) that would help.
Comment: For different patent nodes you just follow this example:

http://stackoverflow.com/questions/8782210/java-dom-xml-parsing-how-to-walk-through-multiple-node-levels
Comment: i have changed please read and revert me...
Answer: carrier.xml ile contains below xml contents
<?xml version="1.0" encoding="utf-8"?>
<carrier>
    <vehicle>
        <vehicle
            cid="1"
            cname="TAXI" />
        <vehivle
            cid="0"
            cname="AUTO" />
   </vehicle>

// In your code
XmlPullParser xpp=null;
int eventType = 0;
XmlPullParserFactory factory =null;
BufferedReader bufr=null;
StringBuilder total ="";
     try{
    bufr = new BufferedReader(new FileReader("/carrier.xml"));
    total = new StringBuilder();
    String line="";
    while ((line = bufr.readLine()) != null)
    {
    total.append(line);
    }
    factory = XmlPullParserFactory.newInstance();
    factory.setNamespaceAware(true);
    xpp = factory.newPullParser();
    xpp.setInput(new StringReader(new String(total)));
    eventType = xpp.getEventType();
    }catch(XmlPullParserException e){
    // Log.v("xmlpullparser"," "+e);
    e.printStackTrace();
    }catch(IOException ie){
    // Log.v("IOException"," "+ie);
    ie.printStackTrace();
    }

    try{
    while (eventType != XmlPullParser.END_DOCUMENT){
    if(eventType == XmlPullParser.START_TAG){
    String Scid="",Scname="";
    int acount=xpp.getAttributeCount();
    if(acount!=-1){
    for(int x=0;x<acount;x++){
                        if(xpp.getAttributeName(x).equalsIgnoreCase("cid")){
                            Scid=xpp.getAttributeValue(x);
                        }if(xpp.getAttributeName(x).equals("cname")){
                            Scname=xpp.getAttributeValue(x);
                        }
                    }
    }
    }
    eventType = xpp.next();
    }
    }catch(Exception e){
            e.printStackTrace();
    }

After this you can use the Scid Scname etc in your code as per your convenience

Comment: meher, like here you are using only one parent node but i need to use multiple parent nodes which is different with each other like:- vehicle, transport (parent nodes)
Comment: hi, here xml pull parser will read all the start tags with same name or different I have specified the attributes string names like cid and cname and not the start tag String names.If you add log and print the start tag names by reading it in a string you will see all the start nodes. Hope I am clear to you.


VSCode how to fix typescript highlight error Argument of type {} is not assignable to parameter of

Question: What should I do in the function createField in order to remove this syntax error highlighting?
const createField = (
    dataType,
    options = {
        required: false,
        label: null,
        min: Number.NEGATIVE_INFINITY,
        max: Number.POSITIVE_INFINITY,
        email: false,
        match: false
    }
) => {
    return {
        dataType,
        options: {
            ...options,
            label: options.label && options.label.toString() || null,
        },
    };
};

Comment: `const inferToPartial = (o: T) => o as Partial; /*...*/ options = inferToPartial({ required: false, /*...*/ }) /*...*/;`, alternatively you can type out the entire type again, or pull the default into a variable before the function, and use its type to not have to write it again. Also see e.g. [this question's answer](https://stackoverflow.com/questions/49569665/typescript-default-parameters-for-objects-passed-into-function)
Answer: Here a possible solution:
interface CreateFieldOptions {
  required?: boolean;
  // you need to change the type here
  label?: unknown;
  min?: number;
  max?: number;
  email?: boolean;
  match?: boolean;
}
const createFieldDefaultOptions: CreateFieldOptions = {
  required: false,
  label: null,
  min: Number.NEGATIVE_INFINITY,
  max: Number.POSITIVE_INFINITY,
  email: false,
  match: false
}

const createField = (
    dataType,
    options: CreateFieldOptions = {}
) => {
    return {
        dataType,
        options: {
            ...createFieldDefaultOptions,
            ...options,
            label: options.label && options.label.toString() || null,
        },
    };
};

What are the changes?

Add an interface to manage the options type -> CreateFieldOptions

So it can be reused

Extract the default options into a separate variable -> createFieldDefaultOptions

Your intent seems to be to merge the default options with the provided passed options. But that is not possible via the parameter assignment, so it has to be done later (see last bullet point)

The type of the options parameter is now an optional CreateFieldOptions
The returned object with the options attribute is extended by the createFieldDefaultOptions

The order is important! createFieldDefaultOptions needs to be first, so that it can be overridden by the provided options


Is it ok that a new deeper sink disposal line is the same height as drain line?

Question: So we're remodeling our kitchen and my wife insisted we get a new farmhouse sink.  We had a contractor install the new sink and after getting it put in he mentioned that the disposal line is about the same height as the drain line in the wall.  Maybe the disposal line is higher than the wall line, but if it is its like millimeters higher.
He connected it up using some of those flexible tubes and said we should be good.  I was a little worried about this set up, so I tested it by pouring about 3 gallons of water from a bucket (we don't have a faucet yet) down the drain and then unscrewed the black tube line from the disposal.  Water was sitting in the p-trap all the way up to the top of the this black tube, but was not in the disposer itself.  I'm afraid that will be a problem once the disposer starts getting used again.
I was googling around and most suggestions are to either 1.  Get a shallower sink (won't happen, wife won't allow it).  2.  Remove the disposal (I use it every so often so I'd prefer not to do this if I can avoid it).  3.  Move the drain line in the wall down (requires plumber because I ain't doing that haha).  4. IF THIS IS EVEN EXISTS, find a disposer with a shorter neck/flange. My current disposer is a Waste Master SS2600.  Its probably 19-20 years old and original to the house, but still works fine.
Or is it actually ok the way it is set up like the contractor said?  I've never actually explored a p-trap before, but I know they're supposed to hold some water.  Is it ok if they're completely full up to the top of the black tube from the disposer?
If its not ok, it seems my only option is #3 or #4. Based on experience what would be the average cost of moving a drain pipe down like 2-3 inches?  Like no more than $500, surely?
I've attached some screenshots of the setup.

Update:
We'll the new disposal isn't much higher.  MAYBE half an inch.  Also the ptrap is now too close to the wall so I have to have it come off the side and have an extra elbow in there.
Comment: I don't know about the height issue. But you do **NOT** want that accordion pipe. Replace it with appropriately sized regular pipe.
Comment: A small, shallow sink bowl just for the disposer is pretty common, as an accessory to, not a replacement for, the main sink. Presumably you're a non-composting household and on sewer, not septic (if you are on septic, removing the disposal is highly advised...) Accordion pipe is an evil kludge that should be a code violation, but apparently isn't. It will clog, or break, or both. Particularly with the material a disposer will send through it.
Comment: See also https://diy.stackexchange.com/questions/81969/what-is-the-minimum-height-for-garbage-disposal-drain-above-the-drain-stub
Answer: Normally, there wouldn't be water all the way up to the 90° going into the disposal, however, that isn't inherently an issue. (You're not removing that pipe in daily operation, right?) So long as you don't have water standing in the disposal, you should be fine.
I'd agree with the comments that the much bigger issue is the accordion pipe. They're just not recommended.
When replacing that accordion pipe, simply raise the whole trap up 1/4-1/2" so that there is some slope from the top of the trap to the stub-out on the wall to ensure you've got good drainage.
Comment: I actually found a compact disposer whose drain pipe sits a whole inch higher than the one I currently have.  I'm going to replace the old disposer with this new one (the old is close to twenty years old anyway).  I believe if I then trim the new disposer drain pipe by an inch or so I can align the trap to the wall in almost the same position it was before the new sink was installed.
Comment: Sounds good, @Fettster777! I'm glad you were able to find that. Having the disposal drain above the wall stub out will definitely help. I'd suggest test-fitting prior to doing any trimming - you might not need to trim.
Comment: Thanks, I've got a plumber coming in 11 days to take a look at it.  I just don't trust myself with this stuff.  I'll ask if he can replace the accordion pipe.  If it ends up not being too costly I may just have him lower the drain pipe in the wall as well.  If worse comes to worse I guess I'll just ditch the disposal, use regular pipe to the wall, and throw scraps in the trash from now on.
Comment: I added some new pics if you've got an opinion on them. Installed new disposal, but had to make a change with the pipes
Comment: Based on that last pic, about all you've done is change the shape of the trap. Water will sit between the last elbow (closest to the wall) and the disposal. Again, I don't think this is an inherent problem, but the mass of food that is ground up in the disposal will tend to want to sit in the trap anyway, and then it's got to make that extra journey uphill through another elbow. This will, I believe, tend to lead to more clogging. Be sure to run a _lot_ of water every time you use the disposal and expect to have to clean out the trap pretty regularly.
Comment: Thanks, I generally run lots of water when using the disposal so hopefully (praying) I don't have an issue.  I'm still having the plumber come out next week to take a look.  I really...really don't want to open the wall if I can avoid it.  It'll be costly, and I'm afraid they'd need to remove the cabinets which I just can't allow at this point in the remodel of the kitchen.  I'd rather do without the disposer than remove cabinets.
Comment: Honestly, I wouldn't stress over removing a 16x16" square of drywall under the cabinet to lower the drain stub out. It's an awkward place to work, but because it's mostly hidden, the patch job doesn't have to be 100%. You could probably DIY the repair w/o any stresses. If you're not good at drywall mudding, this is a fine place to practice because it's _not_ all that visible.
Comment: I'm mostly worried about the lowering of the pipe.  I've no clue what it looks like behind that wall haha.  There is a second stub to the left of this stub at the same height (for the other sink bowl) and I hope they're not connected horizontally.  I've done some drywall work before, very little, but some, so I'm not too concerned about patching the hole afterwards.

I was thinking maybe connect the disposer to the drain on the other sink bowl, but it comes right at the top of the nut of the beginning of the p-trap on that one.
Comment: Adjusting the height of the stub out is literally cut & paste (well, glue). It'll take a plumber 30 min or less. Probably take you 2 hours if it's your first time and because cutting the pipe nice and square _in_ the wall is a bit of a challenge, but nothing you can't overcome. If you have questions about DIYing that, ask a whole new question about that portion of the project. I'm out here before the system starts to yell at us about conversation in the comments. ;)
Answer: It should be ok as long as your trap arm has the correct slope and is within the critical trap arm length to prevent siphon.
The accordion style p-traps as others have noted aren't recommended and would likely fail code.
Having the water that high does make servicing harder but it is difficult to lower the roughed in stub for the trap arm without removing cabinets and cutting drywall.
https://www.jlconline.com/how-to/plumbing/maximum-length-for-fixture-drains_o
Comment: I think siphoning is indeed the big question here due to slope and accordion, not puddling, since we can't see in the wall. OP could perform repeated tests, draining a full basin several times and confirming that every time there is water in the P trap.


How to deal with bedroom condensation/moisture on winter mornings?

Question: In late September when the weather started cooling down here in Surrey BC Canada, we started to see morning condensation on our windows (newly installed last year):

My wife and I and our son sleep in the room, so presumably it is due to our breathing. I should double-check the humidity in the room when it happens again tomorrow, but I think it is about 60%. We do have a dehumidifier, but we find it too noisy to run during the night (even with a timer), so we just run it after we wake up.
Questions:

Is the humidity/condensation in the windows and walls a concern for mold growth, or is it sufficient to run the dehumidifier after we wake up and rely on the sun to dry up the windows?
How to prevent excessive humidity/condensation in the bedroom? It is cold, so we don't want to leave our windows partially open all night. And the dehumidifier is too noisy for us to run during the night. Would a silent moisture absorbing product like DampRid help? I heard that it won't help much.

I read that the key to solving humidity problems is improved ventilation. But how to improve ventilation in a bedroom with a closed door? The bathroom fan won't help because the door is closed. Opening a window won't work because it is cold outside. Is our only option an expensive Heat Recovery Ventilator that will vent to the outside while conserving heat? But aren't those as noisy as a dehumidifier?
I saw a similar question here (Why does significant condensation gather on my bedroom windows overnight?) but it just suggests opening the windows, using a dehumidifier, keeping the blinds open, putting bubble wrap on the windows (won't solve moisture getting into the walls though), and not worrying about it.
Answer: Indoor humidity levels are high in the fall, making window condensation more likely. Where I am, we have to wipe our windows each morning for the first few weeks of cold weather. After that, it's less of a problem. It's important to exhaust moist air using bathroom and kitchen fans to reduce this effect.
Mold is a slight concern, but not as much so as during warmer months. More of a concern is liquid water damage. If water collects on the sills the wood will begin to swell and decay and the finish will degrade. This is your primary concern. If you wipe them each morning you'll mitigate the problem.
If you still have regular condensation a few weeks down the road, look into the source of the moisture and whether you can improve ventilation or room-to-room air mixing (possibly using a fan-only cycle on your HVAC system). The appropriate indoor relative humidity level depends on the outdoor air temperature, so it needs to decline during colder weather.
Answer: Don't over look the possibility the windows were installed incorrectly.  If they are bowing any or otherwise out of alignment, there could be just enough room for outside air to get in around seals.  You may not even be able to see any misalignment.
I'd suggest using isherwood's answer first and if it's still a problem later, consider having the installation inspected/double-checked in case there's something wrong.


What is channeling efficiency, and what does it do?

Question: So, most mods that had "Charge speed" or "charge damage" have now been replaced with "Channeling efficiency" as a stat.
What does Channeling efficiency do?  When it says "+30% Channeling Efficiency", what exactly is happening? Does it mean it costs less energy per melee hit while channeling, does it mean I get more damage out of channeling, does it have any other effect?
Answer: Channeling happens when you hold down the left mouse button while in melee mode, and (at base) converts 5 Energy into extra damage on your next melee hit.
Channeling Efficiency reduces the amount of energy each hit consumes to a minimum of 1 Energy per hit, so "30% channel efficiency" would mean your attacks consume 5*0.7=3.5 energy per strike.
Answer: Channeling Efficiency reduces the cost per hit while channeling (holding left mouse button while having the sword equipped).
Base cost is 5 energy per hit (misses do not use energy), minimum energy cost is set to 1 Energy per strike, so even if you should get 100% channelig Efficiency, you can't get below that cap.
Also not that you can gain a damage multiplier while chanelling - ever 5 consecutive hits earns you a damage multiplier of 0.5 (I don't know if there is a cap).
Source: Warframe Wikia
Warframe forum
Comment: so what's my best bet for Channeling Efficiency in terms of limits? For example, p efficiency is limited by 75% or 65% i believe, so going over doesn't affect energy spent anymore, what about channeling? Is it 100% as a cap?
Comment: As per the wiki - Power Efficiency is capped at 80%, which translates to 1 energy per hit while channeling.


How to find the median for dataframe of population with columns of age and count?

Question: df looks like this:
   age  population
0   20           2
1   21           3
2   22           2
3   23           5
4   24           7

df = pd.DataFrame({ 'age': [20, 21, 22, 23, 24], 'population': [2, 3, 2, 5, 7]})

and I'd like to calculate the median age of the total population. Is there a simple way to do this?
Got average like this, but I need the median:
df['years'] = df['age'] * df['population']
average_age= (df['years'].sum()/df['population'].sum())

Answer: Multiplying two pandas Series is different than multiplying lists - you're not copying each value N times, you're performing element-wise multiplication.
Use pd.Series.repeat to repeat each element N times, and then use the .median method to calculate the median of the resulting pandas Series:
df = pd.DataFrame({ 'age': [20, 21, 22, 23, 24], 'population': [2, 3, 2, 5, 7]})
m = df['age'].repeat(df['population']).median()
print(m)  # output: 23.0

Comment: Perfect. Thank you!


Area of triangle formed by normal distributed points

Question: The 3 points of a triangle in $\mathbb{R}3$ are not precisely known. The uncertainty of the points shall be described by three-dimensional Gaussians where the expectation values $(x_i,y_i,z_i), i=1,2,3$ and standard deviations are known. What is the expected area and area distribution? (here a 2d sketch)
The area can be calculated via the cross product and is given in terms of $(x_i,y_i,z_i)$ as
$\frac{1}{2}\sqrt{(x_1 y_3+x_2 y_1-x_1 y_2-x_2 y_3-x_3 y_1+x_3 y_2)^2+(x_1 z_2-x_1 z_3-x_2 z_1+x_2 z_3+x_3 z_1-x_3 z_2)^2+(y_1 z_3+y_2 z_1-y_1 z_2-y_2 z_3-y_3 z_1+y_3 z_2)^2}$
Following simplifications shall be made:

standard deviations are equal for all points and all directions
random distributions are mutually independent
points do not interfere, i.e. standard deviation $\ll$ point distances
Comment: Maybe see: https://math.stackexchange.com/questions/516219/finding-out-the-area-of-a-triangle-if-the-coordinates-of-the-three-vertices-are/516223, https://math.stackexchange.com/questions/92255/probability-distribution-for-the-perimeter-and-area-of-triangle-with-fixed-circu
Comment: the given link considers the case of exact known points but in the problem the points are randomly distributed
Answer: You don't need a square root; the area is given by $A=|x_1y_2-x_1y_3-x_3y_2-x_2y_1+x_2y_3+x_3y_1|$. By your third assumption, we can assume that the argument of the absolute value doesn't change sign, so the area is linear in each coordinate. Then by your second assumption the problem factorizes and you can replace each coordinate by its expected value: The expected area is just the area of the triangle formed by the expected vertices. You don't need the first assumption for that.
Comment: I specified my original question. Does the square root change everything?
Comment: @granularbastard: You didn't "specify" it, you turned it into a completely different question. That's very bad style, changing a question so that a valid answer is no longer valid. You should ask a new question instead.
Comment: Actually I tried to simplify the problem from 3d to 2d but now it seems that the simplification was not valid and a triangle with random points in 2d is not the same as a triangle in 3d. That is surprising.
Comment: the problem was specified here:

https://math.stackexchange.com/questions/3490253/area-of-triangle-with-normal-distributed-points


What is exact value of $\sum_{n=1}^{\infty} \frac{1}{n^n}$ .

Question: I would like to ask if anyone would help me with solving the following infinite series.
\begin{equation}
    \sum_{n=1}^{\infty} \frac{1}{n^n} = \,?
\end{equation}
Thank you in advance.
Comment: [Sophomore's dream](https://en.wikipedia.org/wiki/Sophomore%27s_dream)
Answer: Although it has no closed form, it does satisfy the remarkable identity
$$
\sum_{n=1}^\infty \frac{1}{n^n}  = \int_0^1\frac{dx}{x^x}.
$$
It is also equal to $\ln(3)^e$ to five decimal places.
Comment: Thank you very much.


Print certain parameter in column with awk

Question: I stumbled over a little problem, which I am not able to solve with awk in a bash script.
I do have following data file:
 33   1000   1.108932e-01   2.825803e+00  -9.955642e-05    0.0000e+00       0.0000e+00    8.012180e-02 4.081916e-02

 0.0000e+00   7.8557e-01   6.1128e+01   4.0468e+00  -9.9558e-05   3.8526e-02   3.1874e-03   5.1303e-01   0.0000e+00

 1.6667e-02   7.8530e-01   6.0977e+01   4.0552e+00   1.0627e-01   7.8951e-02   6.2521e-03   5.0750e-01   0.0000e+00

...

which has a header line with 10 elements, followed by an array with 33 rows and 9 columns.
I would like to use the data in this file to print out the forth parameter from the header line followed by the average of line 3 (i.e. sum+=$3 / {Number of lines}). At the moment, I try to do it like:
gawk '{time=FNR==1{$4};if(NR>1)sum+=$3}; time = FNR == 1{$4} END {sum=sum/(NR-1); print time " " sum}' $tmpn.data >> $tmpn.vrms

It works fine for the average, however, the time paramter is not correct and I only get a 0 as return. Maybe I am missing only a small thing, but, unfortunately I couldn't find anything online. What would be the best way to solve this issue.
Thanks for the help.
Cheers.
Comment: Thanks for the tip!
Answer: Try:
awk 'NR==1 {time=$4;next} {sum+=$3} END {print time, (sum/(NR-1))}' $tmpn.data >>$tmpn.vrms

NR==1 {time=$4;next} is a pattern-action pair:

Pattern (condition) NR==1 is only true for the first input line.
Thus, action {time=$4;next} is only executed for the first line, and it stores the header's 4th field in variable time, then proceeds to the next record (line; next).

{sum+=$3}, which is processed for all remaining records (i.e, the data records), iteratively sums up the values in the 3rd field in variable sum.
END {print time, (sum/(NR-1))}:

The END block is executed after all input records have been processed.
{print time, (sum/(NR-1))} prints the header field and the average of the 3rd-field values, separated by the default output field separator (OFS), which is a space. Note that NR contains the total number of input records inside the END block.

A note on your solution attempt and awk's philosophy:

As (currently) stated, your command breaks, because you've enclosed the entire script in {...}.
Generally, awk's terse elegance comes from a sequence of carefully crafted pattern-action pairs.

A pattern is a condition (Boolean expression) that executes the associated action (a sequence of statements) only, if the condition is true.
Think of the pattern as the conditional part of an if statement with the "syntactic noise" removed, and the action as the body of that if statement:
<pattern> { <action-cmd1>; ... } is (conceptually) short for if (<pattern>) { <action-cmd1>; ... }

In a given pair, you may either omit the action, or the pattern:

If you omit the pattern, the action is executed unconditionally (though the action may still not get to execute, if a previous pattern-action pair skipped further processing, such as with next or exit).
If you omit the action, the default action is { print }, i.e., to print the (potentially modified) current record.

This behavior is enables the common shorthand 1 to simply print the current record: 1 is a pattern that, in the Boolean context in which patterns are evaluated, is always true, and, in the absence of an associated action, the current record is printed by default.
Comment: Thank you very much for the detailed description and explenation. Worked perfectly.
Answer: Another version in awk using getline in while loop to read and detect the end of file and then output the header buffer b and the average:
$ awk 'NR==1{b=$4; while(getline==1){s+=$3;c++} print b,s/c}' data
4th 40.7386

It expects the datafile to have a header line. Explained:
NR==1 {                  # read in the first line and ...
    b=$4                 # ... buffer the 4th field of the header
    while(getline==1) {  # then read while there are records to read
        s+=$3            # sum up the values in the 3rd field
        c++              # count the number of values, add if($3!="") if needed
    }
    print b, s/c         # after while output header and average
}


with open(), how can I tell if I am at the last line of a file?

Question: I have:
with open(self.corpus_file) as infile:
    for line in infile:

How can I tell if line is the last line in infile?
This is with Python 3.6 if that matters.
Answer: Here's a simple way:
from itertools import tee

with open(self.corpus_file) as infile:
    infile, check = tee(infile)
    try:
        next(check)
    except StopIteration:
        # file is empty
    for line in infile:
        try:
            next(check)
        except StopIteration:
            # line is the last line

Another even simpler way if you don't have to stay in the loop:
with open(self.corpus_file) as infile:
    for line in infile:
        pass

# line is now the last line

Comment: @Tomerikoo I think I could conceive of a complicated situation where it might be necessary.... like perhaps if you both reading and writing to the file at the same time? but most of the time, yeah, you're probably right.
Comment: Won't the for loop get a `StopIteration` and stop before your `next()` ever does? Seems like you need a `next(check)` before the loop so check is one step ahead.
Comment: Your simpler solution is the perfect solution even you **do** stay in the loop. I mean, on every line, do whatever you want with it, **and** in the end you have the last line available... Don't see why make it more complicated with iterators
Comment: @Tomerikoo. The general idea is that you might have to know whether the line is last *before* you process it.
Comment: Yeah I get that it might be good in some cases... I was quick to dismay. Thanks for the explanations :)
Answer: File objects returned by open are iterators in Python, so you can look out for StopIteration while doing next to consume lines in a while loop:
with open(self.corpus_file) as f:
    line = None
    while True:
        try:
            line = next(f)
        except StopIteration:
            break

Now line should contain the last line.
Answer: Generally you don't want to try to figure that out inside the loop, but rather, you'll know you've reached the end when the loop exits. If you want to do something special if you've reached the end (and might sometimes break out of the loop), you can add an else clause to the for:
with open(filename) as file:
    for line in file:
        if not do_stuff(line):
            break
    else: # got to the end without breaking
        do_something_special_with_last_line(line)

Answer: Using the fact that files are iterators, you can use the following generic recipe. It returns a status flag along with each line. The flag is True for the last element of the underlying iterator:
def is_last(iterator):
    prev = next(iterator)  # immediate StopIteration possible
    for item in iterator:
        yield False, prev
        prev = item
    yield True, prev

You would use it like
with open(...) as infile:
    for last, line in is_last(infile):
        ...

Answer: You could use a collections.deque like this:
from collections import deque

def read_file(filename):
    with open(filename) as infile:
        dq = deque([next(infile)], 1)
        for line in infile:
            yield dq[0]
            dq.append(line)

    # Last line of file.
    yield 'LAST LINE: ' + dq[0]

corpus_file = 'corpus_file.txt'

for line in read_file(corpus_file):
    print(line, end='')


Identifying name of a connector part

Question: An old kitchen table has kind of spanning metal clips connecting parts; some of them are rusty and do not span well anymore.
Note: you might think that because of the rust the clips can't be closed anymore, but in fact they have somehow become weak, i.e. normally you would close and open them with applying slight force, but now the clips can just open up by themselves because of the gravity.
What is the proper name of this metal parts so that I could order and replace them?
Comment: If they are loose now it seems like there are two ways to fix it. First would be to slightly re-form the metal loop so it is tighter. It probably became stretched over time. The second way would be to re-position them to be farther apart from their mate. You'd need to move them so the old screw holes aren't in the way.
Comment: The damage is superficial, you could unscrew them, drop them in a rust- removal solution, spray paint them, lubricate and replace them.
Comment: thank you! still is there a proper term for such parts? also, I think I need to add this, the closure has become weak, not blocked by rust.
Answer: I think they are called latch clamps:
https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=latch+clamp&rh=i%3Aaps%2Ck%3Alatch+clamp

Identifying name of a connector part