Rosewill RSV-S5 and it's transferespeeds

Question: I have just bought a Rosewill RSV-S5, I have installed 5x1,5Tb Western Digital Green disks in it. After that have I created a Raid5 on them all with the software that followed with the hardware.
Not the raid it self works fine, but it is SLOW, I can only obtain a maximum of 25 MB/s, and if SABnzbd+ is downloading with 5 MB/s is it having a hard time streaming a normal DIVX (700 mb) movie.
Is this normal or is there something wrong?
Edit: should be able to handle 3 Gbps = 384 megabytes / second
Edit 2:
As you can see am I only downloading with 3,76 MB/s and I'm trying to watch V s02e08 (720p), but it is completely unwatchable, as I can see 30 sec, and the it buffers for 20 sec.
Edit: Other information there might be required
I'm running Windows Server 2008 R2, optimized for program performance. Windows is installed on a 60GB SSD. I have a 50 Mb/s internet connection and a 1 Gb/s LAN, all connected with Cat6 Ethernet cables. The MCE is using a Gigabyte EP35C-DS3R motherboard with 2 GB DDR2 ram.
Edit 3: I have used chunk sizes for 128 KB
Edit 4: I found this on newegg

Pros: Enclosure for 5x2TB hard drive
  is fine. This is basically a rebranded
  San Digital TR5M-B product. For
  support Rosewill tells you to contact
  San Digital. No direct support from
  Silicon Image for the computer raid
  card.
Cons: Includes computer Silicon Image
  3132 raid card, extremely slow raid 5
  write (our tests ~10MB/s). Compare to
  regular internal local drive write
  30-60MB/s. We basically dumped the
  Sil3132 card and replaced with High
  Point RocketRaid 622 card for extra
  $69.99. Note for RR622, turn off ECRC
  (end to end CRC check) for card to
  work on IBM xserver. What took 12hrs
  to copy now took 2-3hrs. San Digital
  realized the problem and has the newer
  model TR5M-BP TowerRaid Plus that
  comes with High Point RocketRaid 622
  card. Rosewill should discontinue this
  product and go with TR5M-BP. Could not
  get Silicon Image raid management
  software to work with complicated
  2008R2 server with 10 NICs,
  application doesn't know how to talk
  to localhost port with all those NICs.
  No updates from Silicon Image and
  support from San Digital ignored. Gave
  up on Sil3132 card. Save yourself from
  a lot of headaches, get the RR622 card
  too if you are going to buy this
  product.
Other Thoughts: The newer model is
  TR5M-BP TowerRaid Plus, comes with
  High Point RocketRaid 622 raid card
  for the PC instead of Silicon Image
  Sil3132. According to San Digital,
  raid 5 performance for Sil3132 read
  80MB/s write 19MB/s, and RR622 read
  154MB/s write 149MB/s. Our RR622 tests
  gave (8TB raid 5) write ~80-110MB/s
  copying 40GB file took 8mins.

So I have now ordered a HighPoint RocketRAID 622 2P ext SATA III and hopes that it will solve my problems.
Answer: Gone to the mattresses with the RocketRaid 622 card, I really wanted this to work. See my previous 2 newegg posts.
First I wanted a cheap, reliable, and fast storage device to backup Hyper V images. This seems to be the solution but ran into problems. In RAID 5 with the silicon image card 3132, device was very slow and sometimes doesn't work (I think the service prog can't communicate with Java management app when you have multiple Nics). So first dumped 3132 and got High Point RocketRaid 622 card.
622 was fast but kept disconnecting. Told to get the more expensive TLER, Time Limited Error Recovery, enterprise drive. So got WD RE4-GP, WD2002FYPS (I only trust WD), make sure it's on 622 tested or certified list. It still disconnects and hang server. When this happens, can you trust what is copied? Told to disable caching but made it really slow, less than 10MB/s. I have more than one 622 and esata cable so not bad card. Had the latest firmware and driver. Esata cable short, less than 3 feet.
SECRET SAUCE: To make it work, jumper the sata drives to 150. Data transfer still fast (I think around write 70+ MB/s and read 100+ MB/s) and no disconnects. Only tested it once over night transfering 1TB over GB network to IBM DS3300 ($10,000 device). Need further testing, 2008 R2 64bit server. Don't be fool in your tests because Windows copy things into memory first. Transfer speed you see is the speed to copy it to memory. Open task manager and then resouce manager, take a look at disk activities and you will see it still copinig to disk after your copy window close.
Get the version with 622 card. This is a Sans Digital rebranded product so buy the Sans Digital product. If you set it up as JBOD, software raid, the CPU will be doing all the work (not good). Hope this is the last of the problems.
Answer: Thank does indeed look very slow, although you've consciously bought slow disks and R5 isn't the fastest configuration your should be seeing significantly better than 25MBps, even for random reads. Have you spoke with the manufacturers?
Given this question is more about generic hardware rather than being server specific would you like me to move it over to our sister site superuser.com who may be able to help more?
Comment: Given the hardware is a SATA port multiplier (ick!) with fake-raid by a company known for cutting every corner possible to make a product that looks good... I'd think this is a GIGO problem.
Comment: Yes you can move it, i was unsure where to ask!
Comment: I used the same disks in a windows server 2008 r2 software raid before, so i know it is not the disks that slows it down! :D
Comment: Maby it would help then if i did not use the software that followed with the device and will use the build in functions in windows instead?


Pandas Merge returns NaN

Question: I have issues with the merging of two large Dataframes since the merge returns NaN values though there are fitting values. The two dfs are shaped like:
df1
Motor
2232
1524
2230
2230
2224
1516
1724
2224
1524
1624
1724
2224
2224
1524
1524
1516
1524
2224
1624
1724
1724
2224
2224

df2
Motor   Output Torque (mNm)
0615    0,17
1219    0,72
1516    0,59
1624    2
2230    4,7
2233    5,9
0816    0,7
1016    0,92
1024    1,6
1224    1,7
1319    1,4
1331    3,8
1516    0,97
1524    2,9
1717    2,2
1724    4,5
2224    6,8
2232    10
1336    3,6
1727    4,9
1741    8,8
2237    12
2642    26

I use the code:
MergeDat=MergeDat.merge(Motor,how="left")
print(MergeDat)

where MergeDat= df1
and   Motor= df2
As result it returns:
  Motor  Output Torque (mNm)
0      2232                  NaN
1      1524                  NaN
2      2230                  NaN
3      2230                  NaN
4      2224                  NaN
5      1516                  NaN
6      1724                  NaN
7      2224                  NaN
8      1524                  NaN
9      1624                  NaN
10     1724                  NaN
11     2224                  NaN
12     2224                  NaN
13     1524                  NaN
14     1524                  NaN
15     1516                  NaN
16     1524                  NaN
17     2224                  NaN
18     1624                  NaN
19     1724                  NaN
20     1724                  NaN
21     2224                  NaN
22     2224                  NaN
23     1524                  NaN
24     1724                  NaN
25     1841                  NaN
26     2224                  NaN

I have no idea why the Output Torque column is not merged...
Appreciate any help!
Comment: Could you add `df.dtypes` to the question? Suspecting if later is string column and former is numeric type.
Comment: I had differnt dtypes for the "Motor" column. Fixed this issue by applying the answer of  [jezrael](https://stackoverflow.com/users/2901002/jezrael)
Answer: You need same dtype of joined columns:
#convert first or second to str or int
MergeDat['Motor'] = MergeDat['Motor'].astype(str)
#Motor['Motor'] = Motor['Motor'].astype(str)

#MergeDat['Motor'] = MergeDat['Motor'].astype(int)
Motor['Motor'] = Motor['Motor'].astype(int)

#convert first or second to str or int
#MergeDat['Motor'] = MergeDat['Motor'].astype(str)
Motor['Motor'] = Motor['Motor'].astype(str)

MergeDat['Motor'] = MergeDat['Motor'].astype(int)
#Motor['Motor'] = Motor['Motor'].astype(int)

MergeDat=MergeDat.merge(Motor,how="left")

Comment: Would be great if pandas would print a warning when dtypes are different.
Comment: In pandas 0.25.1, I'm having this exact problem, but `.astype(str)` on both columns (`object` containing DOIs) does not change anything.
Comment: @KatrinLeinweber and others - I resolved the issue. So it so turns our that the join function uses indexes to join (even though you specify 'on'). You can resolve it by first setting the doi column as index for both dataframes and then joining type=left without specifying the 'on'.  so something like this --  combined_df = left_df.set_index('l_doi').join(right_df.set_index('r_doi'), how='left', r_suffix='_right') .  This worked for me.
Comment: @Sören - Yes, maybe in future version of pandas. Btw, last of improvement of merge is [this](https://pandas.pydata.org/pandas-docs/stable/merging.html#checking-for-duplicate-keys()), but same dtypes still not check :(
Comment: I would like to add that I experienced an issue trying to merge columns that were of `object` type together. I had to case them as `str` in order for their join to work.
Comment: @KatrinLeinweber - hmmm, object means strings, so try convert to numeric - [link](https://stackoverflow.com/questions/15891038/change-data-type-of-columns-in-pandas)
Comment: Thanks for the link :-) DOIs are unique strings (e.g. `10.1016/j.ribaf.2019.101069`), though, so neither numeric works (`ValueError`) nor are categorical types appropriate.

However, when I cast the colum which `NaN`-ed after the merge to `astype("category")` beforehand, the values were preserved. Very strange...
Comment: There is a chance if you merge `left` and there are NO common values, it'll look like it found matching records, but you'll have NaN's on the right dataframe because it basically did a `pd.concat(axis=1)` since it didn't find anything to merge.
Comment: @KatrinLeinweber, try .astype('string'). See https://stackoverflow.com/questions/60581893/convert-object-data-type-to-string-issue-in-python . It didn' t solve the problem of NaN, but at least the dtype has been changed.
Comment: @KatrinLeinweber I am having the same issue with DOIs. All NaNs on the right df after a left join.  Did you find a solution? Thanks
Answer: In my case, it was because I haven't reset the index after splitting the data frame, using df.reset_index(drop=True). Resetting the index of the first data frame enabled merging a second data frame to it.
Answer: For me I thought I had the same index but but there was a trailing space in the index for the first dataframe. Removing/trimming that helped.
Answer: Having some NaN's in the key column(s) is the usual culprit from my experience. Try at least the 2nd of these 3 lines on both df's (where unique_id is the key column used for merging) and see if it helps:
print(df[unique_id].duplicated().sum())
df.drop_duplicates(subset=unique_id, inplace=True)
assert(df[unique_id].duplicated().sum() == 0)

Pandas Merge returns NaN


Style 503 Error Pages Expression Engine

Question: Is there anyway to style the error pages (like the 503 error page attached)? I can find the templates in \system\expressionengine\errors\ but any changes to these will be lost when I update EE.

Thanks
Answer: If you log in to your admin section, click on "Design" and then hover over "Message Pages", then click "User Messages". You can insert/edit the CSS that is associated with this page in the head section.
I know this styles the error messages for logging in, submitting forms, etc. and I am assuming it will apply to the same error message you provided. If not let me know.

Style 503 Error Pages Expression Engine


Is there any alternative other than Process to execute built-in shell commands in C#

Question: Is there any alternative other than Process to execute built-in shell commands in C#? Currently I am using Process class to run those commands. But in the current scenario I want to run more than 200 such commands in parallel. So spawning more than 200 processes is not a good idea. Is there any other alternative?
Comment: Why do you think it's not a good idea?
Comment: As an aside, why would you need to run 200 commands in parallel? You do realise that multithreading them will likely be slower than sequential execution in many cases.
Comment: If you have to use "dos commands" then a seperate process is what you need and the `Process` class is the best way to manage that. However, I'm sure you could achieve your ultimate goal in a more elegant way. I can't say for sure without knowing what you want to achieve.
Comment: Which built-in shell command do you want to execute? Maybe there's a .NET alternative to it...
Comment: Sounds to me as if you must be using the wrong tools for whatever it is you want to do. If you could provide a little more info on what you are trying to achieve, maybe we could provide some alternative advice?
Comment: There is an alternative, but wont stop from spawning multiple processes. `int pid = Interaction.Shell(@"cmd", AppWinStyle.NormalNoFocus, false, -1);`
Answer: "Running a dos command" is the equivalent to "Creating a process and running it" so even if there is an other api, there will still be 200 processes (which, by the way, is nothing to worry about unless you're on a really, really tiny system)
Comment: You might want to reduce the number of spawned processes to a sane number anyway, though. You may need to run 200 commands in total, but likely not all of them at the same time. Batches of less than 10 at a time should suffice.
Comment: We are running an utility which will send some requests to a server. In order to load the server, we need to run the utilities in parallel. And when we start 200+ processes on a machine, its memory utilization goes high. And we do not have any permission to change the code in the utility to send more requests. So we are looking for an alternative. But it seems like there is not other way rather than changing the code in the utility itself.
Comment: @user1283104 You need to know what the utility actually does, then you can write the c# code to do it.
Comment: @Jodrell: Thats the point. Neither we are not supposed to change the code in the utility we are calling nor to simulate the working of the code using another utility. We have to use it and that is the reason am looking for alternatives. But it seems like I dont have much options . I will re-consult with my team regarding developing another utility with better options. Thanks for the help guys.
Answer: You could but, shouldn't do
using Microsoft.VisualBasic;

Interaction.Shell(...);

Note: You would have to add a reference to the the VisualBasic assembly.
This is a direct answer to your question but, not somthing you should do.
Comment: Can you please elaborate why "shouldn't do"
Comment: @user1283104 because, internally it is doing the same as Process.Start but encapsulates all the control and feedback away from the caller. It would be better to write a function to do the start, using the `Process` class directly. You wouldn't need to import the VisualBasic assembley and you would have more control over the usage.
Answer: As Max Keller pointed out, System.Diagnostics.Process always starts a new system process.
If have to start processes/operations for more than just some seconds, I would prefer to save all commands in a temp file and execute this with System.Diagnostics.Process rather than ever single operation.
// Get a temp file
string tempFilepath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "MyBatchFile.bat");
// Ensure the file dont exists yet
if (System.IO.File.Exists(tempFilepath)) {
    System.IO.File.Delete(tempFilepath);
}
// Create some operations
string[] batchOperations = new string[]{
    "START netstat -a",
    "START systeminfo"
};
// Write the temp file
System.IO.File.WriteAllLines(tempFilepath, batchOperations);

// Create process
Process myProcess = new Process();
try {
    // Full filepath to the temp file
    myProcess.StartInfo.FileName = tempFilepath;
    // Execute it
    myProcess.Start();
    // This code assumes the process you are starting will terminate itself!
} catch (Exception ex) {
    // Output any error to the console
    Console.WriteLine(ex.Message);
}

// Remove the temp file
System.IO.File.Delete(tempFilepath);

Comment: @user1283104 Using the [START](http://ss64.com/nt/start.html) windows will spawn a new process for each operation. I've edited my example.
Comment: Is that one of those asynchronous batch files?
Comment: @GodLesZ: Thanks for the help.. Now giving it a try.. :)


Flaw in conditional expectation shortcut

Question: The problem is simple: given 2 independent uniform random variables $X, Y$ over $[a, b]$, find $\mathbb{E}[X - Y \ | \ X > Y]$.
My intuitive approach is to first fix $Y = y$, then for this specific case, we have
$$\mathbb{E}[X - y \ | \ X > y] = \mathbb{E}[X - y \ | \ X \in [y, b]] = \dfrac{b+y}{2} -y = \dfrac{b-y}{2}$$
Now we can integrate over $Y = y \in [a, b]$ to get:
$$
\begin{align}
\mathbb{E}[X - Y \ | \ X > Y]
&=\int_a^b \mathbb{E}[X - y \ | \ X \in [y, b]] \cdot \dfrac{1}{b-a} \ \mathrm{d}y \\
&= \int_a^b \dfrac{b-y}{2} \cdot \dfrac{1}{b-a} \ \mathrm{d}y \\
&= \dfrac{b-a}{4}
\end{align}
$$
which is wrong, as the correct answer (verified computationally) should be $\dfrac{b-a}{\color{red}3}$.
What is the flaw in my logic?
Comment: Both are wrong. Without independnece of $X$ and $Y$ (or some other information)  there is no answer to this question.
Comment: Right, edited the question. $X, Y$ are iid, uniform random variables.
Answer: You are misapplying the rule, valid for $X$, $Y$ independent,
$$E[h(X,Y)]=\int E[h(X,y)]f_Y(y)\,dy.$$ The rule is valid when evaluating the expectation of a function $h(X,Y)$ of $X$ and $Y$, such as $h(X,Y):=X-Y$, but it does not apply to $h(X,Y):= X-Y\mid X>Y$, which is not a function of $X$ and $Y$.
Answer: I am using the following:
$$
\mathbb{E}[g(X,Y) \ | \ r(X,Y) ] = \iint g(x,y) \ f(x,y \ | \ r(x,y)) \ \mathrm{d}x \ \mathrm{d}y
$$
where:

$g(X,Y)$ is a function of $X, Y$, in my case $g(X,Y) := X - Y$
$r(X,Y)$ is the region we condition on, in my case $r(X,Y) := X > Y$

Now we need the conditioned PDF:
$$
f(x,y  \ | \ x > y) = \dfrac{f(x,y)}{p(X > Y)} = \dfrac{2}{(b-a)^2}
$$
for $a \leq y \leq x \leq b$.
and we can proceed with the integration:
$$
\begin{align}
\mathbb{E}[X - Y \ | \ X > Y ]
&= \int_a^b \int_y^b (x-y) \ f(x,y \ | \ x > y) \ \mathrm{d}x \ \mathrm{d}y \\
&=  \int_a^b \int_y^b (x-y) \ \dfrac{2}{(b-a)^2} \ \mathrm{d}x \ \mathrm{d}y \\
&= \dfrac{b-a}{3}  \ \ \blacksquare
\end{align}
$$
Answer: You are trying to claim that $\mathsf E(X-Y\mid X>Y)=\mathsf E(\mathsf E(X-y\mid X>y)_{y:=Y})$  but
$$\begin{align}\mathsf E(\mathsf E(X-y\mid X>y)_{y:=Y})&=\int_a^bf_Y(y)\dfrac{\int_y^b~(x-y)~f_{X}(x)~\mathrm d x}{\mathsf P(X>y)}~\mathrm d y\tag{RHS}\\&=\int_a^b \dfrac{1}{b-a}\int_y^b\dfrac{(x-y)}{(b-y)}\mathrm d x\mathrm d y\\&=\int_a^b\dfrac{b-y}{2(b-a)}\mathrm d y\\&=\dfrac{b-a}{4}\end{align}$$
Where as:
$$\begin{align}\mathsf E(X-Y\mid X>Y) &=\dfrac{\int_a^b\int_y^b (x-y)~f_{X}(x) f_Y(y)~\mathrm d x~\mathrm d y}{\mathsf P(X>Y)}\tag{LHS}\\&=\dfrac{1}{2}\int_a^b\int_y^b\dfrac{(x-y)}{(b-a)^2}~\mathrm d x~\mathrm d y\\&=\int_a^b \dfrac{(b-y)^2}{2(b-a)^2}~\mathrm dy\\&=\dfrac{b-a}{3}\end{align}$$


Are these boxing/unboxing examples

Question: Are 2 and 3 boxing/unboxing examples?
1) The documentation example:
int i = 123;
object iBoxed = i;
i = (int) iBoxed;

2: Is the boxing/unboxing as well?
int i = 123;
object iBoxed = i;
i = Int32.Parse(iBoxed.ToString());

3: Is the boxing/unboxing as well?
int i = 123;
object iBoxed = i;
i = Convert.ToInt32(iBoxed);

I assume that in all examples technically happens the same.

A value type is created on the stack
A reference is created on the stack, the value is copied to the heap.
The heap value is copied to the reference. The reference gets deleted.

So I guess 2 und 3 are examples for boxing/unboxing?
Comment: i think so, since you put int in an object "box" and then you retireve it form that box. The idea behind box and unbox is to change a value type to a reference type and back
Answer: In all three examples:
iBoxed is a boxed copy of i.
In example 2:
There is no unboxing involved here, as ToString is a virtual method that will finally resolve to int.ToString, which will then be parsed by int.Parse, returning a non-boxed int on the stack.
In example 3:
iBoxed will get unboxed in the body of the method Convert.ToInt32 and returned as a non-boxed integer, on the stack again.
Comment: I fixed example 2, which didn't compile anyway.
Answer: The second example is boxing but not unboxing.  The int.parse won't compile because it expects a string and iBoxed is an object.  I think you are mixing the concepts of boxing and conversion.  Boxing is really about taking a value type ie POD as they say in C and treating it as reference unboxing is the ability to extract that same value type out of its container.
Ex 2.  Fixed
int i = 123;  // Assigment
object iBoxed = i ; // This is boxing
i = int.parse(iBoxed.toString());  //This is unboxing but only for the twostring method the assignment is a value type copy.

Answer: It's object iBoxed = i which do the boxing.
Example 2 wont work since int.Parse expects a string
Answer: In all your examples, the value type i is being converted to an object.  This is the definition of boxing according to MSDN.  Boxing could also be done by:
object boxed = (object)i;

The unboxing is the conversion of the object back to a value type.
Example 1 is unboxing
Example 2 will fail to compile because Parse expects a string argument but would be unboxing if you did iBoxed.ToString()
Example 3 i suspect is not unboxing because the Convert method will just return the value that you pass in.
Its worth being aware of the performance hit of boxing and unboxing.  It is more expensive than normal assignment.

Are these boxing/unboxing examples


In a step for proving $\sum\limits_{cyc}{abc}\le5$ when $a + b + c + d + e = 5$.

Question: I had the following problem in my book-
$$
abc + bcd + cde + dea + eab \le5
$$
which is to be proved for non - negative real numbers satisfying $a + b + c + d + e = 5$.
Suppose $min(a,b,c,d,e) = e$,
My question is: Is this even possible?
Say on an occasion, $b$ is the least,
It's obvious as the sum is cyclic not symmetric,
\begin{equation}
\begin{split}
f(a,e,c,d,b)
&= aec + ecd + cdb + dba + eab\\
&= abd + abe + ace + bcd + cde\\
\end{split}
\end{equation}
Hence,
$$
f(a,b,c,d,e) \neq f(a,e,c,d,b)
$$
This was the first step to the solution to this problem, in my textbook.
But in my opinion, this is wrong.
May someone explain me where I went wrong, if I did.
Thanks!
Comment: @DavidG.Stork $\sum_{cyc}{abc} = abc + bcd + cde + dea + eab$. I didn't mention it there because it is already known to involve $5$ variables (as $a + b + c + d + e = 5$).
Comment: The sum in your title doesn't involve $d$ or $e$... why?
Comment: I would definitely argue the title is written correctly using cyclic notation.
Comment: @TeresaLisbon $f(a,b,c,d,e)\neq f(a,e,c,d,b)$ is correct. I have tried that the statement of the first line of proof of the solution is incorrect. It said: Suppose $min(a,b,c,d,e) = e$.
Comment: There is nothing wrong in *assuming* that $e$ is the smallest (so it is not always true, but we imagine it is and proceed), but it seems you are on to something. What happens in the proof after that?
Comment: @TeresaLisbon If any of the variables except $e$ is the smallest, then the inequality is not the same, that is what I have shown in my post.
Comment: Yes, you are right, the inequality is not the same. So those cases will have to be handled. I wanted to know the rest of the book proof to see how that is handled : that is, if the book is handling the case "$a,b,c$ or $d$ is the smallest of the five" the way you are saying, it is definitely wrong.
Comment: @TeresaLisbon Definitely not. It just assumes that $e$ is minimal and proves the inequality.
Comment: You are correct : one cannot assume **WLOG** that $e$ is minimal. One is *losing generality* if $e$ is minimal, as you point out.  So the book must be doing the other cases separately, and if not then there's something off. If there is still a confusion, and you feel the book is not wrong, then direct me to the book so I can read the proof and rephrase it for you. Every good book will still have some unclear statements.
Comment: @TeresaLisbon I am adding the entire proof to the question...
Comment: Thank you so much for this discussion, +1 to your question.
Comment: The proof is given by @nguyenhuyen_ag in one answer.
Answer: I think the proof in book is

Note $$abc + bcd + cde + dea + eab = e(c+a)(b+d)+bc(a+d-e). \quad (*)$$
Suppose $e = \min (a,b,c,d,e)$ and using the AM-GM inequality,
we have $$e(c+a)(b+d)+bc(a+d-e) \leqslant\frac{e(c+a+b+d)^2}{4}+\frac{(b+c+a+d-e)^3}{27} $$
$$=\frac{e(5-e)^2}{4}+\frac{(5-2e)^2}{27}.$$ We need to prove
$$\frac{e(5-e)^2}{4}+\frac{(5-2e)^2}{27} \leqslant 5,$$  equivalent to
$$(e+8)(e-1)^2 \geqslant 0.$$ Done.

Note. Now, what happened if $b$ is the least? The key is identity $(*).$
Indeed, if $b = \min (a,b,c,d,e)$ we write $(*)$ as
$$abc + bcd + cde + dea + eab = b(c+e)(a+d)+de(c+a-b).$$
$$ \leqslant \frac{b(c+e+a+d)^2}{4}+\frac{(d+e+c+a-b)^2}{27}.$$
$$ = \frac{b(5-b)^2}{4}+\frac{(5-2b)^2}{27}.$$
If $c = \min (a,b,c,d,e)?$ We write $(*)$ as
$$abc + bcd + cde + dea + eab=c(b+e)(a+d)+ae(b+d-c).$$
$$\leqslant  \frac{c(5-c)^2}{4}+\frac{(5-2c)^2}{27}.$$
Similar to $c, d,a$ is the least, and using the AM-GM inequality as above.
Conclude. Without loss of generality we can suppose $e = \min(a,b,c,d,e).$
Comment: Yes, this is the proof in my book!
Comment: Can you please insert the whole proof if $b$ was the least?
Comment: @BookOfFlames Now I get it : the proof was done for $e$ the smallest. If $b$ is the smallest, then $e \to b$ is like a cyclic shift of $2$ indices.  So in the proof for $e$ being the smallest, just literally change $e \to b, a \to c,b \to d,c \to e, d \to a$ in each of the statements, and you get the proof if $b$ is the smallest! Similarly if $c$ is the smallest, $e \to c$ is a cyclic shift of $3$, so shift all variables in the statements by $3$
Comment: @TeresaLisbon If that is calculus, I don't understand as I don't know much of it.
Comment: @BookOfFlames See update post.
Comment: @nguyenhuyen_ag Yes, thank you! (accepted)
Comment: The equivalence doesn't use calculus, it uses just LCMs , polynomial factorization and so on. There is an error in the power of $5-2e$ which I have asked to be corrected.
Comment: @nguyenhuyen_ag Correction : the $5-2e$ has $3$ as exponent everywhere, not $2$.
Comment: @TeresaLisbon Then too I am not familiar, if $e\rightarrow b $ and $b\rightarrow d$ then $e\rightarrow d$?
Comment: @BookOfFlames I will try to explain. See, if $e$ is the smallest then we had some argument which worked, right? Now, what happens if $b$ is the smallest? The identity $*$, which we used for $e$, is *cyclically invariant* : if we "cycle" or "shift" permute $a,b,c,d,e$ ,then we get another way of expressing the LHS. For example, the identity used to prove the $b$ smallest situation, is obtained from the $e$ situation by changing every $e$ to $b$, every $a$ to $c$, every $b $ to $d$, every $c$ to $e$ and every $d$ to $a$. Continued...
Comment: @BookOfFlames Once we do that, we observe that the same inequality which we had to prove for $e$, comes out except that $e$ is replaced by $b$. So, the *entire proof for $b$ smallest is a "cyclical" permutation of the entire proof for $e$ smallest*. For this reason, it is *possible* (but I would still disagree) to say "WLOG" let $e$ be the smallest, because one can *reproduce* the proof for $b$ smallest, from the proof for $e$ smallest, by cycling the indices. (Note : by $e\to b$, I meant : change every $e$ to a $b$ in the proof, and so on.).
Comment: @TeresaLisbonYes I saw that in the above answer. But it is difficult to come up with such proof, and even more tough to notice the WLOG!
Answer: While you already have a good answer which shows why it doesn't matter in the specific problem, please note that this is in fact general.
It is true that in ANY cyclic case, we may WLOG take any of the variables to be the minimum (or maximum).  This is because you can cycle through $(a, b, c, d, e)  \rightarrow (b, c, d, e, a) \rightarrow (c, d, e, a, b)  \rightarrow (d, e, a, b, c) \rightarrow (e, a, b, c, d)...$ to get the minimum (or maximum) to occupy the first position or the last position, or any of the positions you desire.
In your particular e.g. what matters is that $f(c, d, e, a, b) = f(a, b, c, d, e)$, so it doesn't matter if $b$ is the smallest instead of $e$.
In fact you can even say WLOG things like let $a, b, c$ be s.t. $b \geqslant \max(a, c)$. Again the logic is the same, in a (cyclic) sequence, you will somewhere always find one number at least as high as its neighbours, and then you can cyclically push that triplet to the front. Or things like WLOG let $b-a$ be the highest among consecutive differences.  If that helps solve the particular inequality in question, great!
Comment: Could you please explain in more detail how in **any** cyclic sum WLOG we can assume a variable to be minimal or maximal?
Comment: That's what is done above. Which line is troublesome to you?
Comment: I have learnt that symmetric sum we can assume WLOG any variable is minimal. But how does it occur in cyclic sum?
Comment: In a symmetric sum you can do much more. You can assume $a,b,c,d,e$ are in order for e.g. - say ascending.


When finding a derivative, would you be able to distribute factors or would you have to use the product rule?

Question: Lets say we have $f'(x)$ when $f(x)=(x^2+3)(x^3-1)$.
We could use product rule with $u = (x^2+3)$ and $v = (x^3-1)$, but we would get the same answer if we had just multiplied $uv$ before taking the derivative.
Does this apply to any problem where we take the derivative of two factors being multiplied and why? If so, why would we ever need to use the product rule? Does the same apply for the quotient rule (although i understand that for quotient rule, it would be easier to simplify when not dividing variables)?
Comment: you are thinking about polynomials only. product rule is useful to find a derivative of, for example, $f(x)=x^2e^x$
Comment: Do you want to get $f'((x^2+3)(x^3-1))$ or $f'(x)$ when $f(x)=(x^2+3)(x^3-1)$?
Comment: $2\cdot3=6$. This means that you can replace $2\cdot3$ by $6$, or conversely, in any correct formula.
Answer: Sure, you are always free to make any valid algebraic simplification at any time, e.g. expanding a product of polynomials.  So a problem like this one can be done either by using the product rule, or by first multiplying out the polynomials and then using just the power and sum rules.  Both methods will yield the same answer.

If so, why would we ever need to use the product rule?

Well, think about an example like
$$\frac{d}{dx} \left[(8x^6+3x^5-2x^4+x^3-9x^2+2x+3)(2x^5+x^4-x^3+4x^2-8x+4)\right]$$
You can certainly multiply out all 42 terms if you like, but I think you would find it much more convenient to use the product rule here.
Also, not all functions are polynomials; if you want to find $\frac{d}{dx} x \sin(x)$ there is not really an obvious way to "multiply it out".

Does the same apply for the quotient rule (although i understand that for quotient rule, it would be easier to simplify when not dividing variables)?

Sure, if the quotient can be simplified.  But this is not always possible; if you look at $\frac{d}{dx} \frac{x^2+2x+2}{x^2+7x+12}$, the numerator and denominator have no common factors, so you can't really write it in a simpler way.
Answer: Yes, you can multiply them together first.
$$f(x) = (x^2+3)(x^3-1) \implies f(x) = x^5-x^2+3x^3-3$$
$$f'x = 5x^4+9x^2-2x$$
Using the Product Rule gets the same answer. For questions regarding polynomials, using the it might not be necessary since multiplying them directly gives the answer quickly.
However, not all functions are in this form. As said in one of the comments, imagine you have a function like $f(x) = x^2e^x$.
How would you differentiate that function? Here, the Product Rule comes in handy.
$$(fg)' = f'g+g'f$$
Our $f(x)$ is $x^2$ and our $g(x)$ is $e^x$. We know that $f'x = 2x$ and $g'x = e^x$.
So, we can find the derivative of $x^2e^x$ using it.
$$(x^2e^x)' = (x^2)'e^x+(e^x)'x^2$$
$$(x^2e^x)' = 2xe^x+x^2e^x \implies \boxed{(x^2e^x)' = e^x(2x+x^2)}$$
Or, for example, $f(x) = x\sin(x)$. Once again, we can't multiply the terms, so we'll use the rule again.
$$(x\sin(x))' = x'\sin(x)+\sin'(x)x \implies \boxed{(x\sin(x))' = \sin(x)+x\cos(x)}$$
As you can see, neither of those functions were polynomials. For such problems in which simplification via multiplication is impossible/hard, you can use the Product Rule.
The exact same idea applies to the Quotient Rule, which is essentially a "variation" of the Product Rule.
Comment: $\cos(x)\sin(x)$ might not be the best example since we _can_ "multiply terms" to get $\frac12\sin(2x)$.
Comment: Ah yes, didn't think about possible simplification there. Thanks for pointing out.


Is the "browser cookies" the same as HTTP cookies

Question: Just to be clear and not playing with words, the term "browser cookies", is the same as the HTTP cookies. Or is there a difference?
Thanks
Answer: Browser cookie is just another way of saying HTTP cookie and vise versa.
You have two types of cookies one that stay even when you close your browser and another that disappear when you close your browser. look up Session cookies and persistent cookies.


Increment padding with wildcard

Question: I have a function which creates an arbitrarily deep unordered list like such (with stuff in-between). The HTML output looks like;

Stuff

Stuff

Stuff

More Stuff

Even More Stuff

Stuff

I am using CSS wildcards to select the ul classes
ul[class^='side-nav-level-'] { styling }

This works nicely for selecting all the classes, but I wish to indent the list like so
-Stuff
-Stuff
-Stuff
    -More Stuff
        -Even More Stuff
-Stuff

Currently it looks like this
-Stuff
-Stuff
-Stuff
-More Stuff
-Even More Stuff
-Stuff

How can I get the incrementing classes to increase the left-padding incrementally using CSS? I was thinking something with nth-child but I can't think how to increase the padding size each time.
My last option is to in-line the style within the function, but I was curious if there is a CSS solution.
Answer: What's wrong with using padding-left?

ul[class^='side-nav-level-']{
    margin: 0; /* reset browsers default margin styles*/
    padding-left: 20px; /* add some padding value */
}

Stuff

Stuff

Stuff

More Stuff

Even More Stuff

Stuff

Note: You didn't close the
 on your .side-nav-level-3

Even More Stuff

                                         ---^---

Increment padding with wildcard


What is A flat to C minor?

Question: I know that Cm is the relative minor of Eb.
I noticed the Eb chord is made up of two of the same notes of Cm (beginning on the third degree). Ab is also made up of two of the same notes, but on the opposite side of the Cm chord.
I wondered if Ab/Cm have a particular relationship (like 'relative' for Eb/Cm)?
Comment: About the chords sharing notes, that is Ab and Cm sharing C and Eb, in a way it's related because together you've got an Ab7. If you build a minor triad from the third, you end up with a 7 chord. That is, if Ab is the one, the third would be C, so you build a Cm and you end up with Ab C Eb G or Ab7.
Comment: I should have said a major 7th chord - AbM7
Answer: Your question is mostly about chords, but the term "relative minor" is about key signatures. I will answer from both perspectives:
Key Signatures
"Relative major" and "relative minor" are terms typically used to describe keys with identical key signatures and root notes a minor third apart. So, when we compare C minor and Eb major, the key signature is 3 flats and C and Eb are a minor third apart, so we say C minor is the relative minor of Eb major, or vice versa, that Eb major is the relative major of C minor. Another common example is the 0b/0# natural key signature and the relationship between C major and A minor.
Now, if we compare Ab major to C minor, we can't get too far off the ground since Ab is a major third away from C, not a minor third. However, if we get a little creative we can come up with a logical answer:
Let's consider that both chords come out of the same heptachord (set of 7 notes, a.k.a. key signature). We need the notes Ab, C, Eb, and G, which means the fewest number of flats we can use is going to be 3 (see also: Order of flats). This is convenient, because the relative major of C minor is Eb major, or 3 flats.
Now, the "creative" part is that I'm going to extend our terminology to make use of the diatonic "church modes" (lydian, ionian, mixolydian, dorian, aeolian, etc.), so that we can talk about any keys relative to one another that share the same key signature. Aeolian and minor as terms here are interchangeable, since their key signatures are identical.
In this system, I would say that Ab major triad outlines the relative lydian to C minor, because in our key signature of 3 flats (we've already established that the relative major of C minor is Eb major, or 3 flats), the mode that starts on Ab is the lydian mode.

Sidebar: As another example of how I'd use this terminology, consider the chords G minor and A minor. It is possible to draw a relationship between them in the key signature of F (one flat) by saying the G minor triad outlines the relative dorian of A phrygian, and that the A minor triad outlines the relative phrygian of D dorian. This should work for any two chords that are possible within a single valid key signature.

Chords
This, I imagine, is going to be closer to the answer you were really looking for.
When we talk about chords, we don't use the terms "relative minor" or "relative major", instead, we talk about functional relationships. For example, G major is the dominant of C major. C minor is called the submediant of Eb major. In the other direction, Eb major is called the mediant of C minor.
These names, and a much more in-depth explanation can be found on the above linked Wikipedia article. Mediant relationships involve distances of a 3rd.
So then, if we look at the chords in your question (Ab major, C minor, Eb major) and we are in the key of C minor, we would say Ab is the submediant of C minor and Eb is the mediant of C minor.
Comment: Actually, relative minor/major (and parallel major/minor) can also be applied to chords, at least in Neo-Riemannian theory. I've added answer to explain this.
Answer: In Neo-Riemannian theory, this relationship is called a Leading Tone Exchange (often abbreviated "L"), and is one of the three fundamental transformations that can be performed to a chord. The other two are Parallel (P) and Relative (R) which are much better known.
If you look at the geometric triangle that a chord makes on a Tonnetz map, these three operations (L, P, and R) can each be visualized as creating a new chord by flipping the existing one over one of its edges. This is because each of the transformations only involves changing a single note.

A Parallel exchange (P) involves switching chords by raising or lowering the third of the chord.
A Relative exchange (R) involves switching chords by raising the 5th of a major chord (or dropping the root of a minor chord) by a whole step.
A Leading-Tone exchange (L) involves switching chords by raising the 5th of a minor chord (or dropping the root of a major chord) by a half step.
Answer: Cm is the relative minor of Eb because they have the same key signature.  I don't think the chords overlapping is anything other than coincidence.  For example, the "relative minor" of G Mixolydian could be said to be Am, and the G Major chord (which fits G Mixolydian) does not share any notes with the Am chord. Conversely, D Dorian also has the same key signature as Am, and both Dm (in the key) and D Major (not in the key) share only the A with Am.
You could certainly give a name to this relationship you're seeing and describe other keys according to it.  You can look at the differences/similarities between any two keys and transpose up or down to find another pair of keys with exactly the same characteristics, in fact.  But that doesn't make the relationship useful :).  In this case I don't think there is a name or obvious use for this relationship, and Cm / Ab are not closely related keys.

What is A flat to C minor?


Acsessing field data for a views template

Question: I have a client who wants to be able to input a content type which allows for the upload of 4 different pdf files. They want to have a view that allows them to click on one link and load each pdf file in a separate tab. I can get this to work in the footer of the view with the global text option and inputting the following code:
[title]

The problem is, I need this to work in the fields using the global text option but full html is not allowed there. I am trying to use a views template file to input the code but I can not figure out how to access the data that is supplied by the replacement patterns in the view. Any tips on how I can assign variables with the right data in the template file?
Answer: Use the Theme: Information in the Advanced part of the view configuration (you need to click the Advanced link to expand it).
Here you can explore all the possible templates for that specific view and specific display. But additionally you can click the specific template and see the default code (in your case you will use Row template I guess). There you can see the available variables.
To print out the specific values, I would recommend Devel module and then the kpr() or dpm() functions, like this: dpm($fields); in your template.
Alternatively, you can use debug($fields); without using the Devel module.
Important: Do not forget to delete these debug functions before deployment.


Comparação de Data (status a vencer)

Question: tenho uma data informada ($date_crl) e preciso mostrar um alerta em 3 condições:
Se date_crl for maior que 30 dias da data atual: VIGENTE.
Se date_crl for menor que a data atual: VENCIDO.
Se date_crl falta 30 dias ou menos para vencer: ALERTA
Estou com dificuldade para conseguir pegar esses 30 dias?
Comment: Como essa data está formatada? Você poderia colocar o que você já fez ou tentou fazer na sua pergunta?
Answer: exemplo - ideone
A principal função usada no exemplo foi strtotime

a data atual pode ser em qq formato válido desde que seja igual ao formato da data $date_crl

<code>//Exemplos de formato data atual
//$dataAtual = date("Y-m-d H:i:s");
//$dataAtual = date("d-m-Y");
//$dataAtual = date("Y-m-d");

$time_atual = strtotime($dataAtual);

$time_expira = strtotime($date_crl);

$dif_tempo = $time_expira - $time_atual;

$dias = (int)floor( $dif_tempo / (60 * 60 * 24));

if ($dias <= 30 && $dias > 0){
    echo "ALERTA";
}elseif($dias<0){
    echo "VENCIDO";
}else{
    echo "VIGENTE";
}
</code>
Comment: Certo, sua resposta me ajudou muito a descobrir onde estava errando. Fiz a alteração no IF e alterei o post
Comment: Certo, mas o ALERTA seria para 30 ou menos dias. Se passar da data, aí fica VENCIDO. Por isso usei o: `$dias <= 30 && $dias > 0`
Comment: Qual a sua sugestão nesse caso ?
Comment: editei a pergunta de modo que a edição que vc fez na reposta esteja de acordo com o desejado.
Comment: ah ta, valeu Leo!

Comparação de Data (status a vencer)


Finding the limit of function - exponential one

Question: Find the value of $\displaystyle \lim_{x \rightarrow 0}\left(\frac{1+5x^2}{1+3x^2}\right)^{\frac{1}{\large {x^2}}}$
We can write this limit function as :
$$\lim_{x \rightarrow 0}\left(1+ \frac{2x^2}{1+3x^2}\right)^{\frac{1}{\large{x^2}}}$$
Please guide further how to proceed in such limit..
Answer: Write it as
$$\dfrac{(1+5x^2)^{1/x^2}}{(1+3x^2)^{1/x^2}}$$ and recall that $$\lim_{y \to 0} (1+ay)^{1/y} = e^a$$ to conclude what you want.
Answer: $$\lim_{x \rightarrow 0}\left(1+ \frac{2x^2}{1+3x^2}\right)^{\frac{1}{x^2}}$$
$$=\lim_{x \rightarrow 0}\left(\left(1+ \frac{2x^2}{1+3x^2}\right)^{\huge{\frac{1+3x^2}{2x^2}}}\right)^{\huge{\frac2{1+3x^2}}}$$
$$=\left(\lim_{\frac{2x^2}{1+3x^2} \rightarrow 0}\left(1+ \frac{2x^2}{1+3x^2}\right)^{\huge{\frac{1+3x^2}{2x^2}}}\right)^{\huge\lim_{x \rightarrow 0}{\frac2{1+3x^2}}}=e^2$$
as $x\to0\implies \frac{2x^2}{1+3x^2}\to0$
Comment: @GitGud, thanks for your help.
Comment: No problem. I suggest that you use \large for the limits instead of \huge. Also try \lim \limits_{x\to 0} instead of \lim _{x\to 0}.
Comment: @GitGud, btw, do you know how to wrap text in the cell of a table using latex?
Comment: I don't understand what you want.
Answer: Let $n = \displaystyle\frac{1}{x^{2}}$:
$\displaystyle \lim_{x \rightarrow 0}\left(\frac{1+5x^2}{1+3x^2}\right)^{\frac{1}{\large {x^2}}}$ = $\displaystyle\lim_{n \rightarrow \infty}\left(\frac{n + 5}{n + 3}\right)^{n}$ = $\displaystyle\lim_{n \rightarrow \infty}\left(1 + \frac{2}{n + 3}\right)^{n}$ = $\displaystyle\lim_{n \rightarrow \infty}\left(1 + \frac{2}{n}\right)^{n}$ = $e^{2}$
by definition of $e$.
Answer: Based on the fact that
$$\forall\,a\in\Bbb R\;,\;\;\lim_{x\to x_0}\left(1+\frac{a}{f(x)}\right)^{f(x)}=e^a\;,\;\;\text{whenever $\,f\,$ is a function s.t.}\;\;f(x)\xrightarrow[x\to x_0]{}\infty$$
we get:
$$\left(1+ \frac{2x^2}{1+3x^2}\right)^{\frac{1}{x^2}}=\left(1+ \frac{2}{3+\frac{1}{x^2}}\right)^{3+\frac{1}{x^2}}\left(1+ \frac{2}{3+\frac{1}{x^2}}\right)^{-3}\xrightarrow[x\to0]{}e^2\cdot  1=e^2$$


Recuperar e calcular valores de EditText gerada programaticamente

Question: Eu estou criando um app pqra calcular uma média aritmética de N valores. Existe um botão add, quando for clicado ele vai gerar um EditText programaticamente. E vai ter um botão calcular, quando ele for clicado, deve mostrar a media das EditText criadas.
Porém não estou conseguindo recuperar os valores dessas EditText pra usar no botão calcular. Abaixo está meu código java:
private ArrayList<EditText> listEdit = new ArrayList<>();
botaoAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            aviso.setVisibility(View.GONE);
            LinearLayout layout = (LinearLayout) view.findViewById(R.id.container); //criar o container(pai)
            listEdit.add(new EditText(getActivity()));
            listEdit.get(count).setBackgroundColor(Color.WHITE);
            listEdit.get(count).setHint("Media " + count);
            listEdit.get(count).setGravity(Gravity.CENTER);
            listEdit.get(count).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

            layout.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(300,100); // tamanho do container
            layoutParams.setMargins(0,15,0,0);
            layout.addView(listEdit.get(count),layoutParams); //adicionando a view ao container
            count++;
        }
    });

botaoCalc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int i =0; i < listEdit.size(); i++){
                String texto = listEdit.get(i).getText().toString();
                if(!texto.isEmpty()){
                    Double valor = Double.parseDouble(texto);
                    Double result = 0.0;
                    result = result + valor;
                    Double media = result/(i+1);
                    resultado.setText("media " + media);
                }
            }
        }
    });

Como eu li em outros posts aqui, recomendaram sempre guardar os valores das EditText em uma ArrayList para usar ela. O problema desse código é que ele não esta somando os valores, ele apenas está pegando o valor da última EditText e dividindo pelo número de EditTexts (no caso, o i do for).
Answer: A média tem que ser calculada fora do laço:
Double total = 0.0;
for (int i = 0; i < listEdit.size(); i++) {
  String texto = listEdit.get(i).getText().toString();
  if (!texto.isEmpty()) {
    total += Double.parseDouble(texto);
  }
}
Double media = total / listEdit.size();
resultado.setText("media " + media);

Comment: Ahhh, eu alterei tanta coisa, usei chieldCont, e nao reparei nesse detalhe. Deu certo aqui, vlw :D
Comment: O único detalhe é que nesse caso usar `double` (o tipo primitivo) ao invés de `Double` (a classe empacotadora) é mais eficiente porque evita autoboxes e autounboxes desnecessários.
Answer: List<EditText> colecaoEditText = newArrayList<EditText>();
int vezesClicados = 0;

addButton.setOnClickListener(new OnClickListener(...){
    EditText editText = new EditText(MinhaActivity.this);

    meuContainer.addChild(editText);
    colecaoEditText.add(editText);
    vezesClicados++;
});// Pode adicionar quantos quiser e ele estará no ArrayList

//vamos pegar o valor de todos com um loop (abaixo)
for(int i = 0; i <= vezesClicados; i++){
    //aqui você pega o valor dos editTexts pelo índice dele no array e faz o que quiser
    colecaoEditText.get(i).getText().toString(); //aqui eu só mostrei como vc pegaria o texto do editText
}

Comment: Hm, deu certo dessa maneira tbm, vlw :D
Comment: Com grandes poderes vem grandes responsabilidades em, hahaha, passe adiante


randomize position of marker on google map

Question: This problem has really troubled me and yet to have a solution.
I have a list of locations with latitude and longitude.
And each time i click on the button next, it suppose to auto open the infowindow of the location one by one each click. However, the infowindow and marker always open at the center. May I know how can I make the location of infowindow randomized instead of opening at the center of the map only? Is there any way I can hide the marker and set the beak of infowindow to the pointer of marker?
Thanks. Kinda urgent.
Answer: How are you opening your infoWindow?  The open method on an infoWindow object takes a map parameter and an optional MVCObject parameter.  If you specify the appropriate marker for the second parameter, then the info window will be attached to that marker.
N.B. I am assuming you are using the current Google Maps API v3.  If you are using the v2 API, let us know.


Como comparar se um texto em excel e igual a parte do nome de uma arquivo em pdf em C#?

Question: Gostaria de começar um código que lesse uma coluna numa planilha de excel que contem numeros de CNPJ e comparasse com os nomes de arquivos em PDF em uma pasta.
Exemplo: valor numa celula de excel versos nome do arquivo em PDF, se forem iguais true, senão false.
Poderiam me dar uma luz.
Ler a planilha já fiz, mas não sei como percorrer os arquivos em PDF salvos na pasta.
ABAIXO o código que leio os arquivo:
static void Main(string[] args)
{

    string[] arquivos = Directory.GetFiles(@"C:\Projects\MOD01-EnvioDeE-mail\fila\");

    Console.WriteLine("Arquivos:");
    foreach (string arq in arquivos)
    {
        string newArq = arq;

        Console.WriteLine(arq);

    }

}

ABAIXO o código que leio a planilha.
using System;
using System.Collections.Generic;
using System.Linq;
using ClosedXML.Excel;
using System.Text;
using System.Threading.Tasks;
using System.IO; // A BIBLIOTECA DE ENTRADA E SAIDA DE ARQUIVOS
using iTextSharp; //E A BIBLIOTECA ITEXTSHARP E SUAS EXTENÇÕES
using iTextSharp.text; //ESTENSAO 1 (TEXT)
using iTextSharp.text.pdf;//ESTENSAO 2 (PDF)

namespace LerPlanilhaExcel
{
   class Program
   {
     static void Main(string[] args)
     {
        IXLWorkbook wb = new XLWorkbook();
        IXLWorksheet ws = wb.Worksheets.Add("Sheet");
        wb.SaveAs(@"C:\Projects\LerPlanilhaExcel\LerPlanilhaExcel\excel\MeuExcel.xlsx");

        var workbook = new XLWorkbook(@"C:\Projects\LerPlanilhaExcel\LerPlanilhaExcel\excel\MEI_ATIVO26072021.xlsx");
        StreamWriter logCnpj = new StreamWriter(@"C:\Projects\LerPlanilhaExcel\LerPlanilhaExcel\log\logsCnpj.txt");

        int contador = 0;
        int cont = 1;

        for (int i = 1; i <= 89; i++) //são 89 praças
        {
            var sheet = workbook.Worksheet(i);
            var linha = 2;

            while (true)
            {

                var email = sheet.Cell("O" + linha).Value.ToString();
                var cnpj = sheet.Cell("C" + linha).Value.ToString();

                if (contador == 5) break;
                if (string.IsNullOrEmpty(cnpj) && (string.IsNullOrEmpty(email)))
                {
                    ws.Cell(cont, 1).Value = "CAMPO VAZIO";
                    ws.Cell(cont, 2).Value = "CAMPO VAZIO";
                    wb.SaveAs(@"C:\Projects\LerPlanilhaExcel\LerPlanilhaExcel\excel\MeuExcel.xlsx");
                    contador++;
                }
                else
                {
                    Console.WriteLine(sheet.ToString() + linha + ": " + cnpj + "---" + email);
                    logCnpj.Write(cnpj + "###" + email + "\r\n");

                    ws.Cell(cont, 1).Value = cnpj;
                    ws.Cell(cont, 2).Value = email;
                    wb.SaveAs(@"C:\Projects\LerPlanilhaExcel\LerPlanilhaExcel\excel\MeuExcel.xlsx");
                }

                if (cnpj == )
                {

                }

                //System.Threading.Thread.Sleep(100);
                linha++;
                cont++;

            }

            contador = 0;

        }

        workbook.Dispose();
        logCnpj.Close();
        Console.WriteLine("END");
    }
}

}
Comment: Isto responde à sua pergunta? [Buscar arquivos pela extensão](https://pt.stackoverflow.com/questions/296284/buscar-arquivos-pela-extens%c3%a3o)
Answer: Para percorrer os arquivos de uma pasta você pode utilizar o metodo GetFiles de DirectoryInfo.
DirectoryInfo directory = new DirectoryInfo("Caminho completo da sua pasta");

//Irá selecionar todos os arquivos que possuem extensão .PDF
FileInfo[] files = directory.GetFiles("*.pdf");

O metodo GetFiles retorna um array de FileInfo, dessa forma você consegue percorrer o array e fazer a comparação que precisa.
foreach (var item in files)
{
    //item.Name é o nome do arquivo
    if(item.Name == "")
    {

    }
}

Comment: Certo. Gostaria de comparar um numero tipo assim: valor na planilha do exce: 24585524000150 e est é o nome do arquivo DAS-PGMEI-24585524000150.pdf Acho, que esqueci de explicar isso melhor.
Comment: Beleza, você só precisa manipular essa string e extrair o numero que quer comparar. Esse numero é um CNPJ e sempre vai estar no final do nome? tente dessa forma: string cnpj = item.Name.Substring(item.Name.Length - 18, 14); estou dando um substring nos ultimos 14 caracteres que é o tamanho de um CNPJ. Vai depender de como esse nome do arquivo foi criado.


convex, twice differentiable functions

Question: Show that if $f:(a,b) \to \mathbb{R}$ is convex, twice differentiable on $(a,b)$ and $c$ is a stationary point, then $c$ is a local minimum point.
I have gone round in circles with this question and am now completely lost and would appreciate any help given
Comment: In the first paragraph you seem to omit the existence of $c$ inside interval $(a,b)$, but rely on this fact in the second paragraph.  It would be better to state this more clearly in the beginning.
Comment: Your definition of local minima seems to be off. You are implicitly enforcing uniqueness on the minima. For e.g., $f(x)=42$ is a twice differentiable function on $(0,1)$ with $0.5$ (or any point in that interval) being a local minima. But there second derivative is $0$.
Comment: yes but f(x) = 42 isn't a complex function so surely that wouldn't matter?
Answer: Quick answer: a convex (differentiable) function always lies above its tangent lines. The tangent line at $c$ is $y=f(c)$ because $Df(c)=0$. Therefore $f(x) \geq f(c)$ for every $x$.
Comment: would i not need a strict inequality to be able to say that f(c) is a local minimum?
Comment: Well, it depends on your definition. I never use a strict inequality to define local minima or maxima.

convex, twice differentiable functions


How to schedule a Rules component at the end of the month?

Question: The users on my website can flag articles with Flag. I want them to be able to do this exactly once every month, but they do not have permission to unflag content. Therefore, my plan is to create a Rule that triggers when an article is flagged and that schedules a Rules component that takes care of the unflagging.
How can I schedule this component at the end of the month, i.e. which value should I add in the field Scheduled evaluation date of the action Schedule component evaluation?
Answer: Introducing last day of 23:59 works for me (last day of is the last day of the current month, and 23:59 just before the day ends). You can see the full reference of DateTime relative formats here: http://php.net/manual/en/datetime.formats.relative.php
In general, you can pass anything recognised by strtotime() as the scheduling date.
Comment: By default it is scheduled at the current time of the day. If you need it at a given time, it needs to be specified explicitly. I have just updated my answer.
Comment: Cool! Is the component then by default scheduled at midnight of the last day?
Answer: Your question seems a variation of "Schedule a mail on the 1st day of the following month", which has an accepted answer like so:

Try "first day of +1 month" as your scheduled date.

With that, you may get it to work by using something like "last day of +0 month" as your scheduled date, or maybe simply  "last day of month".
Another approach (plan b ?) might be to try to use the "Day of the month" Rules Condition that comes with the Rules Ones per Day module. Though in that case you have to specify an integer for the monthday (between 1 and 31). So to make that work for each month (with 31, 30, 29 or 28 days) you might end up with pretty complicated Rules logic (possibly combined with the Conditional Rules module to consolidate it all in a single rule). If however it would be acceptable for your case, I'd rather use "1st day of the month" (= 1 day later), which would avoid such complicated rule.


How to debug a MySQL error? [Updated]

Question: I have been building a Drupal 7 site on my Mac. Using PHPMyAdmin, I have exported a sql dump of the database. When I upload this sql file to my host, I get the following error message:
There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

ERROR: Unknown Punctuation String @ 280
STR: =,
SQL:

-- --------------------------------------------------------

--
-- Table structure for table `themekey_properties`
--

CREATE TABLE `themekey_properties` (
  `id` int(10) UNSIGNED NOT NULL,
  `property` varchar(255) NOT NULL DEFAULT '',
  `operator` varchar(2) NOT NULL DEFAULT=,
) ;

SQL query:

-- -------------------------------------------------------- -- -- Table structure for table `themekey_properties` -- CREATE TABLE `themekey_properties` ( `id` int(10) UNSIGNED NOT NULL, `property` varchar(255) NOT NULL DEFAULT '', `operator` varchar(2) NOT NULL DEFAULT=, ) ;

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=,
)' at line 10

How would I go about debugging this? I have searched extensively, but not found any websites that explain how.
The website functions perfectly on my localhost. I have done this process hundreds of times before, and never had any problems.
I seem to have this exact problem when transfering other sites from my Mac to my host, so I am not sure if it is a global problem. The affected sites all use themekey module which is referenced in the error message, but I can't find anything online which indicates why themekey would be causing the problem.

Updated.
I followed the @Erin McLaughlin's answer, but now I get the following error:
CREATE TABLE `themekey_properties` (
  `id` int(10) UNSIGNED NOT NULL,
  `property` varchar(255) NOT NULL DEFAULT '',
   `operator` varchar(2) NOT NULL DEFAULT '=',
)
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 5

Updated.
I followed @Erin McLaughlin's second suggestions, but now I get the following error:
SQL query:

INSERT INTO `themekey_properties` (`id`, `property`, `operator`, `value`, `weight`, `theme`, `enabled`, `wildcards`, `parent`, `module`) VALUES
(1, 'themekey_compat:module_system_triggers_theme', '=', 'static', 5, 'default', 1, 'a:0:{}', 0, 'themekey'),
(2, 'drupal:path', '=', 'user/#/edit', 2, 'default', 1, 'a:0:{}', 0, 'themekey')
MySQL said: Documentation

#1054 - Unknown column 'value' in 'field list'

Comment: The answer below is correct, but if the question philosophically is "How do I debug this?" then you've already accomplished that.  If the end result of debugging is to find the source of the error, well, MySQL reported that there was a syntax error, the line number, and the location of the error. Debugging can take you that far, but you still need enough domain knowledge to be able to identify the bug, and that's no longer a process question. Until then, "Ask about the problem on Stack Exchange" is a perfectly good approach.
Answer: It has got to do with the line:
`operator` varchar(2) NOT NULL DEFAULT=,

It's because the equals sign isn't surrounded with a space and then quotes, which is breaking everything. If you want to have = be the default operator, that line needs to be:
 `operator` varchar(2) NOT NULL DEFAULT '=',

Comment: This is just a guess, but try removing the final comma?
Comment: Erin answered the original question. A new question should go into a new question.
Comment: thanks, but now I get a new error (see original post).
Comment: I still get an error. Do you think it might be something else that is not related to the database contents. Although I'm not sure what it could be!!
Answer: Erin's answer is correct to the original question, so I have marked it correct. However, the problem had nothing to do with importing the mysql code. It was to do with how I was exporting the mysql in the first place.
I was simply using PhpMyAdmin's built in export tools, but for some reason, this was creating errors.
I solved the problem by using mysql commands in the command line.
If anyone has problems where the database's don't import properly, then it might be worth exporting them using the method below:

Use this command in the command line:
mysqldump -u DATABASEUSER -p'PASSWORD' DATABASENAME > dump.sql

In this command, you mustn't have a space after -p. So your command might look like this:
mysqldump -u host_mary -p'pass123' marywebsite > dump.sql

Create new databases. You can do this in PhpMyAdmin as normal.
Finally, import code into the new databases using this command
mysql -u DATABASEUSER -p'PASSWORD' DATABASENAME < dump.sql

How to debug a MySQL error? [Updated]


Helly-Bray theorem for vague convergence in $\mathbb{R}^k$?

Question: A Borel measure $\mu$ on $\mathbb{R}^k$ can be represented by a "distribution function" $F : \mathbb{R}^k \to \mathbb{R}$ via $F(x_1, \dots, x_k) = \mu ((-\infty, x_1] \times \dots \times (-\infty, x_k])$. Note that $\mu$ need not be a probability measure. If we have a sequence of Borel measures $\mu_n$ on $\mathbb{R}^k$ then $\mu_n \to \mu$ vaguely is defined by $\int g d\mu_n \to \int g d\mu$ for all continuous functions $g : \mathbb{R}^k \to \mathbb{R}$ with compact support. Denote by $F_n$ the distribution functions of $\mu_n$. In the one-dimensional case $k = 1$ the Helly-Bray theorem states that
$\mu_n \to \mu$ vaguely if and only if $F_n(x) \to F(x)$ at all continuity points $x \in \mathbb{R}$ of $F$.
Does this theorem generalize to $\mathbb{R}^k$? I have only seen a "Helly-Bray theorem" for weak(!) convergence (with bounded continuous test functions) of probability(!) measures on $\mathbb{R}^k$ (proven via the Portmanteau theorem). Weak convergence and vague convergence coincide for probability measures, so I suppose that this theorem should be generalizable to vague convergence of arbitrary Borel measures on $\mathbb{R}^k$.
Answer: The Helly-Bray theorem also holds for $\mathbb{R}^n$.
"$\Rightarrow$": Assume that $\mu_n \to \mu$ vaguely. By the Portmanteau theorem for vague convergence, $\mu_n(B) \to \mu(B)$ for all bounded $\mu$-continuity Borel sets $B \subseteq \mathbb{R}^n$. For $i = 1, \dots, n$ denote by $D_i \subseteq \mathbb{R}$ the set of continuity points of the marginal measure $\mu_i$ on $\mathbb{R}$. Then $D_i$ is countable and $C := D_1^c \times \dots \times D_n^c$ is dense in $\mathbb{R}^n$. For any point $u \in C$, the set $(-\infty, u]$ is a $\mu$-continuity set. Therefore, $u$ is a continuity point of $F$. Any rectangular box $(a, b]$ with $a, b \in C$ is a $\mu$-continuity set. Any corner $u$ of $(a, b]$ is contained in $C$.
With this in mind, let $x$ be a continuity point of $F$. We can decompose $(-\infty, x]$ into a countable collection of boxes $(a^k, b^k]$ with $a^j, b^j \in C$. Since all these boxes $(a^j, b^j]$ are $\mu$-continuity sets, we get
$F_n(x) = \sum_j \mu_n(a^j, b^j] \to \sum_j \mu(a^j, b^j] = F(x)$ by the bounded convergence theorem.
"$\Leftarrow$": Assume that $F_n(x) \to F(x)$ for all continuity points $x$ of $F$. For a box $(a, b]$ it holds $\mu(a, b] = \Delta^a_b F$ which is an alternating sum over values $F(x)$ with $x$ a corner of $(a, b]$. If $a, b \in C$ then all the corners of $(a, b]$ are contained in $C$ and since $F$ is continuous on $C$ we get $\mu_n(a, b] = \Delta^a_b F_n \to \Delta^a_b F = \mu(a, b]$. Let $g : \mathbb{R}^n \to \mathbb{R}$ be continuous with compact support. Then $\textrm{supp}(g) \subseteq (a, b]$ for some $a, b \in C$. Let $\varepsilon > 0$. Since $g$ is uniformly continuous on $(a, b]$ and $C$ is dense in $\mathbb{R}^n$ we can partition $(a, b]$ into finitely many boxes $(a^j, b^j]$, $j = 1, \dots, m$ with $a^j, b^j \in C$ such that $\sup_{x \in (a^j, b^j]} |g(x) - g(b^j)| < \varepsilon$ for all $j$. Decompose $\int g d\mu = \sum_j \int_{(a^j, b^j]} g d\mu$. We can approximate
$$\left|\int g d\mu - \sum_j g(b^j) \mu(a^j, b^j]\right| = \left|\sum_j \int_{(a^j, b^j]} (g(x) - g(b^j)) \mu(dx)\right| \\
\leq \sum_j \sup_{x \in (a^j, b^j]} |g(x) - g(b^j)| \mu(a^j, b^j] < \varepsilon \cdot \mu(a, b]$$
and similarly for all the $\mu_n$. It follows
$$\left|\int g d\mu_n - \int g d\mu\right| \leq \left| \int g d\mu_n - \sum_j g(b^j) \mu_n(a^j, b^j]\right| + \left| \sum_j g(b^j)(\mu_n(a^j, b^j] - \mu(a^j, b^j])\right| \\
+ \left| \int g d\mu - \sum_j g(b^j) \mu(a^j, b^j] \right| \leq 2\varepsilon + \lVert g \rVert \sum_j |\mu_n(a^j, b^j] - \mu(a^j, b^j]|.$$
As $n \to \infty$, the right-hand side converges to $0$ (the sum is finite) and we get
$\limsup_n |\int g d\mu_n - \int g d\mu| \leq 2 \varepsilon$. Since this is true for all $\varepsilon$, $\int g d\mu_n \to \int g d\mu$. Therefore, $\mu_n \to \mu$ vaguely.


Node edit page not showing up using page.tpl.php?

Question: I'm working on a new drupal 7 site right now (I'm new to drupal) and currently have given the ability to users to create nodes. The node creation page (url.com/node/add/) works just fine and uses the page.tpl.php template.
However, when I'm using the edit page (url.com/node/NODEID/edit/), it doesn't even load a page.tpl.php file. I went ahead and added some code to my page.tpl.php file to see if it would even read out--which it didn't. I've found that the edit page is inserting itself at the html.tpl.php level of the site. Is there a quick way I can get this to use page.tpl.php or by creating a node--edit.tpl.php or something? Hopefully I have made enough sense, but am stuck.
Answer: Make sure you have the setting 'Use the administration theme when editing or creating content' unchecked in you 'appearance' settings page. This would override your theme on the node edit pages causing your page.tpl.php file not to be used.


Python/Selenium: HTMLUNIT Driver Connection Refused - Port Blocked

Question: I am trying to set up and use HTMLUnit driver in Python 3. I believe I have the server running (v3.7.0) and believe the code should work based looking up other questions on here. I believe that the remote server uses port 4444 but my ISP locks that port down (along with basically every other port). Currently when I run the code I get a connection refused. Is this to do with the port being closed? Can I change the port to 8080 (which is open)?
from selenium import webdriver
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS)
driver.get('http://www.google.com')

Current output:
urllib.error.URLError: <urlopen error [Errno 61] Connection refused>

Comment: Are you able to launch any other browser? Also is the server running on the same machine or a external machine? Because if server runs on same machine then port blocking may not matter
Comment: @TarunLalwani Yes, I can launch with Chrome and Safari with no issue but I would like to try HTMLUnit as it appears to be the fastest browser. Yes, the server is running on the same machine. I ran it by typing `java -jar selenium-server-standalone-3.7.0.jar` into the terminal window in Pycharm.
Comment: when you say chrome works? Did you run it using `driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.CHROME)`
Comment: @TarunLalwani no I did not try and run chrome remotely.
Comment: If you are doing it on a local machine then only thing that would block access is a firewall. ISP won't come into picture when you are testing on a local system
Answer: From this Link:
You can use:
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNITWITHJS)


Como acessar outro aplicativo com banco de dados SQLCipher, passando a senha no Content Provider?

Question: No código abaixo, eu concedo acesso ao banco de dados no app1, utilizando Content Provider, que faz uso do SQLCipher:
App1
public class StudentsProvider extends ContentProvider {

private SQLiteDatabase db;

@Override
public boolean onCreate() {
    Context context = getContext();
    DatabaseHelper dbHelper = new DatabaseHelper(context);
    SQLiteDatabase.loadLibs(context);
    db = dbHelper.getWritableDatabase("password");
    return db != null;
}

No app2, eu faço a query no banco de dados do app1:
App2
static final String PROVIDER_NAME = "com.example.a436236692.myapplication.StudentsProvider";
static final String URL = "content://" + PROVIDER_NAME + "/students";
static final Uri CONTENT_URI = Uri.parse(URL);
private void carregaResultados() {
    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(CONTENT_URI, null, null, null, null);
    if (c.moveToFirst()){
        //reading db...
    }
}

Mas eu quero passar a senha pelo Content Provider, do app2 para o app1 e mudar esse hardcode:

db = dbHelper.getWritableDatabase("password");

Qual a melhor maneira de fazer isso?
Obrigado!
Answer: Que eu saiba isso não é possível.
O que deve fazer é definir permissões que as aplicações que queiram aceder ao provedor devem ter.
No AndroidManifest da aplicação do provedor declare um ou mais elementos <permission>:
...
<permission android:name="com.example.myapp.permission.DEADLY_ACTIVITY"
    android:label="@string/permlab_deadlyActivity"
    android:description="@string/permdesc_deadlyActivity"
    android:permissionGroup="android.permission-group.COST_MONEY"
    android:protectionLevel="dangerous" />
...

Aplicações que desejarem usar o provedor terão de declarar no seu AndroidManifest os respectivos <uses-permission>.
Referências:

Permissões do provedor de conteúdo.
Definir e impor permissões.
Comment: Eu já imaginava que não pelo content provider, tentei manipular o URI passando o dado por ele, mas não funciona. Referente as permissões, estão tudo de acordo. O problema é que ao acessar o DB com SQLCipher, apenas com o contexto da app2, o app1 retorna nulo. Eu lí sobre utilizar o sharedpreferences e passando usuário e senha, só não sei o quanto isso é seguro. Se puder me dar uma luz do que eu possa implementar, ficarei muito grato. Obrigado de qualquer forma. =)
Comment: Também tinha pensado no URI mas não vi como. Não entendi o que quer dizer com "o app1 retorna nulo".
Comment: Quis dizer que sem senha, o retorno da resposta do app1 é nulo. Como tabela não retornou o objeto, aí a aplicação "quebra", por causa do null pointer.
Comment: Mesmo usando `db = dbHelper.getWritableDatabase("password");`?
Comment: Desta forma funciona! Sem senha que dá erro...
Comment: Então qual é o problema? Se é ter a *password* no código, na minha opinião, não é problema. No entanto veja [Onde guardar credenciais de conexão à API no Android](https://pt.stackoverflow.com/q/194393/2541).


Need for another Domain Controller

Question: I have two domain controllers (Windows 2003) in one site where most of the department I support resides. There is another building (at another site) where my department resides as well, but they have no DC.
This probably a classic question of whether to install an additional DC when a company is spread out over multiple sites.
We've been experiencing various issues like login scripts not mapping drives and users failing to login several times before being let in (even though they're typing the right password).
I'm getting different errors on the clients. Some of them are :
Netlogon, 5719, This computer was not able to set up a secure session with a domain controller in domain domain.com due to the following:
There are currently no logon servers available to service the logon request.
This may lead to authentication problems. Make sure that this computer is connected to the network. If the problem persists, please contact your domain administrator.
GroupPolicy, 1055, The processing of Group Policy failed. Windows could not resolve the computer name. This could be caused by one of more of the following:
a) Name Resolution failure on the current domain controller.
b) Active Directory Replication Latency (an account created on another domain controller has not replicated to the current domain controller).
On the servers I keep getting these errors:
Netlogon, 5722, The session setup from the computer SOMEPCNAME failed to authenticate. The name(s) of the account(s) referenced in the security database is SOMEPCNAME$.  The following error occurred:
Access is denied.
*(this above error keeps repeating for the same computer. Probably just need to re-add this to domain. ) *
NTDS Replication, 1864, This is the replication status for the following directory partition on the local domain controller. Directory partition:
CN=Schema,CN=Configuration,DC=domain,DC=com
This last one looks like it has to do with a DC that wasn't completely removed. When I ran dcdiag, it showed that we are trying to replicate with a server that doesn't exist anymore. I don't think this would cause us to have all these logon problems though.
I'm wondering if we should install another DC or try something else. Our clients run mostly windows 7, but there some XP and Vista clients as well.
The bandwidth looks to be 37.4 Mbs between PCs on the different sites (just verified with this utility iperf).
Any help is appreciated.
Comment: Anything over 10Mb with reasonable latency should be plenty fast enough that you don't "need" a DC at the other location. I'd check for problems in the network first, but you may want a DC there for a variety of reasons anyway.
Comment: Thanks for the input. I feel that this bandwidth is more than adequate but something (most likely the network) keeps interfering with the logon process.
Comment: If you can't authenticate across the connection I suspect replication across the connection would be an equally difficult challenge.
Answer: There is a lot of room in your question for other problems to be causing problems, but on the surface (if you are fairly certain that everything else is working as expected) you sound like you may be a good case for a Read-Only Domain Controller (RODC).
This would necessitate upgrading to Server 2008 for your DCs (which is a good idea, anyway; 2003 is nearing end-of-life), and a little care in setting up the RODC, but it could solve your problems well.
Yes, you could just set up another 2003 DC in the remote office, but it sounds like there isn't an IT presence there, so a RODC may be 'safer'.  RODCs are good where you may not have an IT staff, especially if you don't have a safe and secure area for the server (no server room / lockable racks, shady neighborhood, etc)
Also keep in mind that the mapping of drives over the network is going to eat up bandwidth, and by itself could be a major cause of your problems.  It may be worthwhile to investigate a local implementation of a storage solution (such as DFS or CIFS servers).
If you haven't already, separating your organization based on location (whether by Sites or just OUs) could also help you with managing traffic and user experience.
Comment: @gWaldo mainstream support ended last year for windows 2k3 - it's not just near EOL it's already in the extended support phase.
Comment: This sounds like a really good idea. Upgrading to a 2008 domain seems like a bigger project then I was hoping for. Thanks for the suggestion!
Comment: Actually, Upgrading AD is less of a big deal than upgrading Windows to 2008; it's pretty simple, though I recommend reading the docs and making a checklist before starting it.  Likewise with the RODC; it's not hard, but there is a procedure to follow.
Comment: Thanks; I didn't feel like looking up it's support status. #lifeistooshort
Answer: @gWaldo has a good idea in terms of increasing reliability and updating your outdated DC, but it's a "guess" as to if it'll fix the issue. @Chris-S is correct in comment that bandwidth (at first glance) doesn't sound like it's the issue either.
First you should ensure that WAN connection is reliable, has no packet loss, and has ample available bandwidth throughout the day.
Also a DC not being available will not prevent a Windows client login (assuming default GPO's) because cache credentials on a domain let you in.  It would help if you posted the actual errors the users are getting.
For mapped drives, if they are done by login script then you have little to no ability to see any logs about that info, but I would move that functionally to Group Policy Preferences which will let you map drives, make them persistent, and also log to the client event logs on any issues.  Your mapping issues could be either they can't get the script, or they can't access the drive... but hard to tell without logging.
Again, keeping DC's current and having one at remote site is "better" but is just throwing darts at the wall of this specific issue.  I've had 70-100 remote sites on much lower WAN speeds with no remote DC's act just fine as long as connection was reliable and had available bandwidth.
Comment: Thanks for your insights. I keep getting NTDS kcc, netlogon and group policy errors as described above. We are running the domain in 2000 mixed mode. It sounds like it's time to upgrade.
Comment: If your oldest DC is running 2003 then you can upgrade the forest and domain mode to 2003 native right now.  2000 Mixed mode is generally bad as it allows for NT 4 domain controllers which is insecure and not meant for modern networks.
Comment: Could there be any possibility of users not being able to login or exchange 2003 getting messed up if I switch to native 2003? Exchange will probably be happier in native, but just checking. Thanks.
Comment: nothing is certain but no the only reason I can think of to stay 2000 mixed is NT4 DC's.  Your forest/domain version is not related (directly) to how things authenticate... it's related to how DC's talk to each other and new features of Active Directory.
Answer: I would definitely put another dc at the remote site to provide some redundancy should the connection between the sites fail.

Need for another Domain Controller


Is there any exceptions to be avoided in this simple class?

Question: This is from a practice exam, anyhow, I was thinking, what are the exception that I should take care of?

Thanks.
Answer: The first one that comes to mind is NullPointerException if you're doing anything with the name.  For instance, if Employee's or SessionalEmployee's toString() were do anything with the name other than displaying it...
Answer: I think obvious runtime exceptions mean here NullPointerException, ArrayOutOFBoundsException, IllegalArgumentException and so on, so your code will run without obvious failures.


Moebius strip orientability

Question: Let $\{M\}$ be the one-sided Moebius strip and $\{MM\}$ the corresponding two-sheeted Moebius strip.
Let us assume $\{MM\}$ to be the doubling of $\{M\}$; hence it is orientable.
Then, $\{M\}$ is orientable, too?
I assume the definition of doubling from:

A Texbook of Topology, Seifert and Threlfall:
  ~24*: Moebius band is the simplest example of a non-orientable pseudomanifold with boundary.
36: We define doubling for a pure complex: we take a homeomorphic copy...and we identify points of the boundary...with points of the boundary... A pseudomanifold with boundary is a bounded pure complex whose doubling is a closed pseudomanifold.
  The pseudomanifold with boundary is orientable if and only if its doubling is orientable.
https://en.wikipedia.org/wiki/Glossary_of_differential_geometry_and_topology:
  Doubling, given a manifold M with boundary, doubling is taking two copies of M and identifying their boundaries. As the result we get a manifold without boundary.
The Geometry of Physics by T. Frankel:
16.11: Each non-orientable manifold has a 2-sheeted orientable covering manifold...

UPDATE To answer to @Christian Blatter (I'm new to this site, sorry I'm not yet allowed to answer...):
I admired your symbolism. It is only a symbolism, but how useful it is! By it, shortly: $D_{\rm ST}(M)$ a closed manifold; ${\rm DC}(M)$ a manifold with boundary.
Surely I used $D_{\rm ST}(M)$ in a cavalier manner.
I add an image link here to describe my case study: Moebius Strip Composition
A 2D Intrinsic Observer, with left, front, right, aft, no top, no bottom.
Left hand, one-sided, sheet #1 Moebius strip ${\rm M1}$, twist 0->Π rad, with closed boundary of lenght ~2(L+l).
In series to it, in the same cover: the left hand, one-sided, sheet #2 Moebius strip ${\rm M2}$, twist Π->2Π rad, with closed boundary of length ~2(L+l).
The length of the closed Midline of ${\rm M1}$ being that ${\rm L}$ of the generating one-sided plain rectangular <code>(L*l)</code> Strip ${\rm S}$. The boundary of ${\rm M1}$ is equivalent to the boundary of ${\rm S}$. The same for ${\rm M2}$.
The above pair yielding the (assumed transparent), one-sided, two-sheeted, oriented manifold ${\rm MM}$, total twist 0->2 Π rad; the former superposed boundaries reduced to an inner curve.
I must analyze ${\rm DC}(M1)$ and $D_{\rm ST}(M1)$ in ${\rm MM}$.
Comment: Identifying two möbius bands along their boundary gives the Klein bottle, which is not orientable.
Comment: @Noah: quite rightly you quoted Klein bottle, got by one left hand Moebius strip and one right hand Moebius strip.
My fault was not presenting my case in study, say: one l.h. Moebius, one l.h. Moebius, and their composition.
Answer: The doubling ${\rm ST}(M)$ of a manifold with boundary $M$ according to the definition in Seifert-Threlfal is completely different from a double cover ${\rm DC}(M)$ of $M$. Note that $D_{\rm ST}(M)$ is a closed manifold whereas the double cover ${\rm DC}(M)$ doubles  the boundary as well, hence is again a manifold with boundary.
You get the double cover of a Moebius strip $M$ if you first manufacture a model of $M$ from paper. Then each point $p\in M$ is a puncture of the paper, and is visible on both sides. You obtain the double cover ${\rm DC}(M)$ of $M$ by viewing the two aspects of the puncture on the two sides of the paper as two different copies of $p$. By walking from $p\in M$ once around $M$ you arrive at the same puncture, but you have to walk twice around $M$ to arrive at the same point in ${\rm DC}(M)$.

Moebius strip orientability


How do I make a Deep Copy of a UIElement?

Question: So I have a printing component that serves a Silverlight application.  Other modules in this program have the ability to signal the printing component and pass it a UIElement, which the printing component will then draw to the screen.  All well and good.  The problem arises when I try to manipulate the UI Element in order to better format it to fit the user's selected paper size or anything to that effect;  it seems that the UI element that is passed in is frequently the exact same instance of the one on the screen, and the screen element changes itself to match the 'print-only' changes I have made.  For now, I can manually save the previous values, make my changes, and restore the previous values, but it would be easier/more robust/more efficient/more flexible if I had a way to, given the UI element, make a copy of the element, and manipulate that freely, without worrying about alterations or state on the original UI element.  How can I programatically copy an instance of a UI element such that I have another instance with the same visual appearance?
Answer: I know 2 ways you can try:
Save the object to a xaml string and recreate it from it.
(XamlWriter.Save and XamlReader.Parse)
Save the object with the serializer to a memorystream and recreate it from that - it is possible that not all objects are marked serializable so the other option might be the one to use.
It might seem a bit much - but there are not so many ways to create a deep copy - and not any standard c# method that I know of.
Comment: Also if you don't show the object you recreate and just send it printing with different margins you probably need to call Measure(..) and Arrange(..) to get anything drawn.
Comment: Are those the only 2 things that need to be called?
Comment: string XamlWriter.Save(Object)  gives you a string and Object XamlReader.Parse(string xamlText) gives an object you can insert - so yes that should be it - you can probably do: var uielementcopy=(UIElement)XamlReader.Parse(XamlWriter.Save(myUIelement));
Comment: It looks like you have to use XamlReader.Load(string) for silverlight - and the writer doesn't seem to be there .. take a look at this for a writer: http://www.davidpoll.com/2010/07/25/to-xaml-with-love-an-experiment-with-xaml-serialization-in-silverlight/


Apache2 403 permission denied on Ubuntu 12.04

Question: I have a sub-directory in my /var/www folder called prod, which is password protected. It was all working fine until I asked my server admin to help me set up allow all access to one particular file. Now the entire folder is just giving me a 403 error. This is the sites-enabled file:
<VirtualHost *:80>
  ServerAdmin firstname.lastname@example.com
  # Server name
  ServerName prod.xxx.co.uk
  DocumentRoot /var/www/prod
  <Directory /var/www/prod>
    Options Indexes FollowSymLinks MultiViews +ExecCGI Includes
    AllowOverride None
    Order allow,deny
    AuthType Basic
    AuthName "Please log in"
    AuthUserFile /home/ubuntu/.htpasswd
    Require valid-user
  </Directory>
 <Directory /var/www/prod/xxx/cgi-bin/api.pl>
   Allow from All
   Satisfy Any
 </Directory>
  ScriptAlias /xxx/cgi-bin/ /var/www/prod/xxx/cgi-bin/
  ErrorLog ${APACHE_LOG_DIR}/prod.xxx.error.log
  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel warn
  CustomLog ${APACHE_LOG_DIR}/prod.xxx.access.log combined
</VirtualHost>

Now he's unsure why this is blocking me out completely. No permissions have been changed, but this is the /var/www/ folder:
4 drwxr-xr-x  2 root    root     4096 Jan  3 21:10 images
4 drwxr-sr-x  4 root    www-data 4096 Mar 31 14:47 jslib
4 drwxr-xr-x  7 root    root     4096 Jun  2 13:00 prod

When I try to visit http://prod.xxx.co.uk, I don't get asked for the password; I just get 403'd
I hope I've given enough information...
Anyone able to spot something he can't?
Answer: I was missing:
allow from all

from the Directory for prod


Can I combine several ordinal questions to create an independent variable?

Question: I am currently doing a research and recently encountered a few statistical concerns. I am basing this question on the following post.
My question is quite similar to the above-mentioned one but has some important differences.
I designed a survey in order to get data from participants. This survey had 12 different items (ranked on a scale from 0 "minor importance" to 10 "major importance").
Before constructing my independent variables with these 12 items, I decided to get rid of the items that do not display a linear relationship with the dependent variable (the latter being a continuous value between 0 and 100).
After having done that, I am left with 10 items and I decide to create 3 independent variables. Each of the latter is constructed with some underlying items, based on a logical link between the items (i.e. the items referring to volatility are put together, the one referring to performance are put together...)
When constructing the variables, I decided to use the mean between the underlying items—for example, performance = (item1 + item2)/2.
My question is the following: I need to justify each step from a "mathematical" perspective with some references. For example, I know there is a unsettled debate for the use of ordinal data in regressions but fellow researchers argued that my data can be considered as interval, especially after using the mean between the items.
My question is the following: Is this mathematically ok? Also if you can cite work that did more or less the same, or that can mathematically support my steps, that would be greatly appreciated.
Thank you!
Comment: It's never "mathematically OK". Sometimes, indeed often, push comes to shove and people do something like what you describe. But it's still wishful thinking. Bear in mind that many universities average grades based on ordinal scores, even while many of their courses (e.g. in Psychology schools) explain that you really shouldn't do that. That aside, I can't see that you have a new question here on a topic that's much discussed already.
Comment: The previous post is not quite the same question. But if you can't average one ordinal variable (across different observations or cases), then it doesn't make more sense to average two or more (within each observation or case)
Comment: @NickCox Thank you for your help. I will check this link and come back to you if necessary

I also based my thinking on the following article from Norman G: https://doi.org/10.1007/s10459-010-9222-y

I think that I am mixing two different problems. The first one is to know if averaging 3 items based on a logical link between them is fine. The second is to know if that average can be used as an independent variable.
Comment: FYI: I had 56 respondents to the survey, 56*10 items = 560 answers
Comment: @NickCox Edit: I read the topic and it seems that this debate of ordinal vs interval data is at the heart of my use of the mean. I remember having discussed it with my superviser, he thinks we could treat it as interval because the ranks that are used in my statistical analysis (i.e. 0 to 10) were available as such to the respondents of the survey and even if they could not choose 6.534 as an answer, the mean remains a pretty accurate representation. I might also suggest the use of the median...
It thus remains to be seen whether I can use this mean/median as an indep. variable
Comment: Don't get me wrong: I think the mean is often a pragmatic, sensible choice. But  there are not usually deep mathematical or theoretical reasons beyond that. The median will typically be uselessly insensitive in practice, for all that in principle it makes complete sense and is well defined. Suppose your grades are 1 1 1 2 2 2 2 and 2 2 2 2 3 3 3, so the median is 2 in either case. Is that really a better summary of the data than the means? Trimmed means are an interesting direction!
Comment: @NickCox Thank you for this clarification and all the useful help. Let's consider I go on with using the average because I believe that within this context, treating an ordinal scale as interval (as many studies already did and as you mentioned in the other post), while being aware of the mathematical concerns that might pose, I could go ahead and use this average as an independent variable in my regression? I also checked the Gauss-Markov assumptions and everything seems to be well appropriate from this perspective (or is there any other concern/assumption I am missing?)
Comment: You could. Naturally the real question is whether you should. My preference is always for using the original variables as predictors and seeing how they work. But the opposite style is common in some fields, to regard the original variables as just way-stations in attempts to define underlying or latent variables. I can't at a distance and with no data in hand act as oracle to tell you the best strategy. Bear in mind that no white magic lets the regression know how you produced your predictors and whether they are valid in any sense. It's just a robot reacting to data.
Answer: Combining the independent variables before any analysis and without previous knowledge is not a good approach.
Using 10 original independent variables, the following model is possible to be fit:
$$Y=\beta_0 + \sum_{i=1}^{10}\beta_iX_i + \epsilon$$
After fitting this complicated model, the really useless independent variables (for example p>0.3) can be excluded. Then $X$s (1) with closed values of $\hat \beta$s verified by testing that their $\beta$s are the same and (2) having meaning to be combined can be combined.
Then the new independent variable can be constructed and the new model can be fitted. This approach will be reasonable and results will be better than the combination based on only the meaning of the combination.
This approach needs large sample, for example, > 500.
Comment: But this approach is still treating ordinal variables as if they were measured (interval scale), precisely what is in doubt.
Comment: @NickCox I think OP question is "performance = (item1 + item2)/2." before any analysis. My suggestion is doing something before combining.
Comment: Unless you are feeding in a predictor as indicator variables, not what your notation implies, you are treating it as on interval scale.
Comment: @NickCox Would summing the items "performance = item1+item2" solve the combination problem ?
Comment: That looks like the same question to me, so I don't have a different answer.
Comment: @NickCox Yes, my bad, sorry.


The sum of the greatest 3-digit number and the smallest 4-digit number is???

Question: Options:
A) 1999
B)  999
C) 1099
D) 109
How's it done?
Answer: HINT: What is the greatest three-digit number? What is the smallest four-digit number?
Then, add them.