Failed to copy list of files to another folder

Question: I have a text file called "list.txt" that contain all the directories of the files that need to be copied to a new folder (dir_newfolder). I wrote the code like below:
for file in $(cat list.txt);  do cp ${file} dir_newfolder;  done
I got list of errors: cp:"file_name":No such file or directory. The file_names are the lines pulled out from the "list.txt". But when I copy each file_names from the error message and use cp to copy to the new folder. There is no error.
I am using mac os terminal.
Thanks in advance.
Comment: The two things that come to mind are weird characters in the file (maybe spaces, DOS/Windows line endings, something like that). Run `set -x` before the `for` loop to turn on execution tracing, and see if the `cp` commands it's executing match what you expect. The other one is things being in the wrong directory -- are the files (the ones to be copied) in the same directory you're "in" when you run this loop?
Comment: Hello, Thank you for the suggestions. I am new to bash comments. I have tried the ``set -x`` command, but it gives me a bunch of output that I don't know. Could you specify how I should use ``set -x`` and what should I see from this?
Comment: By the way, thank you for point out the directory issue. I am using the absolute directory. I guess in this case, it does not matter whether the files and scripts are in the same folder, right?
Comment: You need to run the `set -x` command in the same shell context as what you want to trace. So if the `for file ...` loop is in a shell script, put `set -x` in the script (before the `for file ...` loop). If you're just typing that `for file ...` loop in an interactive shell, type in `set -x` before it (and `set +x` afterward, to turn tracing off). In an interactive shell, you may see a lot of other things happening as well, like updating the shell prompt; you'll have to look through the output for the relevant bits (the `cp ...` commands).
Comment: I have tried the ``set -x``, which is helpful. I found out the file directory in the list.txt is not set as ``/Home/dir/file_name``. It was ``~/dir/file_name?``. Thank you for helping me!
Comment: See [this question](https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash) for options to expand `~` to the home directory path (but don't use any of the ones that involve `eval` -- it's likely to cause other problems).
Answer: Copy a file or folder locally
In the Terminal app  on your Mac, use the cp command to make a copy of a file.
For example, to copy a folder named Expenses in your Documents folder to another volume named Data:
% cp -R ~/Documents/Expenses /Volumes/Data/Expenses

The -R flag causes cp to copy the folder and its contents. Note that the folder name does not end with a slash, which would change how cp copies the folder.
in your case:
make sure you are providing correct path list.txt and the correct path for destiny folder, also i mentioned how to access file variable in double quotes , try this code it's working for me
for file in $(cat ~/Documents/list.txt);  do cp "$file" ~/dir_newfolder;  done

Comment: Thank you. I think I might need the ``-R``, as the "list.txt" contain the list of directories for file names. They are not folder names. But correct me if I am wrong.
Comment: i updated answer as per your requirement please check
Comment: I found out the file directory in the list.txt is not set as ``/Home/dir/file_name``. It was ``~/dir/file_name?``. Thank you for helping me!


how to prove $\frac{\partial (Wx)^T A (Wx)}{\partial W} = 2AWxx^T$

Question: I'm trying to evaluate $\frac{\partial (Wx)^T A (Wx)}{\partial W}$, where

W is a $m \times n$ matrix
x is a $n \times 1$ vector
A is a $m \times m$ symmetric positive semi-definite matrix (e.g. a covariance matrix)

I did some calculations with simple concrete examples and it looks the answer can be $2AWxx^T$, but I am not sure how to prove it in general.
I am familiar with $\frac{\partial y^TAy}{\partial y} = 2Ay$ (e.g. $y=Wx$), but I am confused what $\frac{\partial Wx}{\partial W}$ would be like and how the chain rule would work with it.
Answer: $
\def\o{{\tt1}}\def\p{\partial}
\def\L{\left}\def\R{\right}\def\LR#1{\L(#1\R)}
\def\trace#1{\operatorname{Tr}\LR{#1}}
\def\grad#1#2{\frac{\p #1}{\p #2}}
$Starting with the known gradient, use it to write the differential, then change the independent variable from $y\to W$, and recover the new gradient
$$\eqalign{
\grad{\LR{y^TAy}}{y} &= 2Ay \\
d\LR{y^TAy} &= 2Ay:dy \\
  &= 2A\LR{Wx}:\LR{dW\,x} \\
  &= 2AWxx^T:dW \\
\grad{\LR{y^TAy}}{W} &= 2AWxx^T \\
}$$
where a colon denotes the matrix inner product, i.e.
$$\eqalign{
A:B &= \sum_{i=1}^m\sum_{j=1}^n A_{ij}B_{ij} \;=\; \trace{AB^T} \\
A:A &= \big\|A\big\|^2_F \\
}$$
Comment: @zyxue To paraphrase Laplace:  "I had no need of that hypothesis (or in this case, tensor)"
Comment: what is the result of $\frac{\partial Wx}{\partial W}$ alone?
Comment: can you explain a bit more why $2A(Wx):(dWx) $ leads to $2AWxx^T:dW$?  Is it just a property of matrix inner product? (I'm not too familiar with matrix inner product operation)
Comment: It follows from the cyclic property of the underlying trace function. Just treat the vectors as rectangular matrices with one column.
Answer: As you said, the derivative of the map $$f(y)= y^T A y$$ is the linear form
$$f^\prime(y)(h) = (2Ay)^Th$$ which is summarized using gradient notation as
$$\frac{\partial f}{\partial y} = \nabla_y f = 2Ay.$$
The map
$$\begin{array}{l|rcl}
g : & \mathcal M_{m,n}(\mathbb R) & \longrightarrow & M_{m,1}(\mathbb R)  \\
    & W & \longmapsto & Wx \end{array}$$ is linear. Therefore, its derivative at any point is itself. That is
$$g^\prime(W)(H) = Hx.$$
You are looking for the derivative of the map $h=f \circ g$. Using the chain rule, you get
$$\begin{aligned}h^\prime(W)(H) &= \left(f^\prime(g(W)) \cdot g^\prime(W)\right)(H)\\
&=(2AWx)^THx
\end{aligned}$$
Now, you have to make a decision. Either you stay with this result. That would be sufficient for numerical analysis. Or you want to get the result in terms of matrix calculus.
For each $W \in M_{m,n}(\mathbb R) $, $h^\prime(W)$ is a linear form on $M_{m,n}(\mathbb R) $ that can be defined as
$$\begin{aligned}
h^\prime(W)(H) &= \operatorname{tr}\left(\left(\frac{\partial h}{\partial W}\right)^T H\right)\\
&= \operatorname{tr}((2AWx)^THx)\\
&= \operatorname{tr}(x(2AWx)^TH)\\
&= \operatorname{tr}(2xx^TW^TAH)\\
&= \operatorname{tr}((2AWxx^T)^TH)
\end{aligned}$$
using the properties of the transpose and the cyclic property of the trace. That gives exactly the result you were looking for from the definition in matrix calculus of $\frac{\partial h}{\partial W}$ where $h$ takes real values.
Note: on my side, I don't use matrix calculus conventions. Those are difficult to remember, not always implemented in the same way in software packages (numerator vs. denominator conventions), and obfuscate the natural properties of the derivative.


Computation of $L(p+q+r)$ on a smooth projective curve

Question:
Let $X$ be a smooth projective curve in $\mathbb{P}^2(\mathbb{C})$ of degree $4$ and $p,q,r \in X$. What's $L(p+q+r)$?

With a standard computation, the genus of $X$ is $3$, so applying Riemann-Roch theorem, we obtain $\dim L(p+q+r)=1+L(K-p-q-r)$, with $K$ a canonical divisor. As $\deg(K)=4$, we have $\deg(K-p-q-r)=1$ and so $\dim L(K-p-q-r) \leq 1$. Indeed, we have two possibilities: $\lvert K-p-q-r\rvert=\lvert s\rvert$ for some $s \in X$, so that $L(K-p-q-r)=L(s)=\mathbb{C}$, because the genus of $X$ is strictly bigger than $0$; or $L(K-p-q-r)=0$.
I don't know how to conclude from this or if this the right way to proceed.
Answer: If the points $p$, $q$, and $r$ in $\mathbb{P}^2$ are collinear, then
$\dim H^0(X,K_X(-p-q-r)) = 1$, and hence by Riemann-Roch $\dim H^0(X,O_X(p+q+r)) = 2$. Otherwise, $\dim H^0(X,K_X(-p-q-r)) = 0$, and  $\dim H^0(X,O_X(p+q+r)) = 1$.
Comment: I'm sorry but I'm not used to this notation: as far as I've seen about Riemann-Roch,we just talked about meromorphic functions with specified poles and linear systems and never introduced homology.
Comment: These are synonyms: $H^0 = L$.


How can I create this inverted outer radius in a div?

Question: I am trying to create this pointed arrow for a div which has the following design:

What I did so far was:

.box {
  width: 200px;
  height: 100px;
  position: relative;
  border-radius: 8px;
  background-color: #F6F4FF;
  border: 1px solid lightgray;
}

.box:before {
  content: "";
  position: absolute;
  left: 50%;
  bottom: -8px;
  width: 16px;
  height: 16px;
  background-color: #F6F4FF;
  transform: translateX(-50%) rotate(45deg);
  border: 1px solid lightgray;
  border-radius: 4px;
  z-index: -1;
}

Is there a way to do it including that border that follows this rounded path?
Comment: use `clip-path` : `clip-path: polygon(0% 0%, 100% 0%, 98% 100%, 66% 100%, 49% 83%, 33% 100%, 1% 100%);`
Comment: The problem with clip-path is that I can not add the radius border as I said in my question. It's not possible with polygons, as far as I know.
Answer: changed in your before
  z-index: 1;
  border-top: lightgray;
  border-left: lightgray;

.box {
  width: 200px;
  height: 100px;
  position: relative;
  border-radius: 8px;
  background-color: #F6F4FF;
  border: 1px solid lightgray;
}

.box:before {
  content: "";
  position: absolute;
  left: 50%;
  bottom: -8px;
  width: 16px;
  height: 16px;
  background-color: #F6F4FF;
  transform: translateX(-50%) rotate(45deg);
  border: 1px solid lightgray;
  border-radius: 4px;
  z-index: 1;
  border-top: lightgray;
  border-left: lightgray;
}

Comment: clip-path with polygons doesn't provide the ability to round corners.


C#: What technic is that code?

Question: I would like to know:

What technic is that code?
Can you rewrite that code to make it more readable,  because I do
not completely understand its meaning.
Paragraph para = CaretPosition.Paragraph;

var matchedRun = para.Inlines.FirstOrDefault(inline =>
{
   Run run = inline as Run;
   return (run != null && run.Text.EndsWith(inputText));
}) as Run;

if (matchedRun != null)
{

}

Comment: Posting as a comment because I only can answer (1) it's LINQ. What *do* you understand about the code?
Comment: he do not completely understand its meaning.
Comment: It would help to know what you don't understand about it.
Comment: @HPT he ??? The whole var block, but Lee made a good rewrite!
Answer: I'd say a more readable version would be:
var matchedRun = para.Inlines
    .OfType<Run>()
    .FirstOrDefault(r => r.Text.EndsWith(intputText));

OfType filters the input sequence on the given type (Run) and FirstOrDefault finds the first Run instance whose Text property ends with the given input (or null if none was found).
Comment: That's neat, I hadn't come across `OfType` before.
Answer: It's Linq. Do you know the "var" keyword? It's a type that the compiler knows but the programmer doesn't want to write.
The re-written code without using Linq is
Paragraph para = CaretPosition.Paragraph;

Run matchedRun = null;
foreach (var inl in para.Inlines)
{
   Run run = inl as Run;
   if( (run != null) && run.Text.EndsWith(inputText))
   {
     matchedRun = run;
     break;
   }
}

if (matchedRun != null)
{

}

Note that I converted "inline" to "inl". It's not a keyword in C# but Stackoverflow makes it look like one.
Also note that it's even LESS readable once you get accustomed to Linq!
Comment: You cannot assign null to var, because compiler won't recognize the type.
Answer: This code appears to be related to the RichTextBox class in the .NET Framework.
The CaretPosition.Paragraph.Inlines is a collection of "Inlines" that make up the body of the paragraph.
The code is basically looking for any Inlines that are of type Run, and setting the value of matchedRun to that first instance if there are any. The FirstOrDefault method is simply a convenient way to look inside a collection of objects and retrieve the first element or a default value if the collection is empty.
As far as readability, if you are familiar with LINQ syntax, it isn't too bad to wade through that code, though I do personally find the example code provided by Lee to be a bit more readable - mostly because of the use of another LINQ expression: OfType
Answer: it's called "THE MIGHTY LINQ TECHNIQUE" :)
Jokes apart
it is Linq method to get the First element from the collection or return default value.
var matchedRun = para.Inlines.FirstOrDefault(inline =>{   Run run = inline as Run;   return (run != null && run.Text.EndsWith(inputText));}) as Run;

=> is called the Lambda techique for shorthand delagate decalaration
so you can read it as
Find 1st object from the para.Inlines collection where that object EndsWith some user suplied value or retrun default value if no match found
if you don't want to use this technique which actually reduces lot of code so you can try below equibvalent code
        Paragraph para = CaretPosition.Paragraph;
        var matchedRun = null;
        foreach (var inl in para.Inlines)
        {   Run run = inl as Run;
            if ((run != null) && run.Text.EndsWith(inputText))
            { matchedRun = run; break; }
        }

Now you can decide which is better to write

C#: What technic is that code?


Prove that this function is Borel Measurable.

Question: I have this function and I want to prove it is Borel measurable.
$$\begin{equation}
f:\mathbb{R}^2\rightarrow\mathbb{R}:f(x,y)=\begin{cases}
\sin(\frac{1}{x-y}) &\text{ for } x>y \\\
x^2+y^2 &\text{ for } x\leq y
\end{cases}\end{equation}$$
I thought you could start with only looking at the first part (so for $x>y$) and then the other part. Because if they were both Borel measurable then the function is too. But now I don't know how to do them apart.
Comment: How about using the characteristic functions of the sets $A= \{(x, y) \in \mathbb{R}^2,\, x > y\}$ and $B = \{(x, y) \in \mathbb{R}^2,\, x \leq y\}$
Comment: what do you mean?
Comment: For $A$ and $B$ as avove, let $\mathbf{1}_A$ be the function that is $1$ on $A$ and zero on its complement. Same for $\mathbf{1}_B$. Then, your function can be written using these functions, as sum, product and compositions of measurable functions. This is essentially Kavi Rama Murthy's answer.
Answer: Let $h(x,y)=\frac 1 {x-y}$ if $x >y$ and $0$ otherwise. Then $f(x,y)=\sin (h(x,y))I_A(x,y)+(x^{2}+y^{2})I_B$ where $A=\{(x,y): x>y\}$ and $B=\{(x,y): x\leq y\}$. Since products of Borel measurable functions, compositions of Borel measurable functions  and sums of Borel measurable are Borel measurable it is enough  it is enough to check that $h$ is Borel measurable. For this it is enough to check that $\{(x,y): h(x,y) <a\}$ is measurable for any $a \geq 0$ I will leave this last part to you.
Comment: I understand that you can split that function into two different functions. Then you need to prove that they are Borel measurabel. How do you prove that for g(x,y)=$sin(1/(x-y))$ for x>y and h(x,y)=$x^{2}+y^{2}$ for x<y?
Comment: @wisk First check that $h$ is measurable. Then conclude that $\sin (h(x,y)$ is measurable. It then follows that $\sin (h(x,y)I_B(x,y)$ is measurable.


How to write method in automapper class c#

Question: I am trying to write method in AutoMapper class. My situation is as below.
ClinicListVm = AutoMapperConfig.mapper
  .Map<GetClinicsByUserName_Result, ClinicListViewModel>(c);

I already map ClinicListViewModel with GetClinicsByUserName_Result now I want to manipulate one attribute my destination model as below.
ClinicListVm.ProgressBarCssClass = string.Empty;
if (ClinicListVm.PercentComplete == 100)
{
  ClinicListVm.ProgressBarCssClass = "progress-bar-success";
}
else if (DateTime.Now.Subtract(ClinicListVm.BillerStartDateTime ?? DateTime.Now).TotalDays > MaxDaysInDataEntry)
{
  // partial is a warning color
  ClinicListVm.ProgressBarCssClass = "progress-bar-partial";
}

So, How I can include this code it self in automapper class.
Thanks
Comment: AutoMapper is not the place to do it. Such logic has nothing to do with mapping objects.
Answer: I personally think @Rajmond Burgaj's anwer is a good one. Using a ResolveUsing(), or a custom resolver, is in this case a good way to go.
However, I just want to share a more pragmatic alternative that may result in the same and might help you in the future. You may want to consider abstracting the conditional if...then... logic to a seperate function. For example:
private string DetermineProgressBarState(SourceClass source)
{
    if (source.PercentComplete == 100) return "progress-bar-success";

    var MaxDaysInDataEntry = 42; // missing in your sample
    return DateTime.Now.Subtract(source.BillerStartDateTime ?? DateTime.Now).TotalDays > MaxDaysInDataEntry
        ? "progress-bar-partial"
        : null;
}

With that, you can easily map it in your configuration, like so:
Mapper.Initialize((config =>
{
    config.CreateMap<SourceClass, TargetClass>()
        .ForMember(
            dest => dest.ProgressBarCssClass,
            opt => opt.MapFrom(src =>  DetermineProgressBarState(src))
        );
}));

This runs exactly as you'd expect. Here is the full sample, as a XUnit test (but you'll get the picture):
public class SourceClass
{
    public int PercentComplete { get; set; }
    public DateTime? BillerStartDateTime { get; set; }
}

public class TargetClass
{
    public string ProgressBarCssClass { get; set; }
}

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        // arrange - configure the automapper
        Mapper.Initialize((config =>
        {
            config.CreateMap<SourceClass, TargetClass>()
                .ForMember(
                    dest => dest.ProgressBarCssClass,
                    opt => opt.MapFrom(src =>  DetermineProgressBarState(src))
                );
        }));

        // arrange - create a
        var source = new SourceClass() { PercentComplete = 100 };

        // act - map source to target
        var target = Mapper.Map<TargetClass>(source);

        // assert - verify the result
        target.ProgressBarCssClass.Should().Be("progress-bar-success");
    }

    private string DetermineProgressBarState(SourceClass source)
    {
        if (source.PercentComplete == 100) return "progress-bar-success";

        var MaxDaysInDataEntry = 42; // missing in your sample
        return DateTime.Now.Subtract(source.BillerStartDateTime ?? DateTime.Now).TotalDays > MaxDaysInDataEntry
            ? "progress-bar-partial"
            : null;
    }
}

But... I totally agree with the comment that AutoMapper is not the place to put this logic in. The reason is that you're actually defining markup logic (html/css data) in your mapping logic. This is better placed inside your view, presumably your .cshtml.
With that in mind, should you choose to refactor this somehow "the proper way" in the future, the DetermineProgressBarState() function will still be helpful. You'll just move the code from your AutoMapper config to your controller (or .cshtml helper).
Answer: If you want to execute another function while mapping you can use ResolveUsing method and put your logic in there.
CreateMap<GetClinicsByUserName_Result, ClinicListViewModel>()
.ForMember(d => d.ProgressBarCssClass , o => o.ResolveUsing(s =>
{
    //Do your custom logic here.
}))
.AfterMap((src, dest) =>
{
   //Do your logical after mapping has been done
    dest.ProgressBarCssClass = string.Empty;
    if (dest.PercentComplete == 100)
    {
       dest.ProgressBarCssClass = "progress-bar-success";
    }
    else if (DateTime.Now.Subtract(dest.BillerStartDateTime ??
    DateTime.Now).TotalDays > MaxDaysInDataEntry)
    {
       // partial is a warning color
       dest.ProgressBarCssClass = "progress-bar-partial";
    }
});

Not quite sure where that MaxDaysInDataEntry is coming from but if it can be retrieved inside this method your are good to go this way otherwise if MaxDaysInDataEntry is a variable generated from business logic elsewhere then it is a problem!
Anyway let me know if it help and where that variable is coming from!


Android doesn't find Intent for opening a PNG File

Question: So i try to open a PNG File on the system using the Gallery, but for some reason I always get an ActivityNotFoundException saying the following :
No Activity found to handle Intent { act=android.intent.action.VIEW dat=context://storage/emulated/0/Android/data/com.myapp/files/MyApp/1533800534172image001.png typ=image/* }

My code looks like this :
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.setDataAndType(uri,"image/*")
context.startActivity(intent)

Comment: Could you write the content of uri?
Comment: Can you make val intent = new Intent(); and see if it works ?
Comment: https://stackoverflow.com/a/40337627/8648705
Comment: @chiappins yes - if i do a file.length() its equal to the size of the file.
Answer: I think the problem is on your variable uri.
it should be like:
uri = Uri.parse("file://" + "/sdcard/path-to-your-file.png")

Comment: i have tried replacing "context://" with "file://" which leads to a android.os.FileUriExposedException
Comment: yes here can find the right way to avoid this exception: https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed


Discord.py: Going through a specific channel's history, picking a random message and sending it's link

Question: The context I'm using this in is for a Clip of the week command, in which the bot will go through an already created channel filled with clips, pick one at random and send the message link of that message.
From reading the docs, I imagine I'd have to use channel.history and jump_url, but I cannot figure out how to utilise them for my scenario.
I did figure out how to do the weekly cooldown -
@commands.cooldown(1, 604800, commands.BucketType.user)
Answer: You were heading in the right direction with channel.history and the message.jump_url. Here's an example on how you would do that:
import random

@bot.command()
async def randommsg(ctx):
    messages = await ctx.channel.history(limit=None).flatten()
    random_message = random.choice(messages)
    await ctx.send(random_message.jump_url)

You can replace the limit with whatever you want, 100 is the default, None gets every message in the channel. (Note: getting every message is incredibly slow in channels with lots of messages. I had around 3k messages in mine and it took over a minute as reference.)
https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.history


Find the square root of $(x^2 + 3x + 7)(x^2 + 5x + 3) + (x − 2)^2$

Question: I want to find the square root  of $$(x^2+3x + 7)(x^2+5x+3)+ (x −2)^2$$
First , I would like to know if it is really necessary to expand everything , because I think it is in the given form for  a special reason.
Anyway I expanded and got $$x^4+8 x^3+26 x^2+40 x+25$$ and after that also rational roots test is of no use because there are no real factors.
Please help.
Comment: The constant term suggests you expand $(x^2+ax+5)^2$ and equate to find $a$, if it exists.
Comment: @L.F. $a$ can be read off as $\frac 82$ from the cubic term.
Answer: Given that you have already expanded, you might as well equate coefficients of $(x^2 + ax + 5)^2$ as has already been commented.
Perhaps the reason why it is in the form given is, let us say the square root is $p(x)$.
Then, $(x^2+3x + 7)(x^2+5x+3) = p^2 - (x-2)^2 = (p - x + 2) (p + x - 2)$
Now can you read off what $p(x)$ could be?
(Addnl hint, $p$ is just the average of the factors)
Comment: x^2+4x+5 ? Thanks !
Answer: As $x^2+3x + 7-(x^2+5x+3)=-2(x-2), x^2+5x+3=(x^2+3x +7)+2(x-2) $
$\implies (x^2+3x +7)(x^2+5x+3)+(x-2)^2$
$=(x^2+3x +7)\{x^2+3x +7+2(x-2)\}+(x-2)^2$
$=(x^2+3x +7)^2+2(x^2+3x +7)(x-2)+(x-2)^2$
$=\{(x^2+3x +7)+(x-2)\}^2$

Alternatively, if we $x^2+3x + 7=a, x^2+5x+3=b, x-2=c\implies b-a=2c$
$\implies (x^2+3x +7)(x^2+5x+3)+(x-2)^2=a\cdot b +c^2$
$=a(a+2c)+c^2=a^2+c^2+2ca=(a+c)^2$
Comment: @AGoogler, how about this?
Comment: Good method ! Thank you.
Comment: fabulous @lab bhattacharjee


Lucene indexwriter.close() is a must?

Question: My program was running too slow that I had to terminate it halfway to optimize some part of the codes right after 40,000 documents was inserted into database, BUT, before Lucene indexwriter.close was called. Then I couldn't find any results for some of the records that seems to be limited to the 40,000 documents from that particular run.
Does that mean that those record which I had index during the program run was lost? IndexWriter must always be perfectly closed to allow for the data to be written to the index?
Thanks in advance!
Answer: It's not close that you need to call but commit. addDocument only analyzes the document and buffers data into memory while commit will flush pending changes and perform a fsync.
close calls commit internally, I think this is why you assume close is required.
However, beware of not calling commit too often as this operation is very costly compared to addDocument.

Lucene indexwriter.close() is a must?


how can we generate tuples from data Frames columns?

Question: I have a dataframe like this:
    top1    top2    top3
0   0       13      20
1   1       14      23
2   2       11      25
3   3       13      20
4   4       10      21
5   5       19      13

I want to generate to generate tuples like that: [("0", "13"), ("0", "20"), ("1", "14), ("2", "11"), ("2", "25"), ....].
How can we do that if possible? And if I want to do the same for a some given rows (not all the rows)?
Comment: But remember that this way of handling the data isn't well suited to pandas. Why do you want to do this?
Comment: What you want is to iterate the row and make two tuples from each row right?
Comment: @Nephanth yes but always the combination is between the the first element of the row with each of the other columns
Comment: Then do just that I suppose? Here is how to iterate through the rows: https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas
Comment: I want to generate tuple which represent edge in a graph
Comment: Would it be ok to generate a dataframe (with two columns) instead of a list of tuples? That would be way more suited to pandas
Comment: You can do what do you want just I need the tuples to be like  I want in order to generate my graph
Answer: assuming this is pandas we are talking about
import pandas as pd

df = pd.DataFrame({"top1": [0, 1, 2, 3, 4, 5], ... and so on})

tuples = []
for index, row in df.iterrows():
    tuples.append((row["top1"], row["top2"]))
    tuples.append((row["top1"], row["top3"]))

print(tuples)

Answer: An alternative to iterating over the DataFrame would be to create two columns using zip and then convert them to two lists and join them. zip is a very efficient function for this.
df['col1'] = list(zip(df.top1, df.top2))
df['col2'] = list(zip(df.top1, df.top3))

final_list = df.col1.to_list() + df.col2.to_list()

If you want to get a list of row-wise tuples, you can do this:
def get_edge(idx):
    lst = []
    lst.append(df.col1[idx])
    lst.append(df.col2[idx])
    return lst

This returns a list of the pair of tuples whose index you pass to the function.
Comment: Can you please update your answer in case we need to select a given row in the dataframe
Comment: Sure, you can do that by specifying the index. I've updated my answer and created a function to get a row-wise list of tuples,
Answer: Here are a couple of one-line solutions:
pd.concat([df[['top1', 'top2']].apply(tuple, axis=1),
           df[['top1', 'top3']].apply(tuple, axis=1)]).to_list()

(df[['top1', 'top2']].apply(tuple, axis=1)
                     .append(df[['top1', 'top3']].apply(tuple, axis=1))
                     .to_list())


rsync --compare-dest does not work

Question: I have these directories SRC, DST, COMPARE:

/opt/SRC
file1
file2
file3

/opt/DST
file1
file2

/opt/COMPARE
empty

I wish:
$ ls /opt/COMPARE
file3

But when I run :
rsync -avz --compare-dest=/opt/COMPARE /opt/SRC/ /opt/DST

The /opt/COMPARE directory is still empty, why?
Answer: I believe that you are applying the --compare-dest incorrectly.
From man rsync

   --compare-dest=DIR
          This option instructs rsync to use DIR on the destination machine as an  additional
          hierarchy  to  compare  destination files against doing transfers (if the files are
          missing in the destination directory).  If a file is found in DIR that is identical
          to  the  sender's  file, the file will NOT be transferred to the destination direc‐
          tory.  This is useful for creating a sparse backup of just files that have  changed
          from  an  earlier  backup.  This option is typically used to copy into an empty (or
          newly created) directory.

         Beginning in version 2.6.4, multiple --compare-dest directories  may  be  provided,
          which  will  cause  rsync  to  search  the list in the order specified for an exact
          match.  If a match is found that differs only in attributes, a local copy  is  made
          and  the attributes updated.  If a match is not found, a basis file from one of the
          DIRs will be selected to try to speed up the transfer.

         If DIR is a relative path, it is relative to the destination directory.   See  also
          --copy-dest and --link-dest.

         NOTE:  beginning with version 3.1.0, rsync will remove a file from a non-empty des‐
          tination hierarchy if an exact match is found in one of  the  compare-dest  hierar‐
          chies (making the end result more closely match a fresh copy).

If I am reading this correctly, --compare-dest used used to stop the sending certain files.  This would allow you to create a new copy destination directory, containing only files that have changed since the last copy.  Sort of an incremental copy, if you will.
Answer:
rsync will compare the files in /opt/SRC to the files in /opt/COMPARE.  If file exists in /opt/SRC and doesn't exist in /opt/COMPARE, or different version of it exists in both, it will copy it to /opt/DST.
rsync is not only inspecting content when deciding if files are "identical". For this to work correctly, you should sometimes use flags like "--no-times" (this oneworked for me in one occasion), or "--no-perms", "--no-owner", "--no-group, "--checksum", etc.
it is a good idea to use "--dry-run" to test the behavior, without actually copy.

rsync --compare-dest does not work


The bound for the probability of maximum of random variables

Question: I have a small question that as for a fixed number $c$, and random variables $X_i$, $Y_i$ for i=1,2...,n, we know that $|P(X_i<c)-P(Y_i<c)| \leq \alpha$ holds true for any $i$, where $\alpha$ is a constant. Then what is upper bound for $|P(\max_i X_i<c)-P(\max_i Y_i<c)|$. Here, $X_i$ are not i.i.d, and $Y_i$ are also not i.i.d.
Many thanks!
Comment: Is anything known about their distribution or correlation? (since you said they are not i.i.d.)
Answer: I don't think you can get any nice bound in terms of $\alpha.$  Here is an example where $\alpha = 0$ but $|P(\max X_i < c)-P(\max Y_i < c)| > 0$.
Let $X_0$ be a random variable with $\mathbb{P}(X_0 = c) = p$ and $\mathbb{P}(X_0 = -c) = 1-p$ for some $p \in (0,1)$, and let $X_1=X_0$, $X_2 = -X_0$.  Let $Y_1$ and $Y_2$ be independent copies of $X_1$ and $X_2$ respectively.  Then clearly $|P(X_i < c) - P(Y_i < c)| = 0$ for each $i$, but $P(\max_i X_i < c) = 0$ and $P(\max_i Y_i < c) = p(1-p)$ so $|P(\max_i X_i < c) - P(\max_i Y_i < c)| = p(1-p) > 0$.


Difference between gnome-shell & ubuntu-gnome-desktop

Question: I am running Ubuntu 14.04 LTS (32-bit). Now I want to install Gnome Desktop Environment (without removing unity). I know I can install by following command:

sudo apt-get install gnome-shell
sudo apt-get install ubuntu-gnome-desktop

But I don't know exact difference between them. (may be i've misunderstanding with them)
So, What is difference between installing Gnome by gnome-shell and ubuntu-gnome-desktop?
And Which should I use to install Gnome Desktop Environment?
Comment: Gnome Shell, would be installing a vanilla Gnome3 desktop whereas Ubuntu-Gnome-Desktop is the pre-configured DE that come installed in Ubuntu Gnome 14.04. In the end, they both install a pretty vanilla experience, but both should install Gnome3 DE, then just switch to it at the login screen.
Answer: ubuntu-gnome-desktop will install a full GNOME desktop environment (including gnome-shell), along with a few standard applications and optimizations for Ubuntu.
gnome-shell will only install the GNOME shell, and its dependencies. In contrast to ubuntu-gnome-desktop, it won't install the package gnome-session (among others) automatically, which you need to actually use the GNOME desktop.
So, to get the desktop environment, you should install ubuntu-gnome-desktop.

Following will cleraly show that ubuntu-gnome-desktop depends on gnome-shell so it includes the package gnome-shell:
$ apt-cache depends ubuntu-gnome-desktop | grep gnome-shell
  Depends: gnome-shell
  Depends: gnome-shell-extensions

Comment: What good is the `gnome-shell` package if it does not work without `gnome-session`?
Answer: gnome-shell only installs the desktop enviorment, while ubunut-gnome-desktop is a group of packages that contains gnome-shell and all of the basic ubuntu gnome application like totem, rhytmbox, firefox....


cross-browser compatibility

Question: On the new safari browser 6.0 on Lion 10.8 this code is not executing properly. Works fine in firefox and iPad safari. But on the mac it keeps vibrating as I scroll up and down. I'm trying to keep the top banner scrolling until the button reach the top of the page at which point i want the buttons to stay fixed.
here's the link to the page:
http://www.persiantunedpiano.com/Mirror/events.htm
here's the js:

Comment: Not just on the Mac: Win7, Firefox 14, scrolls slooooooow and jerky. Also note, playing music automatically annoys some visitors (like yours truly)... `;)`
Answer: Hmmm... seems like it is too slow, this will speed it up can't be sure it will be fast enough:
(I'm adding the jQuery elements to the closure so you don't have to search for them 4 times per move.)

Comment: Sorry for late response, been bogged down with other projects. Your code isn't working. Here's a page with your code: http://www.persiantunedpiano.com/Mirror/about.htm. Here's a page with the previous code which was causing the problem: http://www.persiantunedpiano.com/Mirror/events.htm. Any ideas?
Comment: Yes, move my code into the `$(document).ready(function(){` function.  Worked locally for me then.
Comment: Ok. That fixed the problem. I guess this is an improvement to the previous version. However i'm still not content with the performance. It still flickers a lot when I scroll with the touchpad. Works fine when I drag the scroll bar. Just the two finger scroll doesn't work like the pre-lion safari which was completely smooth with no flicker what so ever. I'll accept your answer since it was an improvement and take that this is an issue with the new safari with no solution.

cross-browser compatibility


AWS S3 Glacier - how to specify for a vault storage class as DEEP_ARCHIVE in PowerShell?

Question: I created a vault via New-GLCVault, but when it came to upload a file there I understood that I didn't know how to specify desired storage class for the vault. I need to place my file to a DEEP_ARCHIVE vault, and here come 2 questions:

How can I see the storage class associated with particular vault in PowerShell?
How can I specify the desired storage class when I create the vault and(or) upload there my files?
Answer: There are two types of Amazon Glacier:

The 'original' Amazon Glacier that uses Vaults and Archives. It is slow and very difficult to use.
Amazon S3 storage classes that allow you to use standard S3 API calls, but gain pricing benefits by using Glacier storage classes (which are actually cheaper than the 'original' Glacier).

It appears that you are attempting to use a Storage Class (#2 above) with the Amazon Glacier service (#1 above), which won't work.
Instead, just use standard S3 API calls and specify: StorageClass='DEEP_ARCHIVE'
This method also means you don't need to do anything with Vaults.
Comment: Does it mean that I should use New-S3Bucket and Write-S3Object to upload my file to Deep Archive storage?
Comment: Yes, that is correct. Include the Storage Class when performing the upload.


Half-hot outlet connected to dimmer switch

Question: My home has a half-hot outlet connected to a dimmer switch.  I have two questions about it.
First, is this a code violation?
Second, What would be better in the long term:

Change to a standard switch
Replace the outlet with a normal duplex outlet
Other
Comment: Just change the dimmer to a switch, it's very easy.
Answer: Some things have a dim view of being dimmed
Things other than lamps, such as motors and some electronic loads, often take a rather dim view of being connected to a dimmed receptacle.  This may range from merely "not working" to "overheating and catching on fire", something you (and the NFPA) would rather not have happen.  So, the 2014 NEC prohibits your current configuration in 406.15:

406.15 Dimmer-Controlled Receptacles. A receptacle supplying lighting loads shall not be connected to a dimmer
  unless the plug/receptacle combination is a nonstandard
  configuration type that is specifically listed and identified
  for each such unique combination.

This leaves you with two options -- either you can swap the culprit dimmer out for a switch, or you can use a special receptacle and plug to prevent non-lamps from being plugged in to the dimmed outlet.
Going Dimmerless
Swapping a dimmer for a switch is a relatively easy task, at least as far as single pole configurations are concerned:

Turn the power to the circuit off at the breaker
Remove the old dimmer + faceplate from the box and undo the terminal screws
Connect the new switch's brass screws to the two wires that went to the dimmer's brass screws (they may be any color but green or bare).  Which wire goes to which brass terminal doesn't matter, either.
Connect any bare or green wire present to the new switch's green grounding screw.
Put the switch back in the box and put the faceplate back on
Turn the circuit back on

Keeping pesky non-lamps at bay
Lutron makes a plug and receptacle combination for this job -- the receptacle you need is a Lutron HDTR, and you'll have to put the matching plug on whatever lamp you plug into the dimmed receptacle, as well.

This is the costlier and slightly trickier option of the two, but may be needed if the dimmer serves other lights as well as the half-dimmed receptacle or otherwise can't be removed.
Comment: Beat me to it while I was trying to find pictures of the Lutron plug :)  Added to your answer


ARGH udev won't stop renaming my interfaces!

Question: I have the following in /etc/udev/rules.d/70-persistent-net.rules
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="d0:50:99:50:43:17", KERNEL=="eth*", NAME="eth0"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="d0:50:99:50:43:18", KERNEL=="eth*", NAME="eth1"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="68:05:ca:1a:ce:9d", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth2"

However, on boot, udev hate me. Why?
dmesg snips:
[   13.328778] e1000e 0000:01:00.0 eth0: registered PHC clock
[   13.328781] e1000e 0000:01:00.0 eth0: (PCI Express:2.5GT/s:Width x1) 68:05:ca:1a:ce:9d
[   13.328783] e1000e 0000:01:00.0 eth0: Intel(R) PRO/1000 Network Connection
[   13.970303] igb 0000:07:00.0: Intel(R) Gigabit Ethernet Network Connection
[   13.970305] igb 0000:07:00.0: eth1: (PCIe:2.5Gb/s:Width x1) d0:50:99:50:43:17
[   13.970434] igb 0000:07:00.0: eth1: PBA No: 001300-000
[   14.013474] igb 0000:08:00.0: Intel(R) Gigabit Ethernet Network Connection
[   14.013476] igb 0000:08:00.0: eth2: (PCIe:2.5Gb/s:Width x1) d0:50:99:50:43:18
[   14.013603] igb 0000:08:00.0: eth2: PBA No: 001300-000
[   16.274874] systemd-udevd[155]: renamed network interface eth2 to p121p1
[   16.847244] systemd-udevd[160]: renamed network interface eth1 to p119p1
[   19.425858] systemd-udevd[607]: renamed network interface eth0 to eth2

How come the third works but the first two don't?
Comment: It appears to be a bug: https://bugs.launchpad.net/ubuntu/+source/biosdevname/+bug/1284043
Comment: Actually I did get it to work eventually with PCI address ID. You have to put this in `etc/default/grub`: `GRUB_CMDLINE_LINUX_DEFAULT="ipv6.disable=1 net.ifnames=1 biosdevname=0"`
Comment: Just saw the notes here: https://wiki.debian.org/Bonding about UDEV. I'm going to try and rename by PCI address and see if that helps.
Comment: Nope that didn't work either...
Answer: Actually I did get it to work eventually with PCI address ID. Two things, you have to:

Put/edit this in etc/default/grub:
GRUB_CMDLINE_LINUX_DEFAULT="net.ifnames=1 biosdevname=0

then do a sudo update-grub
Put your desired names into /etc/udev/rules.d/70-persistent-net.rules, like this:
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", KERNELS=="0000:03:00.0", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

Where 0000:03:00.0 is your PCI address you located in your dmesg output.

Note: No need to disable IPV6, I forgot that flag was in there. We just don't use it, so we disable it for safety.
Answer:
Append this to /etc/default/grub:
GRUB_CMDLINE_LINUX_DEFAULT="net.ifnames=0 biosdevname=0"

Update bootloader :
sudo update-grub

Reboot!
reboot

Tested on ubuntu 15.10
Comment: the OP already posted the answer in a comment... also, an accepted answer is already here.
Comment: you wrong I did it and if you don't set  `net.ifnames=0` kernel will rename the interfaces. I don't really know maybe on other version it differ.


Skirting board filler chipping off

Question: We're about to paint our skirting board with black gloss paint but some of the filler is chipping off in places.
Should we remove the areas of filling that are chipping off and refill those only or should we try to remove all of the filling and completely redo from scratch? What is the best product to fill with?
And do we need to sand down the original gloss paint before painting over with new black gloss?
Comment: Just a note about gloss black: black (actually *all dark*) paints do not cover well, so use premium paint brushes and expect to apply a second coat. Also, gloss black paint will tend to show defects clearly, so expect any dents, divots, cracks, nail holes, etc. to be visible if they are not repaired.
Answer: Are you trying to achieve a perfect seam or just looking to hide the gap?
You can fill it with paintable caulk/silicone and proceed with painting.
Yes, gloss paint needs to be scuffed up so that new paint can adhere properly unless you are applying an oil-based paint.
If you want to turn this painting project into a painful multi-day renovation then remove the skirting, sand or scrape down the protruding paint from both the wall and skirting, patch the wall with mud, sand, prime, re-attach the skirting, apply paintable caulk or silicone, and finally paint the skirting and wall.
Comment: Community bump because there is no accepted answer... :/
Comment: While the advice in the last para is "painful" and "multi-day", it is the _one true way_ to a quality finish.
Comment: @FreeMan Thanks, and I applaud you for finding this answer 1 month later!
Answer: I would sand the board slightly to remove the gloss paint sheen. Then I would put masking tape or the newer type edging tape, green or blue, on both the wall and baseboard, just past where you want to fill. Clean out the loose debris and use a paintable silicone caulking to fill the slot. After you add the caulking run your finger along that caulking to give you a smooth finish. When the caulking has been smoothed, remove the tape to leave a nice straight edge.  After the caulking has dried you can paint the baseboard as you like.
Answer: It would be best to "rake" out the loose and jagged paint in the gap so that it can then be filled. After cleaning out the gap you should use a latex caulk to fill the gap. You may be able to find a color to match the paint you intend to use.
Inject the caulk along the gap,press it in with your finger and wipe gently with a dampened sponge until you're satisfied with how it looks.
I would suggest making sure the molding (trim) piece in the picture isn't loose and if it is to re-secure it with finish nails and such.
No need to de-gloss before painting, but a quick cleaning with TSP, ammonia, Windex will guarantee a successful paint job.

Skirting board filler chipping off


If $G$ is a group with $N$ normal and $H_1$, $H_2$ subgroups of $G$ with $H_1$ a normal subgroup of $H_2$, show $NH_1$ is a normal subgroup of $NH_2$.

Question: I was unsure how to prove this property which seems necessary for the solution to a problem I did recently. Since $N$ is normal, it seems pretty clear that $NH_1 = H_1N$ and $NH_2 = H_2N$ so they are indeed subgroups of $G$. I tried to prove normality directly by taking $nh \in NH_2$ and was able to show that $$nh NH_1 = N nh H_1 = Nn H_1 h$$ using the fact that $H_1$ is normal in $H_2$ and so $h H_1 = H_1 h$. Then, it seems like this problem reduces to showing that $nH_1 = H_1n$ which isn't immediately obvious. In fact, I'm not sure if that's even true.
My latest attempt uses the fact that $NH_1 = H_1N$ and $Nn = N$ so that we can find some $n' \in N$ so that $n'H_1 = H_1n$ which would allow us to conclude $$nh NH_1 = N nh H_1 = n H_1 h = Nn' H_1 h = NH_1nh$$ which is what we wanted but I had some trouble showing that this idea actually worked.
Thank you in advance for your help!
Answer: Since $NH_1$ is a subgroup, we have (refer here) $$NH_1=H_1N.$$
So, $$nhNH_1=nNhH_1=nNH_1h=NH_1h=H_1Nh=H_1Nnh=NH_1nh.$$
Comment: Ah this is a very nice way to do it. Thanks!
Answer: Hp:  $N\trianglelefteq G$, $H_1,H_2\leq G$, $H_1 \trianglelefteq H_2$
Ts: $NH_1 \trianglelefteq NH_2$
Note that, since $N\trianglelefteq G$ and $H_1,H_2 \leq G$, we have $NH_1,NH_2 \leq G$.
Take $x$ in $NH_1 \implies \exists n_1 \in N,h_1\in H_1 :x=n_1h_1$ and consider $y$ in $NH_2$, so $\exists n_2 \in N,h_2\in H_2: y=n_2h_2$. We have to show that $NH_1$ is normal in $NH_2$ (which means that $y^{-1}xy\in NH_1$), so
$$(n_2h_2)^{-1}(n_1h_1)(n_2h_2)=h_2^{-1}(n_2^{-1}n_1)h_1n_2h_2= h_2^{-1}n_3 h_1n_2h_2 = \underset {N\trianglelefteq G,H_1\trianglelefteq H_2}{n_4(h_2^{-1}h_1h_2)n_5}=n_4\bar h_1n_5=\underset{N\trianglelefteq G}{n_6\bar h_1} \in NH_1 \implies NH_1\trianglelefteq NH_2$$


File Object in IE 10

Question: I am trying to use the html input type=file element and get files from it using document.getelementbyid("..").files and it is working fine in chrome and firefox but not in IE 10. I've gone through alot of blogs and most suggest that IE 10 onwards support the File object but its not working for me in either IE 10 or IE 11. Can someone please help me out with this.
code:
HTML:
<input type="file" id="fuAttachment" name="fuAttachment" class="mof-strip-file" style="width:68%;" />
Javascript:
var inputfile = document.getElementById("fuAttachment").files[0]; –
Comment: please share some relevant code in post so that we can help you better.
Comment: @hira Show me your code ??
Comment: @hira Put your code as part of the question not as comment (Remove it from comment)
Comment: @hira Check your error console and try to go through this site maybe useful. http://msdn.microsoft.com/en-us/library/ie/hh673542%28v=vs.85%29.aspx
Comment: @gjman2 i have already been through that site with no help. I was hoping to find a workaround.
Comment: @hira Ic, as I know IE == Problems. Btw can you give me the links of the blogs that said IE 10 onwards support the File object?
Comment: lol.. well it said so on w3c [link]http://www.w3schools.com/tags/att_input_type.asp
Comment: @gjmann also this page is basically the api reference for File api for IE10 http://msdn.microsoft.com/en-us/library/ie/hh673542(v=vs.85).aspx#api_reference
Comment: @hira try to debug your javascript code.Try to put alert("") in your javascript method then check in your error console.
Comment: @hira maybe useful http://stackoverflow.com/questions/16242072/html5-file-upload-form-with-customized-style-cant-fire-submit-button-using-ie10?rq=1   and this one http://stackoverflow.com/questions/16676945/dynamically-submitting-a-file-upload-form-in-ie10-using-jquery?rq=1
Answer: Thank you all for your help. Turns out that the ActiveX content filtering needed to be turned off in Internet Options > Security. First add your website as trusted site and then select "Custom Level" and then select Disable under ActiveX filtering.

File Object in IE 10


Find $\sin(t+\pi)$ and $\cos(t+\pi)$ when $\sin(t)$ and $\cos(t)$ given

Question: I am learning precalculus and I do not know how to approach when solving this problem:

Which steps should i take?
Comment: If you want to prove this the long way, consider your sumangle formulas, $\sin(\alpha+\beta)=\sin(\alpha)\cos(\beta)+\cos(\alpha)\sin(\beta)$ and $\cos(\alpha+\beta)=\cos(\alpha)\cos(\beta)-\sin(\alpha)\sin(\beta)$, then use $\pi$ in place of $\beta$.
Comment: If you want to get straight to the result... notice how sine goes up, then it goes down., and is periodic with period $2\pi$.  You should be able to see visually that $\sin(x+\pi)=-\sin(x)$ and similar for $\cos$.  There are similar results for adding or subtracting $\pi/2$
Comment: Oh!  It's not a multiple-choice problem, it's a problem with four parts....
Answer: Hints:
For (a), use the fact that $\sin(t+π)=-\sin t$ and $\cos(t+π)=-\cos t$ as well.
For (b), you need to know that $\sin$ is odd and $\cos$ is even. Thus, $\sin(-t)=-\sin t$ and $\cos(-t)=\cos t.$
For (c), use the facts that $\cos(t+π/2)=-\sin t$ and $\sin(t+π/2)=\cos t.$
You should now be able to do (d) by applying the facts I suggested in (c) and (b) above.
Answer: Think of (cos(t), sin(t)) as (x,y) coordinates on the unit circle.
I would visualize the point on Quadrant 1, and see what happened next.
$$\begin{matrix}
t → t+\pi & (x,y) → (-x, -y) & \text{Quadrant 3}\cr
t → -t & (x,y) → (x, -y) & \text{Quadrant 4}\cr
t → t+\frac{\pi}{2} & (x,y) → (-y, x) & \text{Quadrant 2}\cr
t → -t+\frac{\pi}{2} & (x,y) → (y,x) & \text{Complementary angles}
\end{matrix}$$
Ignoring the signs, odd $\frac{\pi}{2}$ rotations will swap x and y's.
Then, from the Quadrants, add back the signs.
Answer: use addition/subtraction formulas:
$$\sin(a+b) = \sin(a) \cdot \cos(b)+ \cos (a)\cdot \sin(b)$$
Substitute $-b$ in the formula above, which yields:
\sin(a+(-b)) & = \sin(a-b)\
             & = \sin(a) \cdot \cos(-b)+ \cos (a)\cdot \sin(-b)\
             & = \sin(a) \cdot \cos(b) - \cos (a)\cdot \sin(b)
$$\cos(a+b) = \cos(a)\cdot \cos(b) - \sin(a)\cdot \sin(b)$$
Substitute $-b$ in the formula above, which yields:
\cos(a+(-b)) & = \cos(a-b)\
             & = \cos(a) \cdot \cos(-b) - \sin(a) \cdot \sin(-b)\
             & = \cos(a) \cdot \cos(b) + \sin(a) \cdot \sin(b)
Now rewrite each angle in terms of $a+b$, in terms of 2 quantities added together $ \\ $
i.e: $-t = 0-t = 0+(-t) $
if you used 0-t, you will use subtraction formula, for $a = 0, b = t \\ $
or you can use addition formula, $0+(-t)$, for $a = 0, b = -t$
Comment: Did you mean rewrite each angle in terms of $a$ and $b$ or by substituting for $a$ and $b$?  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.  Welcome to MathSE.
Comment: @N.F. Taussig, yes


Pystray icon available when running as a service

Question: Using:

Python (3.7.5)
Pyinstaller (3.5)
Pywin32 (223)
Pystray (Current)

I have a python program that uses Pystray to show an icon which allows me to make Tkinter window available.  It took a while but, thanks to stack overflow, this functionality works fine.  I then create an executable for this using PyInstaller and this also runs fine. Up to here everything is great, executing the program starts its webservice and shows the icon.
I call this program from a service created with pywin32.  The program starts as expected, and it's webservice functionality is available, however I cannot see the system tray icon.  I assume this is because I am logged in as an administrator, but the service runs under the general service account.
Is there any way to make the Pystray Icon available to all users logged into the machine?
Comment: Hi matthew, did you find the solution. i am also facing the same error
Comment: Hi @SammuSundar.  Unfortunately not yet.  You can try up voting the question to increase it's visibility.  If you do find an answer somewhere else then please let me know,  I'm still scratching my head this end.
Comment: yeah sure, I will share if I found the solution :)
Answer: This link explains it all : https://learn.microsoft.com/en-us/archive/blogs/winsdk/launching-an-interactive-process-from-windows-service-in-windows-vista-and-later
Abstract : You cannot open an interactive process from a windows service as you normally would, cause the service runs on a totally different environment ( aka Session 0 ) while the logged-in user's session id is 1...2... depending upon the number of users.
if you start your service and look at the 'Details' tab in Task Manager you'll find your process running but not showing up
from what i understood, here we ( i too encountered the exact same problem after a while ) are trying to open a process from a service that is in session 0 and it cannot interact with session 1 directly ? so we should create the new process as a user using CreateProcessAsUser
i used the following code to get it running :
<code># A SETUP FOR STARTUPINFO
startupInfo = win32process.STARTUPINFO()
startupInfo.dwFlags = win32process.STARTF_USESHOWWINDOW
startupInfo.wShowWindow = win32con.SW_NORMAL

# GET THE TOKEN FOR LOGGED-IN USER
console_session_id = win32ts.WTSGetActiveConsoleSessionId()
console_user_token = win32ts.WTSQueryUserToken(console_session_id)
# GET THE LOGGED IN USER'S ENVIRONMENT TOO
environment = win32profile.CreateEnvironmentBlock(console_user_token, False)

win32process.CreateProcessAsUser(console_user_token,
                                 'notepad.exe', # PATH TO YOUR EXECUTABLE / SCRIPT
                                 None, # THIS ONE IS 'COMMAND LINE' IF YOU INTEND YOU USE IT
                                 None,
                                 None,
                                 0,
                                 win32con.NORMAL_PRIORITY_CLASS,
                                 environment, # TO OPEN IN USER'S ENVIRONMENT
                                 None,
                                 startupInfo)
</code>
Let me know if you have any queries


Understanding with custom jQuery slider next button

Question: I have a div with 3 divs inside it each of the inner divs have a class of content and one has a class of current. I was trying to show only one .content at a time and just have a next button that hides the div and removes the .current class and adds it to the next one. It all works fine but when I get to the end of the divs. I want it to just circle back to the first one. The following code doesn't do that. The first one shows but the next button stops working after that:
js:
var $ = jQuery

$( document ).ready( function() {

  $('#next').click(function(){

  var item = $('.content.current');
  item.removeClass('current');
  item.slideUp();
  item.next().addClass('current');
  if(item.next().length == 0) {

    $('.content').first().slideDown().addClass('current').end();

  }
  })
})

HTML:

        next

Basic

Unlimited Bandwidth

Unlimited Diskspace

10 Email Accounts

24/7 Support!

$4/month

Order Now!

Professional

Unlimited Bandwidth

Unlimited Diskspace

10 Email Accounts

24/7 Support!

Order Now!

St. Joseph

Unlimited Bandwidth

Unlimited Diskspace

10 Email Accounts

24/7 Support!

Order Now!

Answer: What your  $('.content').first().slideDown().addClass('current').end(); does is it'll show the first element and add the current class to it. Change your script to this
var $ = jQuery
$( document ).ready( function() {
  $('#next').click(function(){
  var item = $('.content.current');
  item.removeClass('current');
  item.slideUp();
  item.next().addClass('current');
  if(item.next().length == 0) {
    $('.content').slideDown();
    $('.content').first().addClass('current');
  }
  });
});

and it will work. Here is a example fiddle. Hope this helps you.
Answer:

var $ = jQuery

$( document ).ready( function() {

    var i = 1;

    $('#next').click(function(){

        ++i;

        $('.content.current').removeClass("current").slideUp();
        $(".content:nth-child("+i+")").addClass("current").slideDown();

        if(i == 3) i=0;
    });
});

        next

Basic

Unlimited Bandwidth

Unlimited Diskspace

10 Email Accounts

24/7 Support!

$4/month

Order Now!

Professional

Unlimited Bandwidth

Unlimited Diskspace

10 Email Accounts

24/7 Support!

Order Now!

St. Joseph

Unlimited Bandwidth

Unlimited Diskspace

10 Email Accounts

24/7 Support!

Order Now!

It's very easy if you insist to do it with JS :
$( document ).ready( function() {

    var i = 1;

    $('#next').click(function(){

        ++i;

        $('.content.current').removeClass("current").slideUp();
        $(".content:nth-child("+i+")").addClass("current");

        if(i == 3) i=0;
    })
})

but better option is BOOTSTRAP which I guess you are using.
you can find it here: Collapse Bootstrap


Java Android Sockets Threading

Question: I've a client class which tries to connect to a server. But as you know you can't
execute network operations on the Main UI thread. So I've to create different threads for each operation.
Current code:

package com.example.justus.rocchat;

import android.os.AsyncTask;
import android.util.JsonWriter;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * Created by justus on 13-1-2015.
 */
public class Client
{

    private String name;
    private int port;
    private String hostAddress;
    private Socket socketClient;
    private MainActivity mainActivity;
    public boolean isConnected;

    public Client(MainActivity mainActivity, String hostAdress, int port)
    {
        this.hostAddress = hostAdress;
        this.port = port;
        this.mainActivity = mainActivity;

    }

   public void send(final byte[] data)
   {

           Thread sendThread = new Thread(new Runnable() {
           public void run()
           {
               try
               {
                   DataOutputStream out = new DataOutputStream(socketClient.getOutputStream());
                   out.write(data);
                   System.out.println("writed data");
               } catch (IOException ex) {
               }
           }
           });

       sendThread.start();
   }

    public void connect()
    {
        Thread connectThread = new Thread(new Runnable() {
            public void run() {
        try
        {
            System.out.println("trying to connect");
            socketClient = new Socket(hostAddress, port);
            isConnected = true;

        }
        catch(UnknownHostException ex)
        {
            System.out.println("ex:" + ex.getMessage());
        }
        catch (IOException ex)
        {
            System.out.println("ex:" + ex.getMessage());

        }
            }
        });

        connectThread.start();
    }

}

Isn't this a little to much? Are there any better ways to handle this operations?
Already thanks for your time.
Comment: what makes you think this is too much ?
Comment: Creating a thread for each operation? Isn't that using to much threads then neccesary?
Comment: it depends on how your `send()` method is going to be used. you haven't specified that. you may actually end up with a single thread, if it complies with what you want to accomplish. note that the primary purpose of threading is to do some task independently i.e. asynchronously
Answer: AsyncTask is the accepted way of handling asynchronous operations.  It is a wrapper around the Thread class and is part of the Android SDK.  They should only be used for operations that last under a few seconds, for longer operations you should use a Service.
developer.android.com/reference/android/os/AsyncTask.html
Answer: There are 2 options that you have

Use AsyncTask - much easier, object oriented that using threads but only for shortlived tasks (under 30 secs)
Use RoboSpice - https://github.com/stephanenicolas/robospice
Of the two, I prefer RoboSpice

Java Android Sockets Threading


Apache Request/Response Too Slow

Question: I have an Apache server with 16GB of Ram. The script cap.php returns a very small chunk of data (500B). It starts a mysql connection and makes a simple query.
However, the response from the server is, in my opinion, too lengthy.
I attach a screenshot of the Developer Tool Panel in Chrome.

Beside SSL and the TTFB there is a strange delay of  300ms (Stalled).
If I try a curl from the WebServer:
 curl -w '\nLookup time:\t%{time_namelookup}\nConnect time:\t%{time_connect}\nPreXfer time:\t%{time_pretransfer}\nStartXfer time:\t%{time_starttransfer}\n\nTotal time:\t%{time_total}\n' -k -H 'miyazaki' https://127.0.0.1/ui/cap.php

Lookup time:    0.000
Connect time:   0.000
PreXfer time:   0.182
StartXfer time: 0.266

Total time:     0.266

Does anyone know what that is?
Comment: If your cap.php establishing connection to mysql and runs a query for each request then this delay can be expected I think, To confirm this is try to calculate the time taken by your PHP to connect to mysql and fetch data. ref here : http://stackoverflow.com/questions/1200214/how-can-i-measure-the-speed-of-code-written-in-php
Comment: I also tried to jump over the query, for example just sending "hello". Same result: the stalled phase remains.
Comment: Then it could be network, try to get `cap.php` with Wget or CuRL command in same server itself, if you are seeing same delay then your configuration need to be tweaked a bit.
Comment: I made a test with curl. The total time is similar. I think is a problem related to SSL, isnt'it?
Answer: According to the Chrome documentation:

Stalled/Blocking
Time the request spent waiting before it could be sent. This time is inclusive of any time spent in proxy negotiation.
  Additionally, this time will include when the browser is waiting for
  an already established connection to become available for re-use,
  obeying Chrome's maximum six TCP connection per origin rule.

So this appears to be a client issue with Chrome talking to the network rather than a server config issue. As you are only making one request I think we can rule out the TCP limit per origin (unless you have lots of other tabs using up these connections) so would guess either limitations on your PC (network card, RAM, CPU) or infrastructure issues (e.g. You connect via a proxy and it takes time to set up that connection).
Your curl request doesn't seem to show this delay as it has just a 0.182 wait time to send the request (which is easily explained with https negotiation) and then a 0.266 total time to download (including the 0.182). This compares with 0.700 seconds when using Chrome so don't understand why you say "total time is similar" when to me it's clearly not?
Finally I do not understand your follow up answer. It looks to me like you have made request, presumably after a recent other request as this has skipped the whole network connection stage (including any grey stalling, blue DNS lookup, orange initial connection and purple https connection). So of course this quicker. But it's not comparing like for like with your first screenshot in your question and is not addressing your question.
But yes you absolutely should be using keep-alives (they are on by default in most web server so usually takes extra efforts to turn them off) and https resumption techniques (not on by default unless you explicitly add this to your https config) to benefit any additional requests sent shortly after the first. But these will not benefit the first connection of the session.
Answer: Eventually, I found that if you use SSL it is really better and it does really matter to switch on the KeepAlive directive into Apache. See the picture below.
Comment: So the screenshot in question is without `keepalive` enabled and the screenshot here is with `keepalive` on ? but am wondering how does a single request make much difference here.
Comment: becuase I think you are under ssl. If there is an error in the SSL handshake (think of CNAME mismatch) the connection is reopened.Checked with chrome://net-internals/#events

Apache Request/Response Too Slow


Second Subpanel

Question: Long time reader first time post.
I recently installed a 100 amp sub-panel from my 200 amp service to a barn on my property. It's been a few months and now I'm finding that I actually should have installed the sub-panel in my detached garage that is near the barn. So, I'm wondering how would I go about adding a sub-panel with power coming from the sub-panel in the barn. I'm thinking 50 amps is plenty for this second sub-panel and would never run anything heavy on amps in both the barn and garage at the same time.
Can this be done? If so is the drawing correct with regards to wiring? I used a main panel in the barn so that I could have a main disconnect which would allow me shut off power in the barn. I believe it's required in a detached building.

Thanks
Comment: The sun panels should not be bonded past the main breaker…am I wrong. That would make the sketch incorrect.
Comment: @Ryan What are you talking about specifically? The diagram shows the neutral bars in the sub-panels isolated, and the ground bars attached to the metal panel boxes - everything exactly as it should be.
Answer: looks like you have it correct 125% of 50 is 62.5 so you should use #6 wire
Comment: OP may not be in Oregon, so Oregon amendments may not be applicable.  It's best to stick to what NEC says, and let the OP worry about local amendments.
Comment: What's the 125% for?
Comment: 125% of your breaker is the wire size for the feed to the 2nd sub.
Comment: Says who? Where are you getting that from?
Comment: this is a feeder 215-2.-1  ,210-20A, 215.3 the over current protection device is the maximum load then add 125% to protect the wires
Comment: Both the breaker and conductors should be 100% of the noncontinuous loads, plus 125% of the continuous loads.
Comment: 210.3 states the OCPD sets the ampacity of the circuit. In Oregon if you have not used the calculation method, or measured values 125% is required, I know this board is all over the world but better safe than sorry

Second Subpanel


Create an array then sort data after ng-repeat

Question: I'm trying to put data in array then sort it. Here is the sample JSON:
"region": {
    "BRA": {
      "activities": 24
    },
    "USA": {
      "activities": 58
    },
    "LUX": {
      "activities": 1
    },

This is what I have so far:

{{a}} : {{d}}

So far, I was able to show the region and activities. I need to sort "activities" by the highest number. Like this:
USA : 58
BRA : 24
LUX : 1
Comment: That data is not an array , it is an object and you can't sort objects. Map it to an actual arry in order to sort
Comment: Thanks @charlietfl! I'm a newbie in programming thus I really don't know how to create an array in angularjs.
Answer: The region data that you are using must be an array / collection. You can define it as below -
$scope.regions = [{
    "name": "Brazil",
    "activities": 24
  }, {
    "name": "USA",
    "activities": 58
  }, {
    "name": "Luxembourg",
    "activities": 1
  }];

The html will then be something like this

  {{region.name}}
  {{region.activities}}

And in order to sort it by highest number, you can use a javascript library like underscore.js
Here's a plunker solution to your problem
https://plnkr.co/edit/wJ2B1D8bphIJ9yfBtnS2


Which time best represents the true time for an audio file

Question: I have an app that records online radio for a later playback. After programmatic recording, They are 3 sets of times(duration). I don't know which time will present the best user experience.
For a radio programs that airs for 1 hour, e.g. 9am to 10am;

The duration of the program is 60 mins. (Stable across recording sessions)
A recording for 60 mins yields an audio file that is always longer than 60 mins e.g. 70 mins. (Differs with recording sessions)
Due to unstable streams a recording might end before 60 minutes are up. e.g. 45 mins. (Differs with recording sessions)

Which times would represent the true duration of the audio file and how do I appropriately show it inside the app?
Comment: Do you have a mockup with the surrounding context? Is this for desktop, mobile? What other metadata is present? That will help the community get a clearer picture.
Comment: No we don't have a mock up surrounding the context. We are yet to design. We are still talking about what informations to provide in the screen
Answer: From a users perspective, the true value is the actual content a user intends to listen to (i.e. an interview). If the recording is too long or too short, it's the systems responsibility. The system should make that clear so users don't think they messed up, or the system is broken.
I don't know how the rest of your app works, but this seems like a case of managing user expectations.
The main cases seem to be that (I hope I have this right):
1. The recording exceeds the content.
There is some extra time which I have to scrub through audio I presumably don't care about to get to the good stuff.
Is there a way to somehow mark when the actual content begins? or even better, somehow detect and edit for the user? I have no idea how this would be possible, but putting it out there.
If you can't smart edit, you can at least calculate the extra time.
If there's 72:30 mins recorded, you have 12:30 mins extra. You could subtly indicate the overage and provide details on hover. Either way, test with some users and see if this adds any value.
2. The recording cuts off some of the content.
In this case, you can have an alert or info tip warning them that some of the content might have been cut off. Perhaps clicking the i has a popover explaining why this has occurred.

Here's a sketch from a modified Soundcloud list item. The duration is right on the timeline, so I can see what to expect. I've added the info tip, so if a user is scrolling a list, they can see items that differ from the norm and can expect they may not have the whole program to listen to.
Either way, be honest with users, and keep them informed.


How to seal HVAC ducts running through old window to addition?

Question: My house has a small addition that was added by the previous owners.  They ran the HVAC ducts through an old window and some of the block:

The rectangular section in the window should be easy enough to seal with some plywood, but how about around the ducts and the blocks?  My first thought was wood and spray foam, but I have read that spray foam is a no-no near HVAC ducts.
I need to seal this in a way that I can still get access to the crawlspace as this is the only way in.
Two other jobs that I already know about and are related to this problem:

The crawlspace walls and floor need to be sealed properly. This allows bad air and radon to enter the crawlspace area.
The ducts in the crawlspace need to be cleaned, sealed with mastic and insulated.  I'm working on this now.
Comment: Before you get too far, I'd make sure that the ledger over the window opening that they widened is adequately supported.
Comment: good point.  I just checked and they did put a beam over the top of the window that is roughly 4x8"
Answer: assumptions from what's in  your photo:
1)  it looks like the right side of the opening is your access, and the ducts are rigidly installed.
2) the crawlspace looks unheated, as the ducts seem to be insulated, and the fact that you mention radon must mean you have an actively vented (fan) crawlspace to evacuate any radon gas (along with a radon alarm in the living space of the basement adjacent).  I personally don't have any experience with radon tight building, but certain municipalities in Ontario have this as an issue, so its covered in the provincial building code.
if that's correct here's what you can do.
1)  build an airtight, removeable access door and frame assembly to give you access.  you can find this on youtube I am sure, or just copy the way an attic access works.
2)  on the ductwork runs, build a bigger pipe around them so that you have a 1" gap between the heated duct and the slip pipe.  you can wrap a piece of galvanized steel flashing around them, overlapping the ends by approx. 3".  use galvanized steel, not aluminum, to prevent galvanic corrosion.
3)  stuff fiberglass insulation into the gap between the pipes (not too compactly) and seal the ends with fiberglass cord sized to match the gap (1 in gap needs 1" cord.
4)  tape the end of the pipe over with vapour barrier and adhere to the slip and the duct. now you have an airtight insulated joint that can expand and contract and won't cause corrosion on the duct pipe.
5)  fill the gaps between the slip pipe and everything else with spray foam. fill the gaps from both the cold side and the warm to trap a dead air space between the foam fields. now you have a vapour proof insulation mass that will keep your heat in.
6)  THIS IS VERY IMPORTANT.  go through all the pipe insulation on the cold side and make sure that all the insulation is in good shape and that the vapour barrier is completely intact.  remember, extra insulation on vent pipes does nothing but save you money and headache when it comes to crawlspace hvac ducting.
now you have a giant section, half access panel, half bulkhead, all of it airtight, insulated and radon-tight.
done
Answer: I'm sure it is a no-no to use the expanding foam over the ductwork insulation wrap or on flexible ductwork, but when the foam is in direct contact with the sheetmetal it should be just fine. Ultimately, you're looking for a solution that prevents the exchange of air between the two spaces, will not condensate, and will not compress the existing ductwork insulation.  I can't think of any other product that meets these criteria besides building a form out of wood and filling the cavity with foam. You just need to make sure the insulation is pushed back behind your wood form.  Once your foam has cured you can then add/replace the insulation right up to the foam.


Behave BDD reusing steps from common step file

Question: How do i re use steps from common_step.py
example:
common_feature:
Given log in with "abc" user
common_step:
@given('log in with "{user}" user')
anotherFile_feature
Given log in with "xyz" user
anotherFile_steps:
how do i pass that xyz user in here, can i get an example
thanks
Answer: If you need to reuse your user in another steps or parts of your code, shouldn't you just assign the value of the user to a variable?
@given('log in with "{user}" user')
def do_login(context, user)
    context.user = user  # the context variable will be accessible during execution time

Answer: First of all, I recommend that you post more documented questions, as it is difficult to understand what you are asking.
As @herickmota says, if you want to share values between different functions in your code you should use the context variable, which is shared by all the steps during the execution of the test, and in which you can store as many values as you want to be able to retrieve them wherever you want.
If, on the other hand, what you want is to call from a step to another step that you have already defined, you should use the context.execute_steps method, of which you have the documentation at https://behave.readthedocs.io/en/stable/api.html?=execute_steps#behave.runner.Context.execute_steps and you can see an example at https://jenisys.github.io/behave.example/tutorials/tutorial08.html.
I'll give you some examples:

This is the example of a valid directory tree. You must have the *.feature files inside a directory named "features" and also inside that directory you must have de "steps" directory with the steps definitions inside.

The second directory tree is an invalid directory tree, because the anohter_file_feature.feature file is unable to find the step definitions. In any case, I can't find any situation where you should separate the features in this way.

The last of the directory trees is the most commonly used sort, as it allows you to separate features into folders according to the criteria you see fit. This is the structure I would recommend to organise your Behave files.
Once we are clear about the valid distributions of the files in different folders, let's talk about how to call the methods from the different *.feature files.
To begin with, the first Scenario we have as an example would be the features/common_features/common_feature.feature, in which we make the most typical call to a step to which we pass a parameter, in this case the name "Manuel".
Feature: Common_feature

  Scenario: Scenario number one
    Given log in with "Manuel" user

The definition of the step is in the file features/steps/common_step.py
from behave import *

@given(u'log in with "{user}" user')
def step_impl(context, user):
    print("I'm logging with the user: " + user)

The output if we run de command behave features/common_features/common_feature.feature is:
$ behave features/common_features/common_feature.feature
Feature: Common_feature # features/common_features/common_feature.feature:1

  Scenario: Scenario number one     # features/common_features/common_feature.feature:3
    Given log in with "Manuel" user # features/steps/common_step.py:4

1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
1 step passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.001s

In another path, we have the file features/another_features/another_file_feature.feature in which we have defined the following two examples: one invoking again the step we already had declared in features/steps/common_step.py and another with a new step, which implicitly calls the step log in with "{user}" user:
Feature: Common_feature

  Scenario: Scenario number two
    Given log in with "José" user

  Scenario: Scenario number three
    Given calling indirectly with "Antonio" user

The definitions of the step we have in features/steps/another_file_steps.py is as follows:
from behave import *

@given(u'calling indirectly with {user} user')
def step_impl(context, user):
    context.execute_steps("Given log in with " + user + " user")

And the output of running the command behave features/another_features/another_file_feature.feature is:
$ behave features/another_features/another_file_feature.feature
Feature: Common_feature # features/another_features/another_file_feature.feature:1

  Scenario: Scenario number two   # features/another_features/another_file_feature.feature:3
    Given log in with "José" user # features/steps/common_step.py:4

  Scenario: Scenario number three                # features/another_features/another_file_feature.feature:7
    Given calling indirectly with "Antonio" user # features/steps/another_file_steps.py:4

1 feature passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
2 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.006s

As you can see, here are some basic examples of the file structure in Behave and how to call both directly and indirectly to the steps from the features.
Comment: hi thanks for the answer, i was looking more for the solution for reusing the step from a different step file, i will try to give another example.
Comment: lets say i have feature_file1 with Given change the configuration to "proceed" and the step_file1 has the step defined for it, now i need to create another feature file feature_file2 in a different directory and that directory has its step_file2 now in feature_file2 i have how do i reuse Given change the configuration to "skip" (instead of duplication the step in step_file2 how do i use the step from the step_file1 with passing that "skip" parameter ) example u provided is for reusing the step of the same feature file. in my case two feature files in a different directories.
Comment: In any case, I'll give you an example in my answer and let's see if it helps to you


A question of the book Elements of the Representation Theory of Associative Algebras: Volume 1

Question: I am reading the book Elements of the Representation Theory of Associative Algebras: Volume 1 .
I have a question on page 9, line -7 (see Page 9 here). It is said that $$f_X(x_2) = x_2e_{21} = x_2e_{21}e_{11}.$$ It seems that $e_{11}$ has not been defined and $e_{21}$ is a $2 \times 2$ matrix. How can $e_{21}$ act on $x_2$? Thank you very much.
Edit: On -9, how to show that  $x_1a_{11} + x_2a_{21}$ is an element in $X_1$? It seems that $x_2a_{21}=f_X(x_2)a_{21}$. But this cannot be true since the left hand side is in $X_2$ and the right hand side is in $X_1$.
Answer: My guesses are that:
1) $e_{11}=e_1$, i.e. a typo. I would have used the notation $e_{11}$ and $e_{22}$ in place of $e_1$ and $e_2$ to make it easier to remember that they really are 2x2 matrices. OTOH $e_1$ and $e_2$ are standard notations for idempotents, so I understand the authors choice as well. It is possible that the author has changed the notation at some point, and no one noticed to make the change here.
2) Here there is another typical abuse of notation. The symbol $x_2$ stands for a vector in the space $X_2$ (similarly $x_1\in X_1$). When we agree to talk about the space $X$ as a direct sum $X_1\oplus X_2$ of its two subspaces we need to pay the price of making certain identifications. A vector $x_2\in X_2$ can be viewed as an element of $X$. because $X_2$ is a subspace of $X$. But when we write $X=X_1\oplus X_2$, and accordingly use the vector notation $(x_1,x_2)$ for its elements, we must identify $x_2$ with $(0,x_2)$. Similary we must identify all elements $x_1\in X_1$ with vector $(x_1,0)$. Early on in algebra studies a distinction is made between inner and outer direct sum. When a certain maturity level is reached, the distinction is blurred. The author may have jumped to this point too soon, or may be not. I cannot tell for sure. Anyway, once you think of $x_2$ as the vector $(0,x_2)$ whenever necessary, your problem should disappear.
Comment: I understand now. The $x_2$ in $f_X(x_2)$ is indeed $(0, x_2)$ but the $x_2$ in $x_2a_{21}$ is an element in $K$.
Comment: but on line -9, $(x_1a_{11}+x_2a_{21}, x_2a_{22}) = (x_1a_{11}+f_X(x_2)a_{21}, x_2a_{22})$. Here $x_1a_{11}+x_2a_{21}$ should be an element in $X_1$. But $x_2a_{21}$ is in $X_2$.
Comment: The $x_2$ in $f_X(x_2)$ is indeed $(0, x_2)$. But how to show that  $x_1a_{11} + x_2a_{21}$ is an element in $X_1$? It seems that $x_2a_{21}=f_X(x_2)a_{21}$. But this cannot be true since the left hand side is in $X_2$ and the right hand side is in $X_1$.
Comment: $X_2$ is a sub*space*, it is not an $A$-sub*module*. Right multiplication by $a_{21}e_{21}$ does take $X_2$ into $X_1$:
$$(0,x_2)\pmatrix{0&0\cr a_{21}&0\cr}=(x_2a_{21},0).$$


URL query format, CGI script request

Question: What is the CGI script executed when we construct URL as follows:

somesite.xx/content/?query=somestaff

after '?' sing we pass arguments, but script name looks like empty string between '/' and '?' signs.
Answer: This is defined by server configuration, which should have a "default document" for the directory in question.
Comment: For most configurations, index.xxx,  home.xxx, default.xxx, isn't it? But I guess, at least for apache, it can always be interpreted via mod_rewrite and point to a completely different path.
Comment: @AJweb I can't say for various servers to make a conclusion of "most", but for Apache this can be changed via .htaccess and via site config, and via mod_rewrite, so there are plenty of ways.

URL query format, CGI script request


How to change python3 from python3.5 to python3.6

Question: I have both python3.6 and python3.5 on ubuntu (zesty beta 2). I know that python calls python2.7. The problem is, when I call python3, it automatically starts python3.5 instead of python3.6.
Is there a better way to fix this than an alias?
Comment: What is wrong with aliases ?
Comment: Changing the system-provided version of Python risks breaking your system. Many essential system services (like apt) are tested against the system-provided version of Python. Best way to experiment with different versions of Python is in a VM.
Comment: @Ravexina Don't they slow down shells?
Comment: I'm not sure they do: [Do aliases slow down a shell's start?](https://superuser.com/questions/543649/do-aliases-slow-down-a-shells-start#543658)
Answer: Changing the default python3 version might break many things on your system, and I'd advise against making python3 point to python3.6. Better to simply call python3.6 explicitly in those programs where it matters, and leave the python3 symlink as is.
Answer: As an alternative to aliases you can use update-alternatives:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1

This command will create a link in: /usr/bin/python3 to /usr/bin/python3.6.
I'm not sure if it's a good idea, maybe an update makes it broken.
An other options is creating a link to desired version of python in ~/bin then adding this path to the $PATH environment variable:
export PATH=/home/$USER/bin:$PATH

Or within your .profile:
PATH=/home/$USER/bin:$PATH

Comment: This will break things that are expecting python3 to be python3.5 (as at 17.04). For example, launching a terminal will not work and the update indicator will fail. Actually breaks apt pretty badly.
Answer: Regarding your actual question (whether it's a good idea or not, I leave aside), you can check your /usr/bin/python3 version (in my case it was 3.4 ), and replace it with the new version:
$ python3 -V
  Python 3.4.9

$ ls -lh /usr/bin/python3
  lrwxrwxrwx. 1 root root  9 Dec  5 16:35 /usr/bin/python3 -> python3.4

$ sudo mv /usr/bin/python3 /usr/bin/_python3
$ sudo cp /usr/bin/python3.6 /usr/bin/python3

$ python3 -V
  Python 3.6.6

Comment: It's not a good idea. Don't do this, it will break things like Gnome Terminal and APT.
Comment: @wjandrea, that's why I explicitly said to put aside "whether it's a good idea or not". I simply answered the OP question: _How to change python3 from python3.5 to python3.6 ?_
Comment: Just because you can doesn't mean you should.


comparing and removing rows in pandas

Question: I am trying to create a new object by comparing two list. If the rows are matching the row should be removed form the splitted row_list or appended to a new list containing only the differences between both lists.
results = []
for row in splitted_row_list:
    print(row)
    for row1 in all_rows:
        if row1 == row:

            splitted_row_list.remove(row)
        else:
            results.append(row)

print(results)

However, this code just returns all the rows. Does anyone have a suggestion?
Sample data
all_rows[0]:'1390', '139080', '13980', '1380', '139080', '13080'
splitted_row_list[0]:'35335','53527','353529','242424','5222','444'

Comment: Can you include some sample data for `all_rows` and `splitted_row_list` ? And please also post the expected output.
Answer: As I understand you want to compare two lists by index and keep the differences and you want to do it with pandas (because of the tag):
So here are two lists for example:
ls1=[0,10,20,30,40,50,60,70,80,90]
ls2=[0,15,20,35,40,55,60,75,80,95]

I make a pandas dataframe with these lists, and build a mask to filter out the the matching values:
df= pd.DataFrame(data={'ls1':ls1, 'ls2':ls2})
mask= df['ls1']!=df['ls2']

I can then call the different values for each list using the mask:
# list 1
df[mask]['ls1'].values

out: array([10, 30, 50, 70, 90])

and
# list 2
df[mask]['ls2'].values

out: array([15, 35, 55, 75, 95])

comparing and removing rows in pandas


Show that $f:[0,1) \to S^{1}$ is not a homeomorphism($S^{1}$ is a unit circle,$S^{1}$={$x \times y : x^2+y^2=1$}).

Question: I've taken $f(t)=(\cos 2\pi t,\sin 2\pi t)$,then as $t $ varies from $0$ to $1$,$(\cos2\pi t,\sin2\pi t)$ covers up the whole $S^{1}$ once,which means $f:[0,1)\to S^{1}$ is a bijection.Also,as $\cos2\pi t$ & $\sin2\pi t$ are both continuous functions which means $f$ is continuous also.
Now,in order to show $f$ is not a homeomorphism we have to show that $f^{-1}$ is not continuous,which can be done by showing that $[0,1)$ has atleast one open set whose image under $(f^{-1})^{-1}$ is not open in $S^1$.
How to do this,i don't know?What is the form of open sets in $S^1$?
Disclaimer:I cannot use  Compactness & Connectedness.
(Using these concepts this problem already has answers- How do I show that $f: [0,1) \to S^1$, $f(t) = (\cos(2\pi t), \sin(2\pi t))$ is not a homeomorphism?)
We can use only above highlighted notion.
Comment: @Gianluca:usual topology on $\mathbb R$
Comment: Ok thanks you :)
Comment: Which topology are you consider on $[0,1[$?
Comment: i've never seen $x\times y$ used to mean $(x,y)$.
Comment: @arctictern:also i have'nt till today:-).
Comment: @arctictern:this notation is from Munkre's topology text.
Answer: HINT: $\left[0,\frac12\right)$ is open in $[0,1)$.
But you've misunderstood what you need to do to show that $f^{-1}$ is not continuous: you need to find an open set $U$ in $[0,1)$, the codomain of $f^{-1}$, such that $(f^{-1})^{-1}[U]$ is not open in $S^1$.
Comment: @PKStyles: It's the subspace topology on $S^1$: the intersections of open sets in $\Bbb R^2$ with the set $S^1$. If you think about that for a bit, you'll see that open intervals around $S^1$ are a base for its topology.
Comment: M.Scott:What is the form of open sets in $S^1$?
Answer: You can use two facts: if $f: X \to Y$ is a homeomorphism then so is $g: X \setminus\{x_0\} \to Y \setminus \{f(x_0)\}$ is also a homeomorphism where $g$ is just the restriction of $f$. Now recall that homeomorphic spaces have the same number of connected components.
Comment: Why was this answer down voted? It seems right to me..
Comment: @PtF: There are a lot of things on this site that get down voted out of personal bias. These two facts, if used correctly, answers the problem in one line.
Comment: @FaraadArmwood:you're downvoted may be because use of connectedness is not allowed.But,i upvoted you,because of the way you represent $g$.


Fade in an element using Javascript when going from display:none to display:block

Question: I have a script that shows an element when a radio button is pressed. I'm trying to fade in the showing of the element so it's not so abrupt.
The JS:
document.getElementById('next').style.display = 'block';
document.getElementById('next').fadeIn(1000);

This works fine except for the fade in animation. What am I doing wrong. I have tried combining both statements into one statement, and I have also tried setting the fade in before the display:block, but it doesn't show up at all. Still fairly new to JS, so I'm just trying to figure out what is possible. Thanks in advance
Comment: `.fadeIn()` is a jQuery method (maybe in other libraries too), not a JavaScript element method. You didn't tag the question with jQuery, but the way to do it with jQuery is `$("#next").fadeIn(1000);`. If you want to do it with pure JavaScript, you'll have to look up ways to mimic this behavior
Comment: are you using jQuery?
Comment: @rahulmaindargi I was not using jQuery. Thank you.
Comment: @EGHDK then check my answer... using JQuery will make your code much simpler and cleaner though..
Comment: Are you using any library?
Comment: Here is the alternative codes :
http://stackoverflow.com/questions/19706147/how-to-hide-elements-with-smooth-transition-by-class-with-javascript/
Answer: There's no .fadeIn() method on DOM elements.
document.getElementById('ques_2').fadeIn(1000);

You're probably seeing some jQuery or other library code. That code must run on the jQuery (or whatever) object that wraps your DOM element.

Another approach that will work in modern browsers would be to use a CSS3 transition. You could have the JavaScript apply a new class, and let the CSS take care of the visual effect.

If you did want to use a library like jQuery, you need to import it into your page. For example, put this in the head of your page:

Then follow the API rules for fetching DOM elements and calling methods.
You can either use the native DOM methods to do the fetching, or just use jQuery, which makes sense if you decided to load it.
Comment: Can I call a function from jQuery inside of a javascript script I wrote?
Comment: @EGHDK: jQuery is just a library of pre-written JavaScript code. So yes, you just run its functions within your existing JavaScript. I can't say if it makes sense to use jQuery in your project or not. Only you can decide that.
Comment: Any idea why it's not working? I think it's because I'm trying to use jQuery in JS.
http://jsfiddle.net/7N5sE/
Comment: @EGHDK: In JS is the only place you *can* use jQuery. :-) Again, all it is is a collection of pre-written JavaScript code. The problem is that your `showHide` function is inside another function... though you can't see it. Look at the menus on the left. You have `onLoad` selected in the second drop menu. This means your code is being defined in a `window.onload` handler. Choose one of the `no wrap` options instead to make your `showHide()` global.
Comment: @EGHDK: If you're going to use a library like jQuery, I'd suggest running through a quick tutorial or two. You'll learn most of what you need to know in a short period of time.
Comment: Really quick, do you know why this doesn't change to red? http://jsfiddle.net/G7LN7/1/
Comment: @EGHDK: jQuery doesn't animate colors. There are likely plugins that do this, or you can also import the jQueryUI library *(or parts of it)* to get color animations.
Comment: Interesting... is there a place where I can see what regular jQuery is limited to? Or what are some things I might try that won't work with Regular jQuery.
Comment: @EGHDK: It pretty much comes down to learning the API. If something doesn't work, you look it up in the docs to make sure you're using it properly. If you can't figure it out, then there's StackOverflow to help you. :) For example, as you learn, you'll learn that the `.fade...()` methods are just a wrapper for a call to `.animate()`, and the [`.animate()` docs](http://api.jquery.com/animate/) talks a little bit about colors.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/31000/discussion-between-eghdk-and-crazy-train)
Answer: You could use CSS3 to develop this effect.
With this HTML:

and this style:
#fader {
   opacity:0;
   -webkit-transition: opacity 2s;
   -moz-transition: opacity 2s;
   -o-transition: opacity 2s;
   transition: opacity 2s;
}

Remove the display attribute from the style.
After that you could use JavaScript to change the style, and the effect will automatically happen:
document.getElementById('fader').style.opacity = 1;

DEMO: http://jsfiddle.net/AUak7/
Comment: the op asked for display:block not opacity
Answer: with simple javascript you can do something like this...
here i am also printing the opacity value as its being increased...
DEMO
function show() {
    document.getElementById('next').style.opacity = (parseFloat(document.getElementById('next').style.opacity) + 0.1);
    document.getElementById('value').innerHTML = (document.getElementById('next').style.opacity);
    if (document.getElementById('next').style.opacity < 1) {
        setTimeout(show, 400);
    }
}

function fadeIn() {

    document.getElementById('next').style.opacity = 0;
    document.getElementById('next').style.display = 'block';
    setTimeout(show, 400);
}

fadeIn();

Answer: FadeIn is a jQuery function, but you are using simple javascript. Include jQuery and use:
$("#next").fadeIn(1000);


Function is not defined ReferecenError onchange in Angularjs

Question: I'm having issues with onchange event for file input.
Here is my code:
Html:
 <input type="file" kendo-upload k-options="uploadOptions" id="fileInput" onchange="fileUploaded(event)"/>

Angularjs code - using Typescript.
$scope.fileUploaded = (event) => {
            console.log("Testing file upload");
            var reader = new FileReader();
            var target = event.target || event.srcElement;
            reader.onload = function(e) {
                $scope.$apply(function() {
                    $scope.readFile = reader.result;
                });
            };
            var file = target.files[0];
            reader.readAsText(file);
        };

I tried to follow this and change accordingly but am still having issues.
Pass angularJS $index into onchange
I changed like this.
<input type="file" kendo-upload k-options="uploadOptions" id="fileInput" onchange="angular.element(this).scope().fileUploaded(this)">

I got this error.
Uncaught TypeError: undefined is not a function.
onchange
When I am trying to use ng-change, I have this error.

        <form kendo-validator="validator" ng-submit="validate($event)">

                    <input type="file" kendo-upload k-options="uploadOptions" id="fileInput" ng-change="fileUploaded($event)"/>

        </form>

This gives error when accessing this
$scope.importFile.center();
"TypeError: Cannot read property 'center' of undefined"
Again, works fine if I use ng-click.
Any help on this is higly appreciated.
Thanks!
Comment: you have to use `ng-change()` angular function rather than `onChange()` plain javascript function.
Comment: Change the input's attribute to `ng-change="fileUploaded($event)"`.
Comment: Thanks Jim and Gaurav! However, I still receive another error when trying to use ng-change. I have updated my post.
Comment: What's that `$scope.importReport` thing? Do you have it somewhere in your code?
Comment: Hi Ammar, my mistake, its $scope.importFile.center(). I changed it. Its a Kendo-window.
Answer: You cannot use ngChange in this case since ngChange always requires ngModel and ngModel doesn't work with input type file. Also, you cannot access a function binded to $scope directly using onchange. Instead use the following:
onchange="angular.element(this).scope().fileUploaded($event)"

Comment: Thanks Tarun, I have this error when trying to user the way you suggested. ReferenceError: $event is not defined onchange
Comment: Replace $event with 'this'
Comment: Hi Tarun, thanks for the suggestion but i tried that way earlier. It's in my code above. I got this error. Uncaught TypeError: undefined is not a function. onchange
Comment: Is there any way to work arround since in the code I am working in they set something like this :  var _this = this;   and instead of doing $scope.functionName, they do _this.functioName.  So when I use this method, it return an error. Any clues?