Homology of real projective plane with two points identified

Question: What is the delta homology of the real projective plane with two points identified. I can't think of any space that it retracts that I can find a delta structure does anyone have any idea
Comment: One way to find a delta structure is as follows. First represent the projective plane as a disk with antipodal points of boundary identified. Draw in a diameter and put a vertex at the center. The two endpoints of the diameter are one vertex since they are identified. Now glue the center vertex to this identified vertex so all three vertices in the picture are the same.
Comment: Isn't the space equivalent to $\mathbb{R}P^1 \vee S^1$?
Comment: I'd say it's equivalent to $\Bbb R P^2 \vee S^1$. Identifying two points it's the same as attaching a path to these two point. by contracting any simple path in $\Bbb R P^2$ connecting those two points and using the Homotopy extension property, you get the claimed homotopy equivalence
Comment: "delta homology" and "delta structure" sound like interesting concepts that weren't recognised back in the day when I first learnt some algebraic topology. What do these terms mean? Clearly if you identify two points on a connected manifold $M$, the result is homotopy equivalent to the wedge $M \lor S^1$. What more do you (or I) need to know?
Comment: @RobArthan: Hatcher uses delta complexes. They are basically simplicial complexes where the faces of a simplex need not be distinct.
Answer: $X$ with two points $a,b$ identified is homotopy equivalent to $X$ plus a line segment between $a,b$. If $a,b$ are in the same path component of $X$ then you can slide one to the other and your segment becomes a loop, so you get $X \vee S^1$.
All this might depend on $a,b$ being nondegenerate in some way, but that shouldn't be a problem in a cell complex.


Is it safe to call pthread_cancel() on terminated thread?

Question: I'm wondering if it is safe to call pthread_cancel() on a terminated thread. I couldn't find any hints in the manual page. Thanks in advance for any hints.
Edit: Maybe I wasn't accurate enough. I'm not talking about threads terminated by an earlier pthread_cancel() but about threads that simply returned from their thread function.
Answer: I think it needs to be safe, or pthread_cancel would be problematic (next to unusable).
Indeed, if it wouldn't be safe, every call to pthread_cancel would have to be enormously complicated by checking the thread is alive (and ensuring it stays alive until you get to cancel it). A simple "are you still there" wouldn't do.
In conclusion, I believe pthread_cancel must be safe if the thread has terminated. Of course, this might not be the case for a terminated and joined thread.
Comment: Simple rule: A pthread_t is valid until the thread terminates (if it is detached) or is joined (if it is not). This means you can safely pthread_cancel a detached thread only if you know it has not terminated. You can safely pthread_cancel a non-detached thread so long as you know it has not been pthread_join'ed.
Answer: There is a  hint actually:

ERRORS         top
  ESRCH  No thread with the ID thread could be found.

And MKS gives a bit other description:

ESRCH
thread does not specify a currently running thread in the process.

OpenGroup recommends:

If an implementation detects use of a thread ID after the end of its lifetime, it is recommended that the function should fail and report an [ESRCH] error.

UPDATE
in NPTL  there is a check for double cancel or cancel after exit:
  /* We are canceled now.  When canceled by another thread this flag
     is already set but if the signal is directly send (internally or
     from another process) is has to be done here.  */
  int newval = oldval | CANCELING_BITMASK | CANCELED_BITMASK;

  if (oldval == newval || (oldval & EXITING_BITMASK) != 0)
    /* Already canceled or exiting.  */
    break;

So, second cancel or cancel after exit will be a noop for dead thread.
The exiting_bitmask is set by __do_cancel:
/* Called when a thread reacts on a cancellation request.  */
static inline void
__attribute ((noreturn, always_inline))
__do_cancel (void)
{
  struct pthread *self = THREAD_SELF;

  /* Make sure we get no more cancellations.  */
  THREAD_ATOMIC_BIT_SET (self, cancelhandling, EXITING_BIT);

__do_cancel is both reaction to async cancel and to pthread_exit
void
__pthread_exit (value)
     void *value;
{
  THREAD_SETMEM (THREAD_SELF, result, value);

  __do_cancel ();

Comment: Yes, but even if the thread terminated, `pthread_join` might be called, so **when a thread ends its ID remains valid**.
Comment: domachine, the link from [this answer](http://stackoverflow.com/questions/6371844/calling-pthread-cancel-on-a-joined-thread-causes-segfault-under-linux/6373108#6373108) is to [standard IEEE Std 1003.1-2008](http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_09_02) which says: The lifetime of a thread ID ends after the thread terminates if it was created with the detachstate attribute set to PTHREAD_CREATE_DETACHED or if pthread_detach() or pthread_join() has been called for that thread.
Comment: @domachine yes, I know that. I was just making a remark. It's a good question with very informative answers.
Comment: Despite whatever the documentation may say about lifetimes and valid thread ids, on my plain Debian Wheezy system, calling `pthread_cancel` on a terminated thread results in a return value of -1 and `errno` set to `ESRCH`.
Comment: I think the question is how the mentioned lifetime is defined. Does it specifiy the time until the thread terminates or does it mean the time until pthread_join() is called?
Comment: Also it says: "A conforming implementation is free to reuse a thread ID after its lifetime has ended. If an application attempts to use a thread ID whose lifetime has ended, the behavior is undefined.". So you can't call cancel after join. But you can send 100 cancel signals before join.
Comment: And the cancellation state after pthread_exit is PTHREAD_CANCEL_DISABLE: "When a cancellation request is acted upon, or when a thread calls pthread_exit(), the thread first disables cancellation by setting its cancelability state to PTHREAD_CANCEL_DISABLE and its cancelability type to PTHREAD_CANCEL_DEFERRED. "
Comment: You can't call cancel after join but you probably would call join after cancel as that's the only way to tell if the thread was actually canceled.
Comment: @celavek: Yes, but that's not the problem. The problem is if it is secure to call pthread_cancel on a thread that has not been terminated via pthread_cancel but has terminated by for example returning from the thread function.
Answer: Yes, it is safe to call it before pthread_detach or pthread_join has been called.
However, according to my experiments, it can return ESRCH (=3) if the thread has already returned from its thread function. (gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0)
#include "gtest/gtest.h"

static void *S_ThreadEntry1(void* pvarg)
{
     return 0;
}

TEST(ThreadTest, PthreadCancelAfterExit)
{
     pthread_t threadid;
     ASSERT_EQ(pthread_create(&threadid, 0, &S_ThreadEntry1, nullptr), 0);
     sleep(1);

     int cancel_ret = pthread_cancel(threadid);
     std::cout << "pthread_cancel returned " << cancel_ret << std::endl;
     if (cancel_ret != 0)
          EXPECT_EQ(cancel_ret, ESRCH);
     void* res;
     EXPECT_EQ(pthread_join(threadid, &res), 0);
     std::cout << "res=" << res << std::endl;
}

Output:
[ RUN      ] ThreadTest.PthreadCancelAfterExit
pthread_cancel returned 3
res=0
[       OK ] ThreadTest.PthreadCancelAfterExit (1000 ms)

Answer: No, it isn't safe to call pthread_cancel() on a thread that has been terminated.
The reason is that the implementation may reuse the thread ID of the terminated thread for another thread and calling "pthread_cancel()" on that TID may trigger the termination on threads that shouldn't be terminated or undefined behaviour.
Comment: This answer is wrong. The lifetime of a thread id extends until it's joined or detached and exited.


What is this chord progression?

Question: There is a chord progression in Nasty Majesty (Track 2 in Octotune, from Splatoon 2) that I am having trouble analyzing.
It is:
Gminor Bflat Cminor D7 Gminor
and I am not sure how to analyze it.
I tried analyzing it with the "negative harmony" approach, and I got:

Gminor: tonic
Bflat: tonic-parallel
Cminor: dominant
D7: dominant, from major

Something did not feel right about this (why would a C be dominant in G?), so I tried an approach similar to analyzing in a major key:

Gminor: tonic
Bflat: ambiguous (is it the dominant-parallel? or the tonic-counterparallel? likely the tonic-counterparallel because it follows a tonic)
Cminor: subdominant
D7: dominant

I am not sure how to analyze this. Does anyone have a solution?
Comment: The progression seems to be in G min.  Relative to that key Gmin is i, Bb is III, C- is iv and D7 is V7.  Seems to be the most direct way to analyze it.
Answer: i III iv V7 i - assuming the key is in G minor
It looks like a simple Tonic - Predominant - Dominant - tonic progression
For Negative theory (Neo Riemannian to take place, I would expect a chord to take place with a Db tonic, thus expanding on the m3 difference between Gm's tonic and BbM's tonic. Whether Db major or Db minor / respelled to C# minor were to appear, I would then assume to also see E major or minor appear, thus completing an octatonic cycle based on Gdimo7 pitches (though enharmonically spelled at times.)
Hope that helps!
Comment: Yes, I know that is an "i-flatIII-iv-V7". Also, we have TWO predominants (Bflat, Cminor).
Comment: @1gr8penguin what additional information are you looking for?
Comment: What the functions are exactly (T/D/S)
Answer: Gm, B♭, Cm, D7. Let's say it's in key B♭.
Gm= vi submediant
B♭ = I tonic
Cm = ii supertonic
D7 = V7/vi secondary dominant (of submediant).
Putting it into key Gm
Gm = i tonic
B♭ = III mediant
Cm = iv subdominant
D7 = V dominant
B♭ and Gm are relative major/minor. Parallels will have the same tonic.
Comment: I'm aware of that, but I know it is in G minor.
Comment: What exactly are you aware of? Terms like 'dominant-parallel' and 'tonic counter-parallel' are not known to me.  That Bb is the relative major - mediant in key Gm, R.N. III.
Answer: No need for 'negative harmony' or any other complicated explanation.  It's just the hoary old '4 chord trick' - that 'Heart and Soul' thing that your kid sister bashes out interminably on the piano with her friend - modified for minor tonality.
In a major key it's I, vi, IV, V7.    The three Primary Triads plus the Relative Minor.
In a minor key it's still tonic, subdominant, dominant 7th. That's Gm, Cm, D7.  But the additional chord is now bIII, the Relative Major.
For hundreds of years, V of a minor key was almost ALWAYS major.   Not quite so inevitable now, but you shouldn't be surprised when it is!
(And, as @Tim has pointed out, your chord-naming is shaky.  The parallel major has the SAME root.  Bb is the relative major of G minor.)

What is this chord progression?


Proving $\sum_i \binom{k}{k-i} \binom{n-k}{i} = \binom{n}{k}$

Question: I am in the middle of a probability question. The question is indeed simple. For the sake of clarity of the notation, I also include the question here, which is from Sheldon M. Ross's Introduction to Probability Models:

A fair coin is independently flipped $n$ times, $k$ times by A and $n-k$ times by B. Show that the probability that A and B flip the same number of heads is equal to the probability that there are a total of $k$ heads.

I have reduced the question to proving $$\sum_i \binom{k}{k-i} \binom{n-k}{i} = \binom{n}{k}$$ and I cannot move on. So far, I have tried to expand $\binom{k}{k-i}$ and $\binom{n-k}{i}$ by the definition of binomial coefficient and then observe for common terms. However, it comes out to be a mess and I am not sure if there is other way to do it.
Thanks in advance.
Answer: If in a box there are $n$ marbles, $k$ of them being red and $n-k$ being black, with
$$\sum_{i}\binom{n-k}{i}\binom{k}{k-i}$$
you are counting the ways to select $i$ black marbles and $k-i$ red marbles, for any possible $i$.
This is just the number of ways to select $k$ marbles out of $n$, i.e. $\binom{n}{k}$.
Answer: It is simply a matter of considering the coefficient of $x^{k}$ on both sides of
$$
(1 + x)^{k} (1 + x)^{n-k} = (1 + x)^{n}.
$$
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{}$
\begin{align}
\color{#66f}{\large\sum_{i}{k \choose k - i} {n - k \choose i}}& =
\sum_{i}{n - k \choose i}\bracks{z^{k - i}}\pars{1 + z}^{k} =
\bracks{z^{k}}\pars{1 + z}^{k}\sum_{i}{n - k \choose i}z^{i}
\\[5mm] & =
\bracks{z^{k}}\pars{1 + z}^{k}\,\pars{1 + z}^{n - k} =
\bracks{z^{k}}\pars{1 + z}^{n} =
\bbox[8px,border:1px groove navy]{\ds{n \choose k}}
\end{align}


Comentário em arquivos .env

Question: Exite alguma maneira de escrever comentários em arquivo .env em projetos em NodeJS?
Answer: A aplicação só olha as chaves que você determinar então você pode colocar, por exemplo, o caractere <code>#</code> na frente do comentário sem problemas
Comment: Valeu. Nenhum erro mostrado. Deu certo. 0/

Comentário em arquivos .env


Bulk namespace rename

Question: I am making an ERP using ASP.NET Web Forms. I started working on this a while back and successfully completed a version. My project's root namespace is EPERP. So I have other namespaces like EPERP.DataAccessLayer, EPERP.Controllers, etc.
Now, due to client demands, I have divided my project into several parts. I have divided the code layer into one part, and divided the view layer into multiple parts based on client requirements.
The ugly part is that, I did this by opening empty web application projects in visual studio and then copying the relevant view files into that project. That is how I have divided one project into four.
Since my code part is a separate project, all my view related projects reference the dll created from that project.
The problem is that, all projects have the same namespace. So my view related projects have root namespace EPERP, and they reference a dll that has a root namespace EPERP.
None of my projects have the same files, but sometimes I get this error when running my project that a file is ambigous since it is specified in both assemblies.
In any case, keeping the same namespace was a really bad decision.
How can I change the namespace of my project so that it affects the subnamespaces as well?
Comment: Just use the "Replace All" function, and let it do the replacing of "namespace EPERP" in "Current Project". Using that "Replace All" function will also rename your "subnamespaces" as well, while keeping the rest intact, as in the ".DataAcessLayer".
Answer: That's why I always say that ReSharper is a must have for all .NET programmers.
In your post, you didn't say nothing about using 3rd tools, so make sure that each project has it's own default namespace (Project Properties -> Application), then right click at Solution -> Refactor -> Adjust Namespaces.
ReSharper will take care of all using needed due new namespace.
And I case you're using folder, it will treat the namespace like you spected, ex.: namespace MyNamespace.EPERP.MyFolder { ... } will become namespace MyNamespace.EPERP.MyNewModule.MyFolder { ... }
Answer: Why dont you Replace All through VS

(shortcut : ctrl+shift+H)

but make sure that there is nothing named after the namespace as as substring or something.
Answer: In this case it is better to do the renaming manually
Answer: I would suggest to write a small utility to do that than to do it manually. And if you are feeling a little lazy then use free tools like notepad++ to recursively find and replace namespace declaration across .cs files in a folder.
Answer: Open a file under the namespace EPERP.DataAccessLayer in your visual studio, and then change it to SOMETHINGNEW.DataAccessLayer. Once you do this you will see a small Red Box like under the word  SOMETHINGNEW.DataAccessLayer, when you click that red thing you will see the option "Rename 'EPERP' to 'SOMETHINGNEW'", when you select this option it will rename all the references of EPERP to SOMETHINGNEW.
Answer: I'm not aware of a completely automatic way to do what you are asking for.
You need to take some steps to do it, and some of the steps can be automated.
I will try to provide an answer and share experience at the same time.
First, you need a way to identify places in the files, where the namespace is actually specified, and the first file type to discover is .csproj files.
Open it as a text file in your favorite text editor. If you need to open it in Visual Studio you need to unload the project first using the right mouse button context menu in the Solution Explorer window. When you have unloaded your project this way, you can edit it using the same context menu. You can reload the project as you finished editing it.
Of course you should backup the entire solution folder before you make any change to the text files this way.
Before the backup you should exit Visual Studio. This way you make sure everything is saved on disk, because Visual Studio does not always play nice when you change something manually, and could eventually mess things up and override the file on disk with it's own version which is in memory.
Now that you have opended the .csproj file in a text editor, you are actually looking at the msbuild file format, which is in XML.
Search for the RootNamespace property:
https://msdn.microsoft.com/en-us/library/bb629394.aspx?f=255&MSPPError=-2147217396
This is the property you need to change, if you taken this path (editing .csproj as a text file).
You can also do the same specifying the Default Namespace in project properties in Visual Studio, but it's important to know that you have control, as all the project files essentially are just XML files, editable as text.
This is the first step of changing the namespace "completely", and you can't skip it, if you want all of the embedded resources and code generation to work correctly.
Second step is to change the namespace declarations and references in all of the project's .cs files, including regular cs files, and Designer.cs files, generated by aspnet designer.
You can use the "Replace in files" command, accessible with Ctrl-Shift-F to replace the text in all the .cs files where you declared or referenced that namespace.
Another option is to use ReSharper's "Adjust Namespaces" command, and I recommend to use ReSharper for all Visual Studio/C# development tasks.
Then you can browse for the namespace reference in all the files in solution folder and discover all the file xml text file types where it is referenced, such as .resx files. Those should be handled by ReSharper also.
One more thing to note, that you might wish to delete the .suo and .user files upon completion of previous steps and also clean ReSharper caches. It's a good idea to do this step after each manual editing of project files in text editor.

Bulk namespace rename


HAML Pass partial dynamically to layout in Sinatra app

Question: I am trying to build a Sinatra app with HAML and use a layout to be able to break my site down into partials:
layout.haml
!!!
%html
    %head
        = partial :head
    %body
        = partial :header
        = partial :#{@template}
        = partial :footer

Where my Sinatra app is calling layout.haml like so:
get '/test' do
    @template = "\"test/index\""

    haml :"layout"
end

To try to pull in:
views/
|----test/
    |----_index.haml

Which gives me the error:

wrong number of arguments (0 for 1..2)

I have also tried redefining a number of different combinations with no success:
@template = ":\"test/index\""
= partial #{@template}

@template = "test/index"
= partial :#{@template}

Note: I am using Sinatra Partials
Am I going about this entirely the wrong way? My brain is really suffering trying to figure out how to employ HAML for such a basic concept of DRY templating.
Answer: Ah it was so simple afterall.. With the help of this question, I realized now of course that everything is wrapped with layout.haml and I simply needed to place the appopriate yield statement.
layout.haml
!!!
%html
    %head
        = partial :head
    %body
        = partial :header
        = yield
        = partial :footer

And call the template as usual:
get '/test' do
    haml :"test/index"
end


How to have a unique local storage variable for different users in Angularjs

Question: I'm building an app using ionic framework. I have an array that i store locally using ngStorage... my problem when i logout i have to clear the $localStorage.SomeArray so that the when logged in as a different user, that user won't inherit the $localStorage.SomeArray. Is there a way to that
Comment: I wouldn't store anything that could give anything about a user away permanently in localStorage. That includes but is not limited to userids.
Comment: could you use sessionStorage instead? that goes away when the tab is closed
Comment: sessionStorage is unique to each tab/window though. Using localStorage is fine, just as long as you clear all sensitive data when no user is logged in.
Comment: personally, i don't really like the idea of clearing localStorage. that kind of requirement is problematic in a world of tab crashes. if you're only keeping it around for the duration of a session, then sessionStorage makes more sense. still, `window.onunload=function(){localStorage.SomeArray='';}` should work to clear it when they leave the page, replace the unload event with a logout one if you can/need.
Answer:
How to have a unique local storage variable for different users in Angularjs

Store it under some user-specific key, e.g.:
<code>localStorage[userKey] = [/*...the array...*/];
</code>
Comment: So i can do this localstorage[localstorage.currentuser.id]??
Comment: @teddybear123: I can't see why you'd store your current user under localStorage, but if you did, yes (with the capital S in `localStorage`)).
Comment: Just the id so i could have different local storages for different id thats logged in thanks!!


just curious if object class are usable in css

Question: the java scipts ias a follows :
<code>function Person(name,age) {
this.name = name;
this.age = age;
}
</code>
in the above object creation function, the class is Person, so can i use ".Person" within my CSS to refer it to all Person class ?
or will I still have to declare the class name in the HTML doc ?
new to coding. was just curious when i was practicing online.
Comment: The class itself is not visible for the user hence don't need any CSS, its output could, most likely using a html element, and that element need a class, which can be dynamically created, and when, you could use an inner function in the given object which will add its name to that output as a class attribute/value
Answer: No. CSS is for Elements provided by DOM, not for JS objects.
Answer: You will have to have it in the DOM, either by declaring it as a class in the HTML element or injecting it via javascript.


Undefined Pickle step (again)

Question: https://stackoverflow.com/questions/5282437/cucumber-pickle-factory-girl-given-a-returning-undefined-step - this post didn't help me a lot.
Gemfile:
gem 'rails' # 3.0.5
gem 'capybara' # 1.1.1
gem 'rspec-rails' # 2.6.1
gem 'cucumber-rails' # 1.0.5
gem 'database_cleaner'
gem 'factory_girl_rails' # 1.2.0
gem 'email_spec'
gem 'pickle' # 0.4.8

I do:
rails new pickle_test
bundle install
rails g cucumber:install
rails g rspec:install
rails g pickle --paths --email
rails g scaffold category title:string
rake db:migrate
rake db:test:prepare
cucumber

I have:
$ cucumber
Using the default profile...
Feature: Manage categories

  Scenario: list existed categories                       # features/manage_categories.feature:3
    Given a category exists, title: "First category ever" # features/manage_categories.feature:4
      Undefined step: "a category exists, title: "First category ever"" (Cucumber::Undefined)
      features/manage_categories.feature:4:in `Given a category exists, title: "First category ever"'
    When I go to the categories page                      # features/step_definitions/web_steps.rb:48
    Then I should see "First category ever"               # features/step_definitions/web_steps.rb:105

1 scenario (1 undefined)
3 steps (2 skipped, 1 undefined)
0m0.127s

You can implement step definitions for undefined steps with these snippets:

Given /^a category exists, title: "([^"]*)"$/ do |arg1|
  pending # express the regexp above with the code you wish you had
end

Note that I did nothing to configure this test app anyhow and I don't use factory_girl or anything rather then ActiveRecord. I'm confident it should work from there. Pickle itself is loaded (tested with puts), cucumber runs using environments/test.rb.
What I am missing?
Answer: Your step def is not using the correct phraseology.
The default Pickle steps (you should feel free to adapt them to your app/style) expect the following:
Given a category exists with title: "First category ever"
Cheers,
Ian
Comment: Sorry for belated feedback. It says the same even I follow the guide: You can implement step definitions for undefined steps with these snippets:

Given /^a category exists with title: "([^"]*)"$/ do |arg1|
  pending # express the regexp above with the code you wish you had
end
Comment: Question is closed - problem was in FactoryGirl.

Undefined Pickle step (again)


Reference to type 'MarshalByRefObject' claims it is defined in 'System.Runtime', but it could not be found

Question: I have been struggling with this error all day today. I'm trying to simulate a small distributed service on my computer, comprised of a remotable object, server, and client in three seperate projects. The idea is to read an XML file with a remotable object.
I have tested and calling methods which are marked as MarshalByRefObject will throw this error. If I just add and call the method without that tag it will work fine.
Here is the code for the object class:
using System.Xml;
using System.Xml.XPath;

namespace XmlViewer
{
    public class XmlViewerClass : MarshalByRefObject
    {
        string xmlFilePath;

        public XmlViewerClass(string xmlFilePath)
        {
            this.xmlFilePath = xmlFilePath;

            XPathNavigator xpath = ViewXmlDoc(xmlFilePath);
        }

        public string XmlFilePath
        {
            set { value = xmlFilePath; }
            get { return xmlFilePath; }
        }

        public XPathNavigator ViewXmlDoc(string xmlFilePath)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlFilePath);

            XPathNavigator ret = doc.CreateNavigator();
            return ret;
        }
    }
}

Here is the server:
using System;
using System.Windows.Forms;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;

namespace MyNamespaceServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public void RunServer()
        {
            try
            {
                TcpServerChannel tcp = new TcpServerChannel(1902);
                ChannelServices.RegisterChannel(tcp, true);

                RemotingConfiguration.RegisterWellKnownServiceType(
                    typeof(XmlViewer.XmlViewerClass), "XmlViewerClass",
                    WellKnownObjectMode.Singleton);

                lblStatus.Text = "Server running...";
            }
            catch (Exception ex)
            {
                lblStatus.Text = "An error has occurred... " + ex.Message;
            }
        }
    }
}

And here is the client (incomplete at this point), which is where the error is showing up - specifically the line XPathNavigator nav = p.ViewXmlDoc("music.xml");
namespace MyNamespaceClientXmlViewerFinal
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlViewerClass p = new XmlViewerClass("music.xml");
            XPathNavigator nav = p.ViewXmlDoc("music.xml");
        }
    }
}

I am very new to remoting, so it's entirely possible I'm just making some small slip up somewhere. But honestly at this point I am stumped!
Comment: "... calling methods which are marked as MarshalByRefObject will throw this error. If I just add and call the method without that tag it will work fine" these sentences makes no sense. Do you really understand what you're trying to do, or have you just blindly copy-pasted code?
Comment: You can't use remoting in a project that targets .NETCore.
Comment: @IanKemp I'm actually trying to recreate code from a software development course I'm doing. I'm trying to get clarification as I am still learning.
Answer: According to the Microsoft Documentation.

Remoting isn't supported on .NET 5+ (and .NET Core). .NET remoting was
identified as a problematic architecture. It's used for communicating
across application domains, which are no longer supported. Also,
remoting requires runtime support, which is expensive to maintain.

You must target .NET Framework 4.8 (or earlier) if you want to continue using remoting.  Alternatively, you could investigate gRPC, which is an open RPC mechanism with support in .NET 5.


React native eslint-disable-next-line react/no-unstable-nested-components

Question: I am using a custom back button in the headerLeft. I have enabled ESLINT, and it is showing the below warning.
Do not define components during render. React will see a new component type on every render and destroy the entire subtree's DOM nodes and state (https://reactjs.org/docs/reconciliation.html#elements-of-different-types). Instead, move this component definition out of the parent component "App" and pass data as props. If you want to allow component creation in props, set allowAsProps option to true.eslintreact/no-unstable-nested-components

App.tsx

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createDrawerNavigator} from '@react-navigation/drawer';
import {StatusBar, useColorScheme} from 'react-native';

import {Colors} from 'react-native/Libraries/NewAppScreen';

import {useNavigation} from '@react-navigation/native';

import {DrawerContent} from './src/navigation/drawer-content';
import {Button} from 'react-native-paper';

import Feed from './src/screens/feed';
import Article from './src/screens/article';

const Drawer = createDrawerNavigator();

const CustomDrawer = (props: any) => {
  return <DrawerContent {...props} />;
};

const BackButton = () => {
  const navigation = useNavigation();
  return (
    <Button
      icon="arrow-left-thick"
      onPress={() => navigation.goBack()}
      children={undefined}
    />
  );
};

function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  return (
    <NavigationContainer>
      {/* <SafeAreaView style={backgroundStyle}> */}
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
      <Drawer.Navigator drawerContent={CustomDrawer} initialRouteName="Feed">
        <Drawer.Screen name="Feed" component={Feed} />
        <Drawer.Screen
          name="Article"
          component={Article}
          options={{
            title: 'Timeline',
            headerLeft: () => <BackButton />,
          }}
        />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

export default App;

Answer: It could be because of the following eslint rule react/no-unstable-nested-components.
I guess according to react-navigation's guide you have defined the headerLeft prop but the above eslint rule contradicts that.
Contradiction occurred here:
<Drawer.Screen
  name="Article"
  component={Article}
  options={{
    title: 'Timeline',
    headerLeft: () => <BackButton />, // <--- this line
  }}
/>

Possible fix(es):

Disable plugin for the file: // eslint-disable react/no-unstable-nested-components (or for just one line)
Move component definition out of the component.
Edit the .eslintrc to allow component as props in this rule's settings

...
"react/no-unstable-nested-components": [
 "off" | "warn" | "error",
 { "allowAsProps": true | false }
]
...

Comment: Note: To disable for the entire file, the comment needs to look like this: `/* eslint-disable react/no-unstable-nested-components */`
This can be useful for the file that exports the Navigator (React Navigation).
Answer: If you're not passing any props to <BackButton />, which you're not, then this should work:
<Drawer.Screen
  name="Article"
  component={Article}
  options={{
    title: 'Timeline',
    headerLeft: BackButton
  }}

BackButton is a function that returns a component, i.e. <BackButton />.   So your anonymous function isn't necessary,


How to customize download filename?

Question: Drupal version: 7.14
Currently drupal save the downloaded filename as the last part of the URL, just like a file link "http://example.com/system/files/abc.txt", the default saved filename is "abc.txt".
I want to ask is how to change "abc.txt" to other filename such as "xyz.txt" while downloading.
Comment: Problem has been solved by setting download method to 'private', if it's set to 'public', you cannot do any control over the download process(that is hook_file_download cannot be called under this mode).
Comment: I looked into the function code and I think it'd be great if you could answer your own question and share your code to let others see what could be done by that hook. I bet you could earn some points too :)
Answer: For this issue there's a prerequisite,that is, your download method must be 'private', otherwise there's no chance for drupal to call your 'hook_file_download', it's important!
Here's an example from drupal's file module, change $file->filename to what you want, then return to HTTP headers.
/**
 * Implements hook_file_download().
 *
 * This function takes an extra parameter $field_type so that it may
 * be re-used by other File-like modules, such as Image.
 */

function file_file_download($uri, $field_type = 'file') {
     global $user;
     // Get the file record based on the URI. If not in the database just return.
     $files = file_load_multiple(array(), array('uri' => $uri));
     if (count($files)) {
         foreach ($files as $item) {
         // Since some database servers sometimes use a case-insensitive comparison
         // by default, double check that the filename is an exact match.
         if ($item->uri === $uri) {
             $file = $item;
             break;
         }
      }
   }
   if (!isset($file)) {
     return;
   }
//...........................other codes.........................
// Access specifically denied.
   if ($denied) {
     return -1;
   }
// Access is granted.
   $headers = file_get_content_headers($file);
   return $headers;
  }
Answer: For Drupal 7, when implementing Justin's solution, my download name was still the original filename, not the custom name I assigned to $file->filename. At the time of this writing Drupal 7's file_get_content_headers() sets
$name = mime_header_encode($file->filename);

but never uses the variable $name.
I found a few patches, but instead of patching core, I did the following:
$headers = file_get_content_headers($file);
$headers['Content-Disposition'] = 'attachment; filename="'. $file->filename .'"';
return $headers;

For my purposes, I needed the file to be downloaded, which is why I used 'attachment'. But if you need the disposition to be 'inline', then the following snippet could get you started (copied from this patch):
$inline_types = variable_get('file_inline_types', array('^text/', '^image/', 'flash$'));
$disposition = 'attachment';
foreach ($inline_types as $inline_type) {
  // Exclamation marks are used as delimiters to avoid escaping slashes.
  if (preg_match('!' . $inline_type . '!', $file->filemime)) {
    $disposition = 'inline';
  }
}

How to customize download filename?


I am making an ios app and I want to split the screen into 4 quadrants/buttons

Question: I am wondering how I can do this I pretty much want the full screen to be 4 giant buttons.
For example,
(bottom left will walk left) and (bottom right will walk right)
(top left will jump left) and (top right will jump right)
I currently have two giant buttons with left being jump left and right being jump right.
Thanks!
<code> override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {
        let location = touch.location(in: self)

        if(location.x > self.frame.size.width/2){
            jumpRight()
        }

        else if(location.x < self.frame.size.width/2){
            jumpLeft()
        }
    }
}
</code>
Comment: Why reinvent the wheel? Just create 4 `UIButtons`, add actions to them, and, using auto layout, size them appropriately?
Comment: I agree with @dfd , and if you want to make it dynamic then give them constraint according to the current height and width of `UIView`
Answer: So I put together a little class that will help you out. I added some documentation to help you understand what is happening.
<code>/// The cases of this enum correspond to the four cartesian quadrants.
enum Quadrant: CaseIterable {
    case one
    case two
    case three
    case four
}

/// Includes four methods corresponding to each quadrant. Methods are called when touches are registerd by the `FourButtonView`.
protocol FourButtonViewDelegate {
    func quadrantITouched(sender: UITapGestureRecognizer)
    func quadrantIITouched(sender: UITapGestureRecognizer)
    func quadrantIIITouched(sender: UITapGestureRecognizer)
    func quadrantIVTouched(sender: UITapGestureRecognizer)
}

/// This view has four quadrants corresponding to the four quadrants of the cartesian plane.
class FourButtonView: UIView {

    var delegate: FourButtonViewDelegate?

    /// Calls the `FourButtonViewDelegate`'s `quadrantITouched(sender: UITapGestureRecognizer)` method.
    /// - Parameter sender: Sender is the `UITapGestureRecognizer` from the button that was touched.
    @objc private func iTouched(sender: UITapGestureRecognizer)  { delegate?.quadrantITouched(sender: sender) }

    /// Calls the `FourButtonViewDelegate`'s `quadrantITouched(sender: UITapGestureRecognizer)` method.
    /// - Parameter sender: Sender is the `UITapGestureRecognizer` from the button that was touched.
    @objc private func iiTouched(sender: UITapGestureRecognizer) { delegate?.quadrantIITouched(sender: sender) }

    /// Calls the `FourButtonViewDelegate`'s `quadrantITouched(sender: UITapGestureRecognizer)` method.
    /// - Parameter sender: Sender is the `UITapGestureRecognizer` from the button that was touched.
    @objc private func iiiTapped(sender: UITapGestureRecognizer) { delegate?.quadrantIIITouched(sender: sender) }

    /// Calls the `FourButtonViewDelegate`'s `quadrantITouched(sender: UITapGestureRecognizer)` method.
    /// - Parameter sender: Sender is the `UITapGestureRecognizer` from the button that was touched.
    @objc private func ivTouched(sender: UITapGestureRecognizer) { delegate?.quadrantIVTouched(sender: sender) }

    // MARK: Sets up a button for every quadrant.
    override init(frame: CGRect) {
        super.init(frame: frame)
        for quadrant in Quadrant.allCases {
            setupButtons(quadrant: quadrant)
        }
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// `setupButtons` sets up a button for a given quadrant.
    /// - Parameter quadrant: `quadrant` is a case of the `Quadrant` enum. It determines which button to set up.
    private func setupButtons(quadrant: Quadrant) {

        /// The button to be set up.
        let button: UIButton = getButton()

        /// The `backgroundColor` of the button.
        let backgroundColor: UIColor

        /// The `topAnchor` of the button.
        let top: NSLayoutYAxisAnchor

        /// The `leftAnchor` of the button.
        let left: NSLayoutXAxisAnchor

        /// The `bottomAnchor` of the button.
        let bottom: NSLayoutYAxisAnchor

        /// The `rightAnchor` of the button.
        let right: NSLayoutXAxisAnchor

        // MARK: Uses `quadrant` to determine top and bottom anchors.
        if quadrant == .one || quadrant == .two {
            top = topAnchor
            bottom = centerYAnchor
        } else {
            top = centerYAnchor
            bottom = bottomAnchor
        }

        // MARK: Uses `quadrant` to determine left and right anchors.
        if quadrant == .one || quadrant == .four {
            left = centerXAnchor
            right = rightAnchor

        } else {
            left = leftAnchor
            right = centerXAnchor
        }

        // MARK: Uses `quadrant` to determine color and `#selector(@objc method)` method.
        switch quadrant {
        case .one:
            backgroundColor = .red
            button.addTarget(self, action: #selector(iTouched), for: .allTouchEvents)
        case .two:
            backgroundColor = .blue
            button.addTarget(self, action: #selector(iTouched), for: .allTouchEvents)
        case .three:
            backgroundColor = .yellow
            button.addTarget(self, action: #selector(iTouched), for: .allTouchEvents)
        case .four:
            backgroundColor = .green
            button.addTarget(self, action: #selector(iTouched), for: .allTouchEvents)
        }

        // MARK: Sets `backgroundColor` of button.
        button.backgroundColor = backgroundColor

        // MARK: Activates layout constraints.
        NSLayoutConstraint.activate([
            button.topAnchor.constraint(equalTo: top),
            button.leftAnchor.constraint(equalTo: left),
            button.bottomAnchor.constraint(equalTo: bottom),
            button.rightAnchor.constraint(equalTo: right)
        ])
    }

    /// This function returns a `UIButton` that is prepared for setup with auto layout.
    private func getButton() -> UIButton {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }

}
</code>


Laravel 4 display custom error pages only in production

Question: Do I understand right: if I want to display custom pages for 403, 404 etc. errors I should check whether app.debug is set to false:
if (!Config::get('app.debug')) {
    App::error(function(Exception $exception, $code)
    {
        switch ($code) {
            case 403:
                return Response::view('errors.403', array(), 403);

            case 404:
                return Response::view('errors.404', array(), 404);

            case 500:
                return Response::view('errors.500', array(), 500);

            default:
                return Response::view('errors.default', array(), $code);
        }
        Log::error($exception);
    });
}

Because, if I set App::error handler without checking app.debug I'll always get these custom pages instead of detailed info
Am I right?
Comment: You want to say use App::environment() instead of app.debug variable to check that? I've just read about environments and it's amazing, I can automatically override app.debug variable in my production environment
Comment: My first thought was to use [Laravel's environment configuration](http://four.laravel.com/docs/configuration#environment-configuration), but I could be wrong.
Comment: You can also use `if (!App::environment('local'){}` or whatever you dev environment is called.
Comment: Usually I create simple function called isProduction() as a shortcut to App:environment('production') to make things easier.
Answer: You could just move the if statement into the app::error function. So that the error is always logged, and the custom error page is only shown when app.debug is false.
App::error(function(Exception $exception, $code)
{
    Log::error($exception);

    if (!Config::get('app.debug')) {
        return Response::view('errors.index', $code);
    }
});

Comment: fix the syntax error, remove additional ')' in return statement.


Como obter as coordenadas do gps em java no android

Question: Qual a melhor forma de obter a latitude e longitude no android.
Ex. após a solicitação (toque no botão) o usuário aguarda o gps obter as coordenadas e após isso exibe-as para o mesmo.
Comment: Você mesmo não obteve uma resposta [aqui](http://pt.stackoverflow.com/q/13158/4337)?
Answer: Bom, existem várias maneiras, vou te passar uma:
Primeiro você cria um service para obter a latitude e longitude, depois é só instanciar ele quando for clicar em algum botão para obter as coordenadas.
public class GPSTracker extends Service implements LocationListener {
    private final Context mContext;

    // flag para GPS status
    boolean isGPSEnabled = false;

    // flag para network status
    boolean isNetworkEnabled = false;

    // flag para GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // A distância mínima para mudar Atualizações em metros
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 metros

    // O tempo mínimo entre as atualizações em milissegundos
    private static final long MIN_TIME_BW_UPDATES = 0; // 1 minute=1000 * 60 * 1

    // Declarar a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // obter o status GPS
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // obter o status da rede
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                //Nenhum provedor de rede está habilitado
            } else {
                this.canGetLocation = true;
                // Primeiro localização obter de provedor de rede
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    //eric

    /**
     * para de usar GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function para obter latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function para obetr longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Função para verificar GPS / Wi-Fi habilitado
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function para abrir o alerta
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // titulo da mensagem de config
        alertDialog.setTitle("Configurar GPS");

        // mensagem de configuração
        alertDialog.setMessage("GPS não Ativado. Você deseja abrir o menu de configuração?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Configuração", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // btn cancelar
        alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Exibir alerta de mensagem
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
        getLocation();
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

E depois para obter os dados na sua MainActivity, por exemplo (ao clicar em um botão):
// clicando no botao
btnShowLocation.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        // instancia o service, GPSTracker gps
        gps = new GPSTracker(MainActivity.this);

        // verifica ele
        if (gps.canGetLocation()) {
            // passa sua latitude e longitude para duas variaveis
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            // e mostra no Toast
            Toast.makeText(getApplicationContext(), "Sua localização - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
        }
    }
});

E lembrando, não esqueça das permissões:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Comment: Tentei usar mais deu location lat e long 0.0
Comment: Ok @Alessandro Barreto, tranquilo, mas se o service nao tem as coordenadas "por algum motivo" na hora do clique, como eu as resgato apos o gps obter os dados, na minha activity?
Comment: tentei usar aqui também, mas me foi retornado 0.0 em ambos os casos


If $\varphi:\mathbb{R}^2\rightarrow T$ is continuous and surjective, then $\varphi^{-1}(0,0)$ has infinitely many elements.

Question: I'd like a hint for the following problem:
Let $T=\{(x,y)\in\mathbb{R}^2:x=0\text{ or }y=0\}$. If $\varphi:\mathbb{R}^2\rightarrow T$ is continuous with the Euclidean distance and surjective, then $\varphi^{-1}(0,0)$ is infinite.
Answer: Hint: Suppose $S=\varphi^{-1}\{(0,0)\}$ is finite.  Then $\varphi$ restricts to a continuous surjection $\mathbb{R}^2\setminus S\to T\setminus\{(0,0)\}$.  What can you say about each of these spaces?
Comment: Very slick!${}{}{}{}$
Comment: @Eric Wofsey. When $X$ is a connected topological space and $A$ is a finite subset of $X$, is it always true that $X-A$ is connected?
Comment: Not always (consider $X=\mathbb{R}$, for instance).  So you have to do some work to prove it in this case.
Answer: Suppose the set $S = \varphi^{-1}(0,0)$ is finite, then the set $\mathbb{R^2}\setminus S$ is connected and the map $\varphi$ restricted to $\mathbb{R^2}\setminus S$ is continuous. Since continuous image of a connected set must be connected, the restriction map can not be continuous.(because the set $T \setminus \{(0, 0)\}$ is not connected)
Answer: In fact, $\varphi ^{-1}(\{(0,0)\})$ is uncountable. If not, $\varphi ^{-1}(\{(0,0)\})$ is countable. It's well known that $\mathbb R^2 $ minus a countable set is connected (in fact, it's path connected). So then we have $\varphi $ mapping the connected set $\mathbb R^2\setminus \varphi ^{-1}(\{(0,0)\})$ onto the disconnected set $T\setminus \{(0,0)\},$ contradiction.


Custom Content types nodes with Nodeblocks module

Question: I have been unsuccessful in accomplishing the following:
I am using the Nodeblocks module and trying to follow its documentation for using it with a custom content type.  My custom content type machine name is content_block. I want a client to be able to create a new content_block and then be able to place it wherever he wants using the Admin > Blocks page.
The content_block content type has these fields (machine names - purpose):

title - Title of the block (nodeblock) that will be seen on the Blocks administration page. Will be hidden from output.
field_headline_level - stores a value like, "h2", "h3", "h4", etc. To be used to customize the HTML Headline tag. Will be hidden from output.
field_headline - The actual words for the headline
field_content - Content to be displayed below the headline

I've been trying to follow the Nodeblocks documentation (linked above) as well as the Drupal 7 Template Suggestions but I can not get it to work.  I keep running into nested template problems, such as the default block template wrapping around the node type template and getting double headlines.  I also can't figure out the correct syntax to display the various content_block fields.
Can anyone out there help me out or point me to a "Node Templates for Dummies" article?  I've done lots of searches on Google, but can't find anything very helpful.
Answer: Figured it out by getting my head around what Drupal calls "Template Suggestions".  The Theme Developer Module helped.
For my particular use case I had to create a template file called block--nodeblock.tpl.php to override the default block output. I basically stripped everything out of the default except the actual content so that this was all that was left: <?php print $content ?>.
Then I made a node--content_block.tpl.php template to override this particular content type's display the way I wanted it.  I had to add some trim() methods to strip out some leading spaces that Drupal insisted on inserting.
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php if($content['field_headline']): ?>
        <?php print render($title_prefix); ?>
        <<?php print trim(render($content['field_headline_level'])) . ' ' . $title_attributes; ?>><?php print trim(render($content['field_headline'])); ?></<?php print trim(render($content['field_headline_level']));?>>
        <?php print render($title_suffix); ?>
    <?php endif ?>

    <div class="content"<?php print $content_attributes; ?>>
        <?php print trim(render($content['field_content'])); ?>

The last thing I had to do was create a template to strip out all the extra tags that the Drupal default field comes with.  I did so with this file, named field--content_block.tpl.php:
<?php foreach ($items as $delta => $item) : ?>
      <?php print render($item); ?>
<?php endforeach; ?>


Get IIS Bindings from many webservers using powershell remoting, invoke command and module webadministration

Question: Right now I made a small script to see my actual webbindings on a server.
Import-Module WebAdministration;

$today = Get-Date -format M.d.yyyy
$machine = hostname
function IISRport

{
Get-ChildItem -path IIS:\Sites | out-file "\\server01\d$\_utils\PowerShell Scripts\IISexport\IISExport$machine$today.txt"
}

IISReport

This wil outfile my IIS bindings to txt which works brilliant.
I now need to invoke that command to several other servers and save the output file on one server. since the machine name will be diffrent I expect as many outputs as servers.
I tried for example the following :
icm -comp server02 {get-childitem -path IIS:\Sites}

But than the imported Module webadministration is not working, since I only loaded on one server. So I tried to load that remotely using :
icm -comp server02 {import-module webadministration}

without success.
How to achieve that?
Answer:
This will get the data from all machines defined in $machines and output to \\server01\d$_utils\PowerShell Scripts\IISexport\.
$today = Get-Date -format M.d.yyyy
$machines = @("server01","server02")
foreach($machine in $machines) {
    icm -comp $machine { param($machine,$today)
        import-module webadministration;
        Get-ChildItem -path IIS:\Sites |
        out-file "\\server01\d$\_utils\PowerShell Scripts\IISexport\IISExport$machine$today.txt"
    } -ArgumentList $machine,$today
}

You can of course change the output path( and import list of machines from a file,AD or some other source).
Comment: thanks, seems to be exactly what I needed. Interesting that I get an error "access denied" OpenError: (:) [Out-File], UnauthorizedAccessException   - even though i am domain admin. hmm
Comment: That's a double hop authentication issue, you can read more about it [here](http://stackoverflow.com/questions/21752707/cannot-find-path-sharepath-because-it-does-not-exist/21757438).. Best thing you can do is to dump the report to the same location on all boxes and pull them all at the end.
Comment: yes thats what i thought about. I guess that's what I do... thanks


How can I rerender my redux state after triggering an action with hooks?

Question: I'm trying to update a state from my Redux by triggering an action that calls out an API.
I have tried debugging by using a console log on actions and the reducer to see whether the states are changing.
The API returns an object and stores it into the reducer and it seems to work just fine but the Screen UI didn't re-render or update the reducer state.
I tried using useState React Hook function to test whether the issue comes from my component or the dispatch function and turns out the issue is from Redux dispatch hook.
In this case, when I press on my ToggleSwitch component, the action triggers the API and store the new value to the reducer. But the state on the UI side isn't updating.
Here's my code
reducer:
const light_list = (state: object = {}, action) => {
    if (action.type === C.FETCH_ALL_LIGHTS) {
        state = action.payload;
        return state;
    } else if (action.type === C.CHANGE_LIGHT_STATE) {
        _.merge(state[action.id].state, action.payload);
        return state;
    } else {
        return state;
    }
}

action:
export const UpdateLightState = (lampID, jsondata) => async (dispatch, getState) => {
    const state = getState();
    const { id }: BridgePairedType = state.pairing_bridge;
    const bridge: ConfigurationTypes = state.bridge_list[id];

    const response = await axios({
        url: `http://${bridge.ipaddress}/api/${bridge.username}/lights/${lampID}/state`,
        method: 'PUT',
        data: jsondata
    });
    if (response && response.data) {
        var payload = {};
        response.data.map((data) => {
            let key = Object.keys(data.success)[0].substring(Object.keys(data.success)[0].lastIndexOf('/') + 1);
            let value = Object.values(data.success)[0];
            payload[key] = value;
        })
        dispatch({
            type: C.CHANGE_LIGHT_STATE,
            id: lampID,
            payload: payload
        })
    }
}

Screen UI:
function ControlBulbScreen() {
    const { colors } = theme;
    const lampID = useNavigationParam('lampID');

    const dispatch = useDispatch();
    const light: LightTypes = useSelector(state => state.light_list);
    const updatelight = useCallback((lampID: string, json: LightUpdateStates) => dispatch(UpdateLightState(lampID, json)), [dispatch]);

    const bordercolor = { borderColor: colors.white }

    return (
        <Block style={styles.container}>
            <Block flex={false} center row space="between" style={styles.header}>
                <Text h1 googlebold>{light[lampID].name}</Text>
                <ToggleSwitch
                    offColor="#DDDDDD"
                    onColor={theme.colors.secondary}
                    onToggle={() => updatelight(lampID, { on: !light[lampID].state.on })}
                    isOn={light[lampID].state.on}
                />
            </Block>
        </Block>
    )
}

const styles = StyleSheet.create({
    container: {
        paddingHorizontal: theme.sizes.base * 2,
        backgroundColor: theme.colors.background
    },
    header: {
        marginTop: 40
    },
    textControl: {
        textAlign: 'left',
        fontSize: 16
    },
    controlrow: {
        marginTop: 20,
        marginBottom: 10
    },
    thumb: {
        width: 25,
        height: 25,
        borderRadius: 25,
        borderColor: 'white',
        borderWidth: 3,
        backgroundColor: theme.colors.secondary,
    },
    textInput: {
        height: 30,
        borderBottomWidth: .5,
        borderRadius: 0,
        borderWidth: 0,
        color : theme.colors.white,
        textAlign: 'left',
        paddingBottom: 10
    }
});

export default ControlBulbScreen;

Answer: I guess the issue is in your reducer. You should not mutate your state directly. What I suggest is to create a new state instead what you need to return in each case.
The following statement will do the job for you: const newState = {...state}.
Try the following:
const light_list = (state: object = {}, action) => {
    if (action.type === C.FETCH_ALL_LIGHTS) {
        return action.payload;
    } else if (action.type === C.CHANGE_LIGHT_STATE) {
        const newState = {...state};
        _.merge(newState[action.id].state, action.payload);
        return newState;
    } else {
        return state;
    }
}

Read further about Immutable Update Patterns in the documentation.
I hope that helps!
Comment: Thank you very much for the detail explanation. It works perfectly now :D
Comment: Is it recommended to add a new state for all cases or just for updating/ delete state?
Comment: @FirmanJamal In those cases when you want to change the `state` only. If there is no change on the `state` it is enough to have `return state`.
Comment: What about inserting a new objects into the state?
Comment: @FirmanJamal If you have want add something new than you shouldn't mutate the original object. You should copy and add there your new object. I hope that clarifies.


Problema ao Contar os CheckBox selecionados. PHP

Question: Tenho alguns checkBox que são uma consulta no BD. Estou precisando pegar os campos selecionados e depois fazer uma divisão mas não esta funcionando.
<form action="contas1.php" method="POST">

                                    Nome Conta:
                                    <input type="text" class="form-control" name="nome_conta">

                                    Valor:
                                    <input type="number" class="form-control" name="valor">

                            <?php
                                    include("conexao.php");
                                    $consulta = "SELECT NOME as nome,EMAIL as email FROM `usuario`";
                                    $result = mysqli_query($conexao,$consulta) or die(mysql_error());

                                     while ($membros = mysqli_fetch_array($result,MYSQLI_ASSOC))
                                    {
                                        echo '
<input type="checkbox" name="members[]" value="' . $membros['email'] . '" /> ' . $membros['nome'] . '
';
                                    }

                            ?>

                            <button type="submit" class="btn btn-default">Adicionar Conta</button>

                        </form>

<?php
include("conexao.php");

$nomeconta = $_POST['nome_conta'];
$valor = $_POST['valor'];
$email_usuario = $_COOKIE['email_usuario'];

$valor = str_replace(',', '.', $_POST['valor']);// Troca de virgula por ponto
$contChkBox = count($_POST['members']);// Contando os membros selecionados
$valor = round($valor / $contChkBox, 2); // Arredondando o valor e fazendo a divisão pelos os campos selecionados

$setNovaConta = atualizaConta($conexao,$_POST['nome_conta'],$_POST['valor'],$email_usuario);

function atualizaConta($conexao,$nome_conta,$valor,$email_usuario){
    try{
        $sql = "UPDATE usuario SET saldo = saldo + $valor WHERE email = '$email_usuario'";
        if (!mysqli_query($conexao,$sql)) echo "Erro ao gravar dados: " .mysqli_error($conexao);
    }catch(Exception $e){
echo "Erro no sql" .$e->getMessage();}
mysqli_close($conexao);
}

?>
Answer: Use JQuery:
$('input[type=checkbox]').on('change', function () {

    var total = $('input[type=checkbox]:checked').length;

    $('#contador').attr('data-value',total);

    $('#contador').text(total + (total > 1 ? ' selecionados' : ' selecionado'));
});


A continous extension of the group of permutation matrices

Question: For any $n \in \mathbb{N}$, the collection $\mathcal{P}_n$ of permutation matrices is obtained by permuting the rows of the $n \times n$ identity matrix. Under the operation of matrix multiplication, $\mathcal{P_n}$ is a subgroup of $\mathcal{G_n}$ -- the subgroup of  $n \times n$ orthogonal matrices $\mathcal{O}_n$ that keeps the vector $e = (1, \ldots, 1)^t \in \mathbb{R}^n$ fixed.
Note that $\mathcal{G_n} \cong \mathcal{O}_{n-1}$. Is $\mathcal{G_n}$ the smallest infinite Lie subgroup  of $\mathcal{O}_n$ containing $\mathcal{P_n}$?
Basically, can $\mathcal{G_n}$ be a "continuous" extension of $\mathcal{P_n}$?
Comment: By "smallest" infinite Lie group, do you mean of the smallest cardinality?
Comment: I mean in the inclusion sense. Let me try to edit the question to make it more clear.
Comment: There isn't a smallest in the inclusion sense. You can find families of nested infinite groups whose intersection is $\mathcal{P}_n$.
Comment: Are they Lie groups? Find me one Lie group that is contained in $\mathcal{G}_n$.
Comment: $\mathcal{G}_n$ is not smallest in the inclusion sense in that not every infinite Lie subgroup of $GL(n)$ which contains $\mathcal{P}_n$ also contains $\mathcal{G}_n$. For instance, the group $\{2^mP:P\in\mathcal{P}_n,m\in\mathbb{Z}\}$, is an infinite Lie subgroup, but it does not contain $\mathcal{G}_n$.
Comment: Thanks. I should add that I only want to look at unitary matrices.
Answer: Let $G$ be an infinite Lie group satisfying $\mathcal{P}_n\le G\le\mathcal{O}_{n-1}$. Since $\mathcal{O}_{n-1}$ is compact, any $0$-dimensional subgroup is finite. Therefore, $G$ has dimension $\ge 1$. This implies that the Lie algebra $\mathfrak{g}=\text{Lie}(G)$ contains a nonzero element $\gamma\in\mathfrak{g}\subseteq\mathfrak{o}_{n-1}$. The set $\{\text{Ad}_P(\gamma):P\in\mathcal{P}_n\}$ spans $\mathfrak{o}_{n-1}$, so $\mathfrak{o}_{n-1}\subseteq\mathfrak{g}$ and thus $\mathfrak{g}=\mathfrak{o}_{n-1}$. Since $\mathcal{P}_n$ (and thus $G$) contains an element in each connected component of $\mathcal{O}_{n-1}$, this implies $G=\mathcal{O}_{n-1}$. Thus there are no infinite proper Lie subgroups of $\mathcal{O}_{n-1}$ that contain $\mathcal{P}_n$.
$\mathcal{O}_{n-1}$ is an extension of $\mathcal{P}_n$, and it is in a limited sense "locally optimal", but there are other extensions. It would be natural, for instance, to require that the extension be compact and connected, and while it's still difficult to find a tenable notion of optimality, at least each finite groups has such an extension.
Comment: After projecting out $(1,\dots,1)$, we get the standard representation of $\mathcal{P}_n$, which acts by permuting the vertices $e^{(1)},\dots,e^{(n)}$ of a regular $n$-simplex centered at the origin. The matrices $$\left\{A^{(\alpha\beta)}_{ij}=e^{(\alpha)}_ie^{(\beta)}_j-e^{(\beta)}_ie^{(\alpha)}_j\right\}_{\alpha,\beta\in\{1,\dots,n\},\alpha\neq\beta}$$ contain a basis for $\mathfrak{o}_{n-1}$, and conjugating by elements of $\mathcal{P}_n$ acts transitively on $\{A^{(\alpha\beta)}\}$, so one (and thus any) nonzero $\text{Ad}_{\mathcal{P}_n}$-orbit spans $\mathfrak{o}_{n-1}$.
Comment: Thanks. Can you elaborate on why $\{\text{Ad}_P(\gamma):P\in\mathcal{P}_n\}$ spans $\mathfrak{o}_{n-1}$?
Comment: It might be possible to agrue that $\mathcal{O}_{n-1}$ doesn't seem like a natural extension for $\mathcal{P}_n$, but I was trying to search for a "continuous" group that has the symmetries of $\mathcal{P}_n$, and $\mathcal{G}_n$ was a natural candidate. I am trying to see if that position can be justified.
Answer: No!  $\mathcal{P}_n$ is a 0-dimensional Lie group, and is clearly the smallest Lie group that contains $\mathcal{P}_n$.  It may be disconnected alright, but any subgroup of $O(n)$ containing $\mathcal{P}_n$ must be disconnected since $\mathcal{P}_n$ contains orientation-reversing elements.
Comment: Thanks. I am not very familiar with Lie groups to have realized this exception. I perhaps want to ask about the smallest infinite Lie group containing $\mathcal{P}_n$ then.
Comment: Then the answer is yes if you insist on putting it inside some compact Lie subgroups of $GL(n,\mathbb{F})$ and no otherwise, as @Kajelad shows in his answer.
Comment: Thanks. Can you confirm Kajelad's arguments? It will take me a while to verify them since I am not that familiar with Lie groups.


Getting JSON object from localhost in android

Question: I need to get data from my localhost. My code is shown below:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

 // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    String url = "http://10.0.2.2:8080/";

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        JSONArray value = json.getJSONArray("one");
        String output = value.toString();
        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(output);

        // Set the text view as the activity layout
        setContentView(textView);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
public class JSONParser {

    InputStream is = null;
     JSONObject jObj = null;
     String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

However my app crashes on opening. Can someone help me out on where i am going wrong? For your info, i set up the local host by running a python script using web.py
Logcat error is below:
08-03 08:55:47.093: E/AndroidRuntime(797): FATAL EXCEPTION: main
08-03 08:55:47.093: E/AndroidRuntime(797): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.customview/com.example.customview.MainActivity}: android.os.NetworkOnMainThreadException
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.os.Looper.loop(Looper.java:137)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.main(ActivityThread.java:5041)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.lang.reflect.Method.invokeNative(Native Method)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.lang.reflect.Method.invoke(Method.java:511)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-03 08:55:47.093: E/AndroidRuntime(797):  at dalvik.system.NativeStart.main(Native Method)
08-03 08:55:47.093: E/AndroidRuntime(797): Caused by: android.os.NetworkOnMainThreadException
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-03 08:55:47.093: E/AndroidRuntime(797):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-03 08:55:47.093: E/AndroidRuntime(797):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-03 08:55:47.093: E/AndroidRuntime(797):  at libcore.io.IoBridge.connect(IoBridge.java:112)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-03 08:55:47.093: E/AndroidRuntime(797):  at java.net.Socket.connect(Socket.java:842)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-03 08:55:47.093: E/AndroidRuntime(797):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.example.customview.MainActivity$JSONParser.getJSONFromUrl(MainActivity.java:75)
08-03 08:55:47.093: E/AndroidRuntime(797):  at com.example.customview.MainActivity.onCreate(MainActivity.java:36)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.Activity.performCreate(Activity.java:5104)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-03 08:55:47.093: E/AndroidRuntime(797):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-03 08:55:47.093: E/AndroidRuntime(797):  ... 11 more

Comment: *However my app crashes on opening* => find and post the stacktrace.
Comment: ` String url = "http://10.0.2.2:8080/";` hmm, you take data from no where. where is a file located?
Comment: its my local host. I have a python dict in it. Its initialized as {"one":1,"two",2}
Comment: possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception)
Answer: You are trying to do your network operation on Main Thread / UI Thread, that's why it gives RunTimeException and NetworkOnMainThreadException. Take a look at this line
08-03 08:55:47.093: E/AndroidRuntime(797): Caused by: android.os.NetworkOnMainThreadException

Do your network operations on a background thread, e.g use an AsyncTask.
Comment: I do not know how to implement an AsyncTask. Can you help me out?
Comment: take a look at this one http://www.survivingwithandroid.com/2013/05/build-weather-app-json-http-android.html?m=1


Adding timestamp to minutes

Question: I have a DataFrame df with 200 rows. The first few rows look like the following:
+--------------+----------+----------------+
|Customer name | Arrival  | Actual Arrival |
+--------------+----------+----------------+
| Customer 21  |       20 |                |
| Customer 22  |       30 |                |
| Customer 23  |       20 |                |
| Customer 24  |       10 |                |
| Customer 25  |       20 |                |
+--------------+----------+----------------+

The Arrival column shows the arrival time minute from the start time. So I want to create the Actual arrival column by adding a fixed timestamp (Start time) to the Arrival column values.
Eg: if Start time is 07:00;
+--------------+----------+----------------+
|Customer name | Arrival  | Actual Arrival |
+--------------+----------+----------------+
| Customer 21  |       20 |    07:20       |
| Customer 22  |       30 |    07:30       |
| Customer 23  |       20 |    07:20       |
| Customer 24  |       10 |    07:10       |
| Customer 25  |       60 |    08:00       |
+--------------+----------+----------------+

How to do this in python??
Answer: Can you try the following:
import datetime
actual_start_time = datetime.time(7, 0)
start_time = datetime.datetime.combine(datetime.datetime.today().date(), actual_start_time)
df['Actual Arrival'] = df['Arrival'].apply(lambda x: start_time + datetime.timedelta(minutes=x))

Example:
>>> df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]).T
>>> df.columns = ['name', 'Arrival']
>>> df
   name  Arrival
0     1        5
1     2        6
2     3        7
3     4        8
>>> start_time = datetime.datetime.strptime('2019-05-17 7:0:0', '%Y-%m-%d %H:%M:%S')
>>> df['Actual Arrival'] = df['Arrival'].apply(lambda x: start_time + datetime.timedelta(minutes=x))
>>> df
   name  Arrival      Actual Arrival
0     1        5 2019-05-17 07:05:00
1     2        6 2019-05-17 07:06:00
2     3        7 2019-05-17 07:07:00
3     4        8 2019-05-17 07:08:00

If you want only the time, you can do the following:
>>> df['Actual Arrival'] = df['Arrival'].apply(lambda x: (start_time + datetime.timedelta(minutes=x)).time())
>>> df
   name  Arrival Actual Arrival
0     1        5       07:05:00
1     2        6       07:06:00
2     3        7       07:07:00
3     4        8       07:08:00

Comment: Let me know if you have any issues
Comment: Thanks Jeril. This works.
Is there anyway i can define Start time as time (not as datetime) so that i dont have to strip time in the lambda function?
Comment: I guess time delta works with `datetime.datetime` and not with `datetime.time`, you need to combine `datetime.time` with `datetime.datetime.today()`. Let me know if you want that
Answer: Try this if you want only use time() for base time:
import datetime
arrival = 20
base = datetime.time(7, 0, 0)  # 07:00:00 or whatever your base time is.
actual_arrival = datetime.time(base.hour, base.minute + arrival, base.second)

This outputs:
07:20:00

EDIT: Note that in the approach above, the arguments to time() must be valid and if your minute becomes greater than 59, it won't work.
As a workaround, you can define a helper function to do that:
def add_times(op1, op2):  # two tuples in this format: (h, m, s)
    hour = op1[0] + op2[0]
    minute = op1[1] + op2[1]
    second = op1[2] + op2[2]

    if second >= 60:
        minute += 1
        second -= 60

    if minute >= 60:
        hour += 1
        minute -= 60

    if hour >= 24:
        hour -= 24

    return (hour, minute, second)

and change the code to:
base_time = (7, 0, 0)  # (hour, minute, seconds)
base = datetime.time(*base_time)  # If you want to have it as a time object in your code. It is redundant now.
actual_arrival = datetime.time(*add_times(base_time, (0, 20, 0)))

But I think it is no longer a datetime approach to solve your problem.
Comment: this wont work when the `arrival` is greater than 59, you will get the following error `ValueError: minute must be in 0..59`
Answer: import datetime
data = {'customers': {0: 'Customer 21',
  1: 'Customer 22',
  2: 'Customer 23',
  3: 'Customer 24',
  4: 'Customer 25'},
 'arrival': {0: 20, 1: 30, 2: 20, 3: 10, 4: 60}}

df = pd.DataFrame(data)

df['actual arrival'] = df.arrival.apply(lambda x:(pd.to_datetime(datetime.datetime.today().date())+pd.offsets.Timedelta(hours=7,minutes=x)).strftime('%H:%M'))

Adding timestamp to minutes


How to extract unique events from a log file and count them?

Question: I have a shoutcast connection log file and want to find out which clients are used and how often. The log file is pretty huge (around 100mb) with entries from the last 3 years. The log entries look like this (IPs have been randomized!):
<03/23/13@15:46:25> [dest: 126.96.36.199] starting stream (UID: 25477)[L: 2]{A: Internet%20Explorer%207}(P: 1)
<03/23/13@15:46:34> [dest: 18.104.22.168] connection closed (9 seconds) (UID: 25477)[L: 1]{Bytes: 403705}(P: 1)
<03/23/13@16:24:36> [dest: 188.8.131.52] starting stream (UID: 25478)[L: 2]{A: WMPlayer/10.0.0.364}(P: 1)
<03/23/13@16:40:56> [dest: 184.108.40.206] connection closed (981 seconds) (UID: 25478)[L: 1]{Bytes: 15938209}(P: 1)
<03/23/13@16:41:29> [dest: 220.127.116.11] starting stream (UID: 25479)[L: 2]{A: WinampMPEG/5.50}(P: 1)
<03/23/13@16:41:40> [dest: 220.127.116.11] connection closed (11 seconds) (UID: 25479)[L: 1]{Bytes: 432719}(P: 1)
<03/23/13@17:51:29> [dest: 220.127.116.11] starting stream (UID: 25480)[L: 2]{A: WinampMPEG/5.50}(P: 1)
<03/23/13@18:07:48> [dest: 220.127.116.11] connection closed (979 seconds) (UID: 25480)[L: 1]{Bytes: 15919475}(P: 1)
<03/23/13@18:18:48> [dest: 184.108.40.206] starting stream (UID: 25481)[L: 2]{A: TapinRadio}(P: 1)
<03/23/13@18:19:07> [dest: 220.127.116.11] connection closed (19 seconds) (UID: 25481)[L: 1]{Bytes: 417192}(P: 1)
<03/23/13@18:34:45> [dest: 184.108.40.206] starting stream (UID: 25482)[L: 2]{A: Internet%20Explorer%207}(P: 1)
<03/23/13@18:34:46> [dest: 220.127.116.11] connection closed (2 seconds) (UID: 25482)[L: 1]{Bytes: 282751}(P: 1)

I want to extract every unique client and in addition count how often this kind of client is used. For the log above the result should look like that:
Internet%20Explorer%207   2
WMPlayer/10.0.0.364       1
WinampMPEG/5.50           2
TapinRadio                1

At first, I simply filtered all entries that are useless. (Sorry for using cat.)
cat shoutcast.log | grep "starting stream" > filtered.txt

Result looks like that:
<03/23/13@15:46:25> [dest: 188.8.131.52] starting stream (UID: 25477)[L: 2]{A: Internet%20Explorer%207}(P: 1)
<03/23/13@16:24:36> [dest: 22.214.171.124] starting stream (UID: 25478)[L: 2]{A: WMPlayer/10.0.0.364}(P: 1)
<03/23/13@16:41:29> [dest: 220.127.116.11] starting stream (UID: 25479)[L: 2]{A: WinampMPEG/5.50}(P: 1)
<03/23/13@17:51:29> [dest: 18.104.22.168] starting stream (UID: 25480)[L: 2]{A: WinampMPEG/5.50}(P: 1)
<03/23/13@18:18:48> [dest: 22.214.171.124] starting stream (UID: 25481)[L: 2]{A: TapinRadio}(P: 1)
<03/23/13@18:34:45> [dest: 22.214.171.124] starting stream (UID: 25482)[L: 2]{A: Internet%20Explorer%207}(P: 1)

But what now? I'm a bit lost, how to access the information in the {A: } brackets?
Answer: try this awk line:
 awk -F'{A: |}' '/starting/{a[$2]++}END{for(x in a)print x" : "a[x]}' input

test with your data:
kent$  cat ff
<03/23/13@15:46:25> [dest: 220.127.116.11] starting stream (UID: 25477)[L: 2]{A: Internet%20Explorer%207}(P: 1)
<03/23/13@15:46:34> [dest: 220.127.116.11] connection closed (9 seconds) (UID: 25477)[L: 1]{Bytes: 403705}(P: 1)
<03/23/13@16:24:36> [dest: 184.108.40.206] starting stream (UID: 25478)[L: 2]{A: WMPlayer/10.0.0.364}(P: 1)
<03/23/13@16:40:56> [dest: 188.8.131.52] connection closed (981 seconds) (UID: 25478)[L: 1]{Bytes: 15938209}(P: 1)
<03/23/13@16:41:29> [dest: 22.214.171.124] starting stream (UID: 25479)[L: 2]{A: WinampMPEG/5.50}(P: 1)
<03/23/13@16:41:40> [dest: 18.104.22.168] connection closed (11 seconds) (UID: 25479)[L: 1]{Bytes: 432719}(P: 1)
<03/23/13@17:51:29> [dest: 18.104.22.168] starting stream (UID: 25480)[L: 2]{A: WinampMPEG/5.50}(P: 1)
<03/23/13@18:07:48> [dest: 184.108.40.206] connection closed (979 seconds) (UID: 25480)[L: 1]{Bytes: 15919475}(P: 1)
<03/23/13@18:18:48> [dest: 18.104.22.168] starting stream (UID: 25481)[L: 2]{A: TapinRadio}(P: 1)
<03/23/13@18:19:07> [dest: 126.96.36.199] connection closed (19 seconds) (UID: 25481)[L: 1]{Bytes: 417192}(P: 1)
<03/23/13@18:34:45> [dest: 18.104.22.168] starting stream (UID: 25482)[L: 2]{A: Internet%20Explorer%207}(P: 1)
<03/23/13@18:34:46> [dest: 184.108.40.206] connection closed (2 seconds) (UID: 25482)[L: 1]{Bytes: 282751}(P: 1)

kent$  awk -F'{A: |}' '/starting/{a[$2]++}END{for(x in a)print x" : "a[x]}' ff
WMPlayer/10.0.0.364 : 1
TapinRadio : 1
WinampMPEG/5.50 : 2
Internet%20Explorer%207 : 2


Installed cocos2d-objc but it says cocos2d swift

Question: I have application which uses cocos2d, and it worked fine before.
I updated cocos2d-obj in myapp project.
After that, my application stop after splash screen.
What the mysterious point is I surely installed the cocos2d-objc
from here, but there are some messages in log that say 'cocos2D-Swift'....??
I had some misunderstanding...??
error  log below
<code>cocos2d: Cocos2D-Swift version 3.4.3-develop
cocos2d: compiled with Profiling Support: NO
cocos2d: OS version: 9.2 (0x09020000)
cocos2d: 64 bit runtime
cocos2d: Multi-threaded rendering: 0
cocos2d: OpenGL Rendering enabled.cocos2d: GL_VENDOR:    Apple Inc.
cocos2d: GL_RENDERER:  Apple Software Renderer
cocos2d: GL_VERSION:   OpenGL ES 2.0 APPLE-12.0.40
cocos2d: GLSL_VERSION: OpenGL ES GLSL ES 1.00
cocos2d: GL_MAX_TEXTURE_SIZE: 4096
cocos2d: GL_MAX_TEXTURE_UNITS: 8
cocos2d: GL_MAX_SAMPLES: 4
cocos2d: GL supports PVRTC: YES
cocos2d: GL supports BGRA8888 textures: YES
cocos2d: GL supports NPOT textures: YES
cocos2d: GL supports discard_framebuffer: YES
cocos2d: GL supports shareable VAO: NO
cocos2d: CCGraphicsBufferClass: CCGraphicsBufferGLUnsynchronized
cocos2d: CCGraphicsBufferBindingsClass: CCGraphicsBufferBindingsGL
cocos2d: CCRenderCommandDrawClass: CCRenderCommandDrawGL
2016-02-20 06:08:59.312 myapp[2859:886706] cocos2d: viewDidLoad
cocos2d: Cocos2D-Swift version 3.4.3-develop
cocos2d: compiled with Profiling Support: NO
cocos2d: OS version: 9.2 (0x09020000)
cocos2d: 64 bit runtime
cocos2d: Multi-threaded rendering: 0
cocos2d: OpenGL Rendering enabled.cocos2d: GL_VENDOR:    Apple Inc.
cocos2d: GL_RENDERER:  Apple Software Renderer
cocos2d: GL_VERSION:   OpenGL ES 2.0 APPLE-12.0.40
cocos2d: GLSL_VERSION: OpenGL ES GLSL ES 1.00
cocos2d: GL_MAX_TEXTURE_SIZE: 4096
cocos2d: GL_MAX_TEXTURE_UNITS: 8
cocos2d: GL_MAX_SAMPLES: 4
cocos2d: GL supports PVRTC: YES
cocos2d: GL supports BGRA8888 textures: YES
cocos2d: GL supports NPOT textures: YES
cocos2d: GL supports discard_framebuffer: YES
cocos2d: GL supports shareable VAO: NO
cocos2d: CCGraphicsBufferClass: CCGraphicsBufferGLUnsynchronized
cocos2d: CCGraphicsBufferBindingsClass: CCGraphicsBufferBindingsGL
cocos2d: CCRenderCommandDrawClass: CCRenderCommandDrawGL
2016-02-20 06:09:00.056 myapp[2859:886706] cocos2d: animation started with frame interval: 60.00
2016-02-20 06:09:00.060 myapp[2859:886706] cocos2d: surface size: 960x1704
(lldb)
</code>
error happens here
<code>// override default logic
- (void)runWithScene:(CCScene*) scene
{
    NSAssert( scene != nil, @"Argument must be non-nil");
    NSAssert(_runningScene == nil, @"This command can only be used to start the CCDirector. There is already a scene present.");

    [self pushScene:scene];

    NSThread *thread = [self runningThread];

// error happned here.
    [self performSelector:@selector(drawScene) onThread:thread withObject:nil waitUntilDone:YES];
       Thred 1: EXEC_BAD_ACCESS(code=1,address=0x0)
}
</code>
Answer: Cocos2D-Swift was just a marketing name. Apportable company which sponsored us back in the day called it that way to attract more people.
Now when Apportable bankrupted, we changed the name back to Cocos2D-ObjC. Even though it is full Swift enabled, it has no Swift code internally.
Update to last stable version (3.4.0) or to the newest 3.5-RC which is due to be released soon.
Comment: I understood. I have developped my application with sprite builder/Apportable. I am surprised that Apportable was bankrupted. I will try Cocos-2D without apportable/spritebuilder support.
Comment: We still support sprite builder, but without Apportable's Android plugin