Interaction has already been acknowledged Discord.js

Question: This command keeps on returning Interaction has already been acknowledged. How can I solve this?
Here's the code I'm currently using:
const {
    SlashCommandBuilder,
    EmbedBuilder,
    ButtonStyle,
    ButtonBuilder,
    ActionRowBuilder,
    ActionRow,
} = require("discord.js");

module.exports = {
    data: new SlashCommandBuilder()
        .setName("highlow")
        .setDescription(" | Starts a new high or low game!"),
    async execute(interaction) {
        const randomNumber = Math.floor(Math.random() * 100) + 1;
        const hintNumber = Math.floor(Math.random() * 100) + 1;
        const row = new ActionRowBuilder().addComponents(
            new ButtonBuilder()
                .setLabel("High")
                .setStyle("Secondary")
                .setCustomId("high"),
            new ButtonBuilder()
                .setCustomId("low")
                .setLabel("Low")
                .setStyle("Secondary"),
            new ButtonBuilder()
                .setCustomId("correct")
                .setLabel("Same")
                .setStyle("Secondary")
        );
        const sent = await interaction.reply({
            content: `Is my number higher or lower than ${hintNumber}?`,
            components: [row],
            fetchReply: true,
        });
        const collector = sent.createMessageComponentCollector({
            filter: (i) =>
                i.user.id === interaction.user.id && i.message.id === sent.id,
            time: 30000,
            max: 1,
        });
        let won = false;
        collector.on("collect", async (i) => {
            await i.deferUpdate({ fetchReply: true });
            row.components.forEach((b) => b.setDisabled(true));
            if (i.customId === "high") {
                if (hintNumber > randomNumber) {
                    row.components.forEach((b) => {
                        if (b.customId === "high") b.setStyle("Danger");
                    });
                    await interaction.editReply({
                        content: `Sadge, you got it wrong! It was ${randomNumber}`,
                        components: [row],
                    });
                    won = false;
                } else {
                    row.components.forEach((b) => {
                        if (b.customId === "high") b.setStyle("Success");
                    });
                    await interaction.editReply({
                        content: `You guessed the number! It was ${randomNumber}`,
                        components: [row],
                    });
                    won = true;
                }
            } else if (i.customId === "low") {
                if (hintNumber < randomNumber) {
                    row.components.forEach((b) => {
                        if (b.customId === "low") b.setStyle("Danger");
                    });
                    await interaction.editReply({
                        content: `Sadge, you got it wrong! It was ${randomNumber}`,
                        components: [row],
                    });
                    won = false;
                } else {
                    row.components.forEach((b) => {
                        if (b.customId === "low") b.setStyle("Success");
                    });
                    await interaction.editReply({
                        content: `You are right! It was ${randomNumber}`,
                        components: [row],
                    });
                    won = true;
                }
            } else if (i.customId === "correct" && hintNumber === randomNumber) {
                row.components.forEach((b) => {
                    if (b.customId === "correct") b.setStyle("Success");
                });
                await interaction.editReply({
                    content: `You guessed the number! It was ${randomNumber}`,
                    components: [row],
                });
                won = true;
            } else {
                await interaction.editReply({
                    content: `Sadge, you got it wrong! It was ${randomNumber}`,
                    components: [row],
                });
                won = false;
            }
        });
        collector.on("end", async (collected) => {
            row.components.forEach((b) => b.setDisabled(true));
            if (!won && collected.size === 0) {
                await interaction.editReply({
                    content: `You didn't guess the number! It was ${randomNumber}`,
                    components: [row],
                });
            }
        });
    },
};

The error is showing:
C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293
        throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
              ^

DiscordAPIError[40060]: Interaction has already been acknowledged.
    at SequentialHandler.runRequest (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async SequentialHandler.queueRequest (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
    at async REST.request (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\REST.cjs:52:22)
    at async ButtonInteraction.deferUpdate (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:192:5)
    at async InteractionCollector.<anonymous> (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\interactions\slash\fun\highlow.js:44:4) {
  rawError: {
    message: 'Interaction has already been acknowledged.',
    code: 40060
  },
  code: 40060,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1021755660406374452/aW50ZXJhY3Rpb246MTAyMTc1NTY2MDQwNjM3NDQ1MjpyMjViUU8xSGtzQ1dXZXVXbWh2YmRiczZ5ZldzcVhuYm1hNXdWWFRRSVlUUzk0MXFDV1M2NmRjQWF3MEJXTVo0TmN1UlR3U1QxQnUxVDd1YlZodjdnbnpNRVM5VlVSV1B0aUNSS2ZGZkQ5QURrdlFIenVHaUVZdTRkUmR5YnBVaQ/callback',
  requestBody: { files: undefined, json: { type: 6 } }
}

Answer: On line 44: await i.deferUpdate({ fetchReply: true }); It makes the error because the interaction has already been replied to. The error should go away when you remove this line. You also should replace await interaction.editReply with interaction.followUp on line 51, 60, 71, 80, 90, 96 and 106. And yup I answer your question again.


For what natural numbers n is $φ(n) ≡ 4 \pmod 8$?

Question: For what natural numbers n is $φ(n) ≡ 4 \pmod 8$?
For this question, first I think that I should consider in two cases. For the first case is that for n is odd number, and the second case is that $n$ is even. But I do not know how to determine how many prime factors does $n$ have in each case.
Any help will be appreciated!
Comment: Well. For all odd primes $p$ we have $2\mid\phi(p)=p-1$. For some odd primes we even have  $4\mid \phi(p)$, and for some $8\mid\phi(p)$. Undoubtedly you also know $\phi(2^n)$. Observe that for odd primes $p$ we have $\phi(p^n)=\phi(p)\cdot m$ where $m$ is an odd number. You should be able to do this by putting all these pieces together. Not all prime factors are equal for the purposes of this exercise :-)
Comment: Well, what do you know about the totient function?  Do you, say, know how to compute it from the prime factorization?
Comment: Is the function you use the totient function?
Comment: I didn't learn what is totient function yet. Sorry
Comment: I still have no clue. Since I am not sure how to start it. Thanks
Comment: What does the function you have do? For example, how would you find $φ(6)$ or $φ(7)$?
Comment: Ok I see. Yes, I use the totient function.
Answer: Well, I think that factorization of $n$ is needed to determine if $\varphi(n)\equiv 4\pmod 8$. Any number $n$ with three or more odd prime different factors holds $8\mid\varphi(n)$. So $n$ is of one of the following forms
$$\begin{align}
n=2^rp^sq^t&\to\varphi(n)=2^{r-1}(p-1)p^{s-1}(q-1)q^{t-1}\\
n=2^rp^s&\to\varphi(n)=2^{r-1}(p-1)p^{s-1}\\
n=p^sq^t&\to\varphi(n)=(p-1)p^{s-1}(q-1)q^{t-1}\\
n=p^s&\to\varphi(n)=(p-1)p^{s-1}\\
n=2^r&\to\varphi(n)=2^{r-1}
\end{align}$$
where $p$ and $q$ are odd, different primes and $r,s,t\ge 1$.
If $r>3$ then $8\mid\varphi(n)$, so in this case the congruence can't hold.
If $r=3$ then $n=8$.
If $r=2$ then $n$ must have exactly one odd prime factor $p$ and $p\equiv 3\pmod 4$.
If $r=1$ or $n$ is odd then there are more possibilities. If $n$ has two odd prime factors $p$ and $q$, it must be $p\equiv q\equiv 3\pmod 4$. If $n$ has only one prime factor $p$ it must be $p\equiv 5\pmod 8$.


Loop repeats despite reaching exit condition

Question: I have a small program that is attempting to build a right triangle.
The boundaries given by the program are that the base and height must both be in the range [10,20].
The code seems to work just fine for building triangles in the range [10,19].
However, at the boundary conditions of [n,20] or [20,n], the output goes haywire and refuses to exit the for loop that generates the middle of the triangle (between the base and top lines).
I'd appreciate assistance pinpointing the issue, thank you.
I've looked into the issue but I'm out of practice and should be treated as a novice.
The issue is definitely with the while or nested for loop after the "BUILD" comment.
Please note that there may be one or two non relevant vars defined above this block level of code provided.
//TRIANGLE//
 if (shapeselect=2)
 {
 int base;
 int height;
 //prompt use for base measurement//
 cout<<"Please select the size of the BASE of your triangle, in the range [10,20]\n"<<endl;
 cin>>base;
  while (base!=10&&base!=11&&base!=12&&base!=13&&base!=14&&base!=15&&base!=16&&base!=17&&base!=18&&base!=19&&base!=20)
  {
  cin.clear();
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  cout<<"You have entered an invalid value.\nPlease enter a valid value for the BASE of your triangle in the range of [10,20].\n";
  cin>>base;
  }
 //prompt user for height measurement//
 cout<<"Please select the size of the HEIGHT of your triangle, in the range of [10,20].\n";
 cin>>height;
 while (height!=10&&height!=11&&height!=12&&height!=13&&height!=14&&height!=15&&height!=16&&height!=17&&height!=18&&height!=19&&height!=20)
  {
  cin.clear();
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  cout<<"You have entered an invalid value.\nPlease enter a valid value for the HEIGHT of your triangle, in the range [10,20].\n";
  cin>>base;
  }
  //BUILD TRIANGLE//
 string bottom(base, '*');
 string top="*";
 int middlerows=height-1;
 cout<<top<<endl;
  while (middlerows!=1)
  {
   int middlespacechars;
   for (middlespacechars=0; middlespacechars!=base-2; ++middlespacechars)
   {
   string middlespace(middlespacechars, ' ');
   cout<<"*"<<middlespace<<"*\n";
   --middlerows;
   }
  }
 cout<<bottom<<"\n"<<endl;
 cout<<"^TRIANGLE\n";
 cout<<"BASE = "<<base<<endl;
 cout<<"HEIGHT = "<<height<<endl;
 cout<<goodbye<<"\n"<<endl;
 }

}

The top of the triangle prints (single "*").
Then the middle portion of the triangle repeats infinitely (asterisks bedded with spaces between).
Counting the rows, it seems that it is reaching the case of base-2 spaces, but not exiting.  It seems to get to line '19/20'.
Comment: What do you think is more readable: the two long expressions that are contained inside those `while` statements, or simply `while (base < 10 || base > 20)` and `while (height < 10 || height > 20)`?
Comment: Have you tried using a debugger? Specifically, does it show you the value `middlerows` inside both loops?
Comment: Also, why do you need a `while`? Won't a `for` loop work here as well?
Comment: Look at this even more, it's probably something to do with putting `--middlerows;` inside your other loop. Your logic not clear to me, but you probably want to rework that. You may only need one loop, even.
Comment: @SamVarshavchik it prevents the use of non int character Input without using additional libraries.
Comment: @chipster I did indeed begin with two for loops (one nested), but encountered the same error.  The while was just troubleshooting and it seems I've left it there; I see no functional difference.
Comment: No, it doesn't. The two simple comparisons are completely 100% logically equivalent to the novel that's currently used for the `while` loops.
Comment: Sorry, Sam, were you addressing my commend that was in reply to you, or to chipster?
Answer: After a bit of debugging, it seems that your code breaks for any input where base != height.
The issue is in your for loop - your logic in the while loop that middlerows is supposed to count down from height-1 until it hits 1 is correct, but in the for, you encounter issues if base and height aren't the same - the loop forces middlerows into a negative value, which causes it to miss your escape condition of middlerows != 1.
If, for example, the user inputs 11, 15, then on the first run-through, middlerows will be 14, and the for loop will count from 0 up to up to 9 (height-2), decrementing middlerows each time. At the end of this loop, your middlerows is now 5. 5 != 1, so the loop will run again.
After running again, middlerows is at -4. -4 != 1, so the loop runs again, dropping middlerows to -13... and then it just keeps going down, forever (or until you wrap around and get lucky, somehow perfectly hitting middlerows=1).
Comment: I'm not sure if I understand why middle rows would decrement by a value greater than one, given "--middlerows".
Comment: The middlerows variable is decremented by one given `--middlerows`, but the for loop does this decreasing **several times in a row.** This causes it to decrement a _cumulative_ value of greater than one, since your code can't check the while loop's condition while it's locked in the for loop.


How to improve performance of spark.write for jdbc?

Question: I'm struggling with one thing. I have 700mb csv which conains over 6mln rows. After filtering it contains ~3mln.
I need to write it straight to azure sql via jdbc. It's super slow and takes 20min to input 3mln rows.
My cluster has 14gb ram and 4 cores. Here is my code.
(clearedDF.repartition(4)
  .write
  .format("jdbc")
  .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
  .option("batchsize", 10000)
  .option("url", jdbcUrl)
  .option("dbtable", "dbo.weather")
  .option("user", properties["user"])
  .option("password", properties["password"])
  .mode("append")
  .save()
)

Is there any way to speed this process up?
Comment: look here: https://docs.databricks.com/data/data-sources/sql-databases.html#jdbc-writes
Answer: Thank you Alex Ott. Posting your suggestion as an answer to help community members.
"You can control the parallelism by calling  coalesce(<N>)  or  repartition(<N>)  depending on the existing number of partitions. Call  coalesce  when reducing the number of partitions, and  repartition  when increasing the number of partitions."
import org.apache.spark.sql.SaveMode

val df = spark.table("diamonds")
println(df.rdd.partitions.length)

// Given the number of partitions above, you can reduce the partition value by calling coalesce() or increase it by calling repartition() to manage the number of connections.
df.repartition(10).write.mode(SaveMode.Append).jdbc(jdbcUrl, "diamonds", connectionProperties)

For more information please refer Azure sql using jdbc.| MS DOC


selected=selected based on value in mysql database

Question: I am currently working on my own CMS where a user can add and update his projects.
Adding them works like a charm, and the update is working aswell, but when i click on a project (it gets all info based on a $_GET['id']) the categorie value is always the first option in my select element.
I know this can be achieved by adding selected="selected" to the option element, but I want to have this working with values from the database and that's where I am getting confused.
I'd like to have this part dynamic:
<select  name="categorie">
   <option value="cv">CV / Boiler</option>
   <option value="onderhoudrenovatie">Onderhoud & Renovatie</option>
   <option value="sanitair">Sanitair</option>
</select>

The option values are already written to the database in the field 'categorie' in the table 'projecten' when adding them.
Does anyone have a solution?
Thank you!
Comment: First you have to tell us what you're pulling from the database in order to help and know what to compare.
Answer: You have to get the value and assign to a variable. Then, with basic PHP you can select printing "selected" or not depending on the value.
For example something like this:
<?php $data=$_GET['id']; ?>

<select  name="categorie">
 <option value="cv" <?php if ($data=="cv") print "selected"; ?>>CV / Boiler</option>
 <option value="onderhoudrenovatie" <?php if ($data=="onderhoudrenovatie") print "selected"; ?>>Onderhoud & Renovatie</option>
 <option value="sanitair" <?php if ($data=="sanitair") print "selected"; ?>>Sanitair</option>
</select>

Comment: Thanks fedorqui! I've accepted your answer as the one that helped me (:
Comment: Your answer is troublesome and wrong. Single `=` is used to assign, `==` is used to compare.
Comment: I know. It was my first fast answer, now I am improving the answer.
Comment: Well you should consider giving a logical answer for the first time too.
Comment: It was. It is good wait till the answer is complete, as you could see is was "under construction" :)
Comment: fedorqui, no need to defend yourself!
Your solution worked like a charm =)
I know the differences between the = and the == so that was no problem at all.
Comment: PS: The solution was so easy and right in front of my eyes! Funny i didn't come up with it after a good 3 years of experience with php/mysql
Comment: Haha no problem @MichaelKoelewijn, now you will for sure remember it! :) And also mark the question as "answered" if it is done. Good luck with your project!
Answer: Try to do something like this:
$categories = array() ; //Fill your array with data from your database ;
$selectedId = (isset($_GET['id'])) ? $_GET['id'] : null ;

foreach ($categories as $cat){ ?>
   <option value="<?php echo $cat['name'] ;?>" <?php echo (!empty($selectedId) &&  $cat['id'] == $selectedId) ? "selected" : "") ; ?> >
      <?php echo $cat['name'] ; ?>
    </option>

 <?php
}


Wordpress - author dropdown / screen options not showing in admin - workaround needed

Question: I have inherited a wordpress website and the admin panel seems to be a little messed up.  There is no 'Author' dropdown on the posts admin pages.  Normally you would select this in the 'screen option' so it displays but this is not working.
Is there a setting in the database that I can set to display the author dropdown or is there another workaround so that I can have this feature?
See attached images for features missing.

Thanks
Answer: UPDATED:
One possibility is that your theme (probably in functions.php) removed that feature, something like:
remove_post_type_support( 'post', 'author' );

If you can't find it, try adding it by doing something like:
function wpcodex_add_author_support_for_posts() {
    add_post_type_support( 'post', 'author' );
}
add_action( 'init', 'wpcodex_add_author_support_for_posts' );

Comment: no thats not in there.  There hasn't been much customisation to the theme.  Is there a similar function to add the authordiv?
Comment: Not sure what else it could be. Maybe there a plugin installed that would do that?
Comment: Or switch to default WordPress theme. Would that fix the issue?


C#: Shared struct fields and inheritance

Question: Now I know that C# doesn't support inheritance of structs for a number of reasons.
I was wondering however, if it is still possible to implement some form of hierarchy for data types such that a function can rely on a variable of type B or type C having field x because they both inherit from type A.
More specific:
I have two structs that have a value field and coordinates (2D and 3D)
public struct BarDataPoint
{
    public TwoTuple<float> coords { get; }
    public float value { get; }
    public BarDataPoint(TwoTuple<float> coords, float value)
    {
        this.coords = coords;
        this.value = value;
    }
}

public struct ScatterDataPoint
{
    public ThreeTuple<float> coords { get; }
    public float value { get; }
    public ScatterDataPoint(ThreeTuple<float> coords, float value)
    {
        this.coords = coords;
        this.value = value;
    }
}

I also have this function that is supposed to find the maximum value of an array of data points
    {
        // Finds the maximum value of an BarData array
        float maxValue = data[0].value;
        foreach (BarDataPoint dataPoint in data)
        {
            maxValue = (maxValue < dataPoint.value) ? dataPoint.value : maxValue;
        }
        return maxValue;
    }

I would like to generalize this function, so that it can take both types (or any other type with a "value" field) and return its maximum value.
Is this possible? If yes, how? Or would you recommend a completely different design?
Answer: There are no problems having a struct implement an interface:
public interface IDataPoint
{
    float Value { get; }
}

public struct BarDataPoint : IDataPoint
public struct ScatterDataPoint : IDataPoint

Then you could do this:
{
    float maxValue = data[0].Value;
    foreach (IDataPoint dataPoint in data)
    {
        maxValue = (maxValue < dataPoint.Value) ? dataPoint.Value : maxValue;
    }
    return maxValue;
}

To avoid the performance hit caused by boxing in the above example, you could make the implementing method generic:
float GetMaxValue<TDataPoint>(TDataPoint[] data) where TDataPoint : IDataPoint
{
    float maxValue = data[0].Value;
    foreach (TDataPoint dataPoint in data)
    {
        maxValue = (maxValue < dataPoint.Value) ? dataPoint.Value : maxValue;
    }
    return maxValue;
}

Just be sure to always refer to data as TDataPoint within the generic method, as using IDataPoint will cause boxing (because interfaces are reference types).
The reason this works is because the generic method will be resolved to either float GetMaxValue(BarDataPoint[] data) or float GetMaxValue(ScatterDataPoint[] data) and not float GetMaxValue(IDataPoint[] data).

As an aside, if you simply need to know the maximum value, Enumerable.Max should do exactly what you're after, without the need for the above approach:
BarDataPoint[] data = //...
float max = data.Max(x => x.Value);

Comment: This might cause a performance problem due to boxing.
Comment: And [here's an SO post](https://stackoverflow.com/q/5531948/3094533) that explains how the usage of generics avoid the need of boxing. +1.
Comment: Thank you so much! This is exactly what I was looking for!


On a First Order Nonlinear Differential Equation

Question: Consider the ordinary differential equation $\dfrac{\text{d}y}{\text{d}x}=\dfrac{y-3}{x^2+y^2},$ with $y(0)=1$. My question is about determining the graph of $y$. Here is most of the information that I have gathered, arguing somewhat heuristically:
$1$. For all $x>0$, $y$ is decreasing. Also, $\dfrac{\text{d}^2y}{\text{d}x^2} = -10$ at $x=0$, so $y$ is concave downwards at this point.
$2$. $\displaystyle \lim_{x \rightarrow \infty} \dfrac{\text{d}y}{\text{d}x}=0$, hence $y$ is bounded below and has a horizontal asymptote. Similarly, $\displaystyle \lim_{x \rightarrow -\infty} \dfrac{\text{d}y}{\text{d}x}=0.$
$3$. By formulating a quadratic in terms of $y$ using the given D.E. and considering its discriminant, I can show (using contradiction) that $y$ must intersect the $x$-axis and hence will eventually be negative. This implies the lower bound is negative, and the horizontal asymptote lies below the $x$-axis. Hence the second derivative must be zero for some positive $x$, and $y$ changes concavity there.
$4$. $y$ attains its maximum for some (maximal) $x_0<0$, and $y(x_0) = 3$. So either $y$ is the constant function $y(x)=3$ for all $x<x_0$, or we have a local maximum that is also a unique stationary point, since $\dfrac{\text{d}y}{\text{d}x}=0 \iff y=3.$ For the latter, $y$ intersects the $x$ axis for some negative $x$, and there is another horizontal asymptote (the two horizontal asymptotes could be equal).
Would it be possible to determine the following?

$ -2 \leq \dfrac{\text{d}y}{\text{d}x} < 0$ for all positive $x$.
Coordinates of the point(s) where the second derivative equals zero ($y$ changes concavity).
Concavity of the graph for negative $x$.
The coordinates of the point(s) where $y$ intersects the $x$-axis, or give a bound.
The equation of the horizontal asymptote(s), or give a bound.
Existence of the turning point (maximum, assuming $y$ does not become constant for sufficiently small $x$), and its $x$-coordinate, or give a bound for it/them.

For reference, here are the possible shapes of the graph that I have in mind. Any help (including any other interesting key features that I might have missed out) will be much appreciated.
https://i.stack.imgur.com/85rKo.jpg
Answer: Decompose the equation into a system
$$
\dot x(t)=x(t)^2+y(t)^2,\\
\dot y(t)=y(t)-3,\\
x(0)=x_0,~~y(0)=y_0.
$$
The second equation has a simple exponential as solution
$$
y(t)=3+(y_0-3)e^t.
$$
With that, the first equation is of type Riccati. Setting $x=-\frac{\dot u}{u}$, $u(0)=1$, $\dot u(0)=-x_0$,  transforms this into
$$
\ddot u(t) + y(t)^2 u(t)=0.
$$
In both time directions  $y(t)$ is eventually bounded away from zero, so that the Sturm-Picone comparison theorem guarantees the existence of roots of $u$. As these are poles for $x$, the domain of $x$ is a bounded interval, its image is $\Bbb R$ and the image of $y$ is bounded on both sides.
Translated back into a $x$-$y$ relation, this means indeed that the solution $y(x)$ has horizontal asymptotes. It is not obvious if $x(t)$ is monotonous


Django API and Front-End Separation

Question: I am using Django for REST API. Currently, I am generating primitive web pages from the same Django project. I think it's in my interest to separate API logic and front end.
What is a best way to do this? Should I create another Django app, that just calls this API and generates web pages from template or should I use some other framework for this?
Thanks
Answer: You should use front-end framework like Angular, React or Vue for the front end.
So you are going to call the Django-api built from the front end.
You are not supposed to create another Django app.
Here is a link for example of using React front-end with Django-rest api.
https://hackernoon.com/creating-websites-using-react-and-django-rest-framework-b14c066087c7

Django API and Front-End Separation


What is the protocol for switching a pitcher between positions?

Question: It's kind of rare, but I've heard that it is possible to "relieve" a pitcher without removing him from the game--by making him a position player such as an outfielder, or first baseman.
My understanding is that the position player leaves, the pitcher replaces him, and a relief pitcher comes in to pitch to at least one batter. Following this, the original pitcher can return to the mound and resume pitching, while a new position player replaces the former one.
But suppose your "outfielder" happens to be Nick Swisher, or even the Pittsburgh Pirates' JB Shuck, who can pitch at least part of an inning. So can the pitcher and outfielder switch places, the outfielder finishes the inning, and the pitcher resumes the following inning with the outfielder going back to his original post?
Can this happen? (I was told that at least the outfielder needed to be replaced in this sequence.) And are clubs beginning to experiment with "swing men," position players who can pitch "strategically?" (The Pirates' Harrison got the last out in a game the team was losing by 10 points, thereby sparing a reliever.)
Answer: First, players on the field may switch positions while the ball is dead during an inning.  A pitcher could switch with an outfielder and then switch back for the next batter.  The only difference between switching between a pitcher and a position player is that a pitcher must face a batter (unless he becomes injured during the at bat).
In your scenario, the outfielder could come in to pitch and the pitcher could go to the outfield.  The next batter, or next inning they could switch back.  There is no required substitution in this situation.  It often happens late in games with limited bench players renaming.  A left handed pitcher may be brought in to face one batter, and instead of burning an extra pitcher in the process, the current pitcher is placed in the outfield for a batter.
This scenario happened to the Atlanta Braves.  You can see in the box score, Chris Resop (a pitcher) comes in to pitch, then moves to left field, and then back to pitcher.
As to your question about "swing men", the basic answer is no.  There are many position players with good arms.  There are many problems with this though.  First of all it takes a lot of time and practice to even make it to the big leagues.  This is spent on hitting or pitching, and not both.  A position player may be able to throw as hard or harder than some pitchers, but it does not mean he can throw strikes, locate pitches, hold runners, etc.  Some players that struggle hitting in the big leagues will go back to the minor leagues and convert to a pitcher.  This again takes time to perfect.  The other issue with "swing men" is that there is an organization of 100+ players, and to have a position player that is better than those pitchers is pretty rare.
The "swing players" you refer to would be called a two way player in baseball.  In college baseball it is much more common.  The players may also DH for them selves as they pitch (a quirky NCAA rule).  The award for that specialty player is called the John Olerud Award.
In most sports, the lower (or younger) levels are dominated on mostly by talent.  Once the highest levels are reached, most players are very talented and the players that work the hardest and train the hardest will be the most successful.  If is hard to out work and out train two different groups of players at the same time.
One last comment, position players will come in to pitch in blow out games some times.  This is usually just to save the innings and pitch count number for the relief pitchers in the bullpen over the course of the season.  These guys are not seen as two way players, even if they pitched in college or high school.  They are simply position players pitching in blow outs.
A position player getting the win in extra innings
Comment: So putting Nick Swisher on the mound in this situation might have been a good idea? (The article is mine on Bleacher Report). http://bleacherreport.com/articles/376438-new-york-yankees-calling-nick-swisher
Comment: @TomAu I would say it is not a good decision, especially in the American League.  This would eliminate the DH.  In the National League it would make more sense.  In that situation however, the score is tied.  You have to go to the bullpen or leave the starter in.  There cannot be a reasonable expectation that Nick Swisher is going to come in a do any better at a position that he doesn't play over some one that does.
Comment: My idea was that if you want to deliberately walk the next batter, let the outfielder do it, because he can do as well as the starter (after taking up 8 warm up pitches to rest the pitcher). In an intentional walk, the batter doesn't even get an "at bat."
Comment: @TomAu Also, in your article you mention having Swisher throw the warm up pitches and then go 1-0 to the hitter.  Putting the pitcher back in is not allowed until one at bat is completed by the pitcher.
Comment: So an intentional walk wouldn't count as such? Or did you mean plate appearance?
Comment: @TomAu Plate Appearance.  It would count.  Sure anyone could intentionally walk a hitter.  I don't see how sending a pitcher to a position for four pitches would help him.  There would be a 12 pitch break with warm up pitches, but the catcher can walk to the mound, followed by a pitching coach.  If he needs time, he can buy time pretty easily.  Also four pitches lightly thrown wont affect the total number of pitches a pitcher can be expected to throw in a game.
Answer: This can happen - Whitey Herzog used to do this every so often in the 1980s to stash a pitcher while some specialist pitched to a batter or so.
It isn't prevalent because:

It puts a bad fielder in the field and a worse hitter at bat for your
original outfielder.
It burns up a relief pitcher once you switch
back.  And there just aren't that many bench players on a team to do
this very often per game.
Most often when your pitcher needs replacing, he's done for the day.
If a regular position player can pitch, he becomes a full-time pitcher. Aside from novelty appearances, a non pitcher pitching gets blown out.


joomla 1.0 administrator cant login due to invalid session

Question: I am using joomla 1.0 for developing a website,I cant login at backend (login only at backend).it shows the error messages as follows
first it shows the following errors in administrator/index.php
first stage
Warning: session_start() [function.session-start]: open(/hsphere/local/home/mdlglobe/mdlglobe.com/sessions\sess_972fdf60f45c091916639d797a8c7458, O_RDWR) failed: No such file or directory (2) in E:\EasyPHP 3.0\www\mdlglobe\administrator\index.php on line 111

Warning: session_write_close() [function.session-write-close]: open(/hsphere/local/home/mdlglobe/mdlglobe.com/sessions\sess_972fdf60f45c091916639d797a8c7458, O_RDWR) failed: No such file or directory (2) in E:\EasyPHP 3.0\www\mdlglobe\administrator\index.php on line 150

Warning: session_write_close() [function.session-write-close]: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/hsphere/local/home/mdlglobe/mdlglobe.com/sessions) in E:\EasyPHP 3.0\www\mdlglobe\administrator\index.php on line 150

then it redirect to index2.php,and shows
second stage
Warning: session_start() [function.session-start]: open(/hsphere/local/home/mdlglobe/mdlglobe.com/sessions\sess_a1d4a8fb0750e8d835ed4ff59cc4e707, O_RDWR) failed: No such file or directory (2) in E:\EasyPHP 3.0\www\mdlglobe\administrator\index2.php on line 37

after that it redirect to the index page itself and show
third stage
Invalid Session
 login failed

I have searched lot and they says the error occurs due to session.save_path
Please anyone tell me how this session.save_path edited in easyphp and solve this problem .I am facing big issues due to this
As one answer says i have changed session.save_path="E:/easyphp/temp/" But it not effected at all..
Please help
Comment: Why on earth would you use Joomla 1.0 for anything? You should seriously consider using something that is being actively developed. Joomla 2.5 released a couple days ago, that would be a good start.
Comment: because my client stricltly need it
Answer: Check session.save_path in php.ini, it should be like
session.save_path = "C:\php\temp"

and DIR path should be valid
Comment: Thanks for your answer.  You mean set the session.save_path to the temp folder where the easyphp installed.I tried but no change for the errors
Answer: Finaly I have Solved this issue,by done the following
I changed the session.save_path in php.ini
session.save_path = "absolute path to the temp folder"

Also I have changed the session path in .htaccess file in the sessions folder of joomla 1.0
Joomla 1.0 is using differnt method to save session variables than other joomla versions


bash script to kill php process older then an hour

Question: I have the following:
kill -9 `ps aux | grep php | awk '$9 !~ /[0-9]:[0-9]/' | awk '{print $2}'`

What it does is kill process that have been left abandoned by fcgid and kills them to free RAM. I want to run this as a cron every hour but would like to kill processes older then an hour. I'm just not sure how to modified the script to do that.
Comment: shouldn't u change your php timeout to something smaller in your php.ini file?
Comment: It's not that. I've got it tuned and setup in the config file but sometimes the processes just get lost and sit there for days/weeks taking up ram. It's a known glitch.
Comment: ahhh ok, yea i guess it saves going in and doing it manually ha ha :)
Answer: Try the following bash code  :
for i in $(pidof php); do
    pidtime=$(stat -c '%Y' /proc/$i)
    now=$(date +%s)
    ((now - pidtime >= 3600)) && { kill $i; sleep 1; kill &>/dev/null -9 $i; }
done

and the crontab :
crontab -e
0 * * * * /path/to/the/script.bash

Answer: Solved with:
/bin/ps -Ao"command,pid,ppid"|/bin/grep ' 1$'|/bin/grep /php|/bin/awk '{ print $2; }'|/usr/bin/xargs --no-run-if-empty kill -9

Comment: Do I replace kill with sigterm by using -15? Is this better even if the processes are Orphaned?


PDF of the minimum of a geometric random variable and a constant

Question: I have $X \sim Geo(p)$, such that
$$p(x) = (1-p)^{k-1}p, \ \ x = 1,2,3, \ldots$$
and Y is a constant random variable which assumes the value of the constant integer $t$, such that
$$P(Y=t) = 1, \ \ t>0$$
And now I am considering a random variable $Z$, where
$$Z = min(X, Y)$$
I am attempting to compute the PDF of Z, and have followed something similar to the answer posted here i.e.
$\begin{align}
f_Z(z) & = \frac{\mathrm d\;}{\mathrm d z} \Bbb P(\min(X,Y)\leq z)
\\[1ex] & = \frac{\mathrm d\;}{\mathrm d z} (1 - \Bbb P(\min(X,Y)\gt z))
\\[1ex] & =  -\frac{\mathrm d\;}{\mathrm d z}\Big( \Bbb P(X>z)\,\Bbb P(Y>z) \Big)
\\[1ex] & =  -\frac{\mathrm d\;}{\mathrm d z} \Big(\big(1-F_X(z)\big)\big(1-F_Y(z)\big)\Big)
\\[1ex] & = f_X(z)\Big(1-F_Y(z)\Big) + \Big(1-F_X(z)\Big)f_Y(z)
\\[1ex] & = (1-p)^{z-1}p\Big(1 - 1_{z \geq t}\Big) - (1-p)^z1_{z=t}
\end{align}$
Am I on the right path? I kind of expected a more compact kind of expression, one I could relate to the exponential family?
Comment: You seem to be on the right track if the problem specifies that $X$ and $Y$ are independent. If not, you might have to deal with their joint PDF.
Comment: There is no PDF anywhere. And since you are assuming independence of $X,Y$, you should mention that in your post.
Answer:
Proposition.
  Let $X$ be a random variable with cumulative distribution function $F_X$ (i.e.,
  $$
F_X(x)
= P(X \leq x)
$$
  for all $x \in \mathbb{R}$, and let $t \in \mathbb{R}$ be a constant.
  Define $Z = \min\{X, t\}$.
  Then the cumulative distribution function $F_Z$ of $Z$ is
  $$
F_Z(z)
= \begin{cases}
F_X(z) & \text{if $z < t$} \\
1 & \text{if $z \geq t$}
\end{cases}
$$
  for all $z \in \mathbb{R}$.

Proof.
Let $Y$ be a constant random variable with value $t$.
Note that $Y$ is necessarily independent of $X$ and that
$$
P(Y > z)
= \mathbf{1}_{(-\infty, t)}(z)
= \begin{cases}
1 & \text{if $z < t$,} \\
0 & \text{if $z \geq t$.}
\end{cases}
$$
Then we have
$$
\begin{aligned}
F_Z(z)
&= P(Z \leq z) \\
&= 1 - P(Z > z) \\
&= 1 - P(\min\{X, Y\} > z) \\
&= 1 - P(X > z, Y > z) \\
&= 1 - P(X > z) P(Y > z) \\
&= 1 - (1 - F_X(z)) \mathbf{1}_{(-\infty, t)}(z) \\
&= \begin{cases}
F_X(z) & \text{if $z < t$,} \\
1 & \text{if $z \geq t$.}
\end{cases}
\end{aligned}
$$

You can use this Proposition to figure out the probability mass function (not the probability density function!) of $Z = \min\{X, Y\}$ where $X \sim \operatorname{Geometric}(p)$ and $Y = t$ almost surely, as in your question.
More concretely, your random variable $Z$ will be a discrete random variable supported on $\{1, 2, \ldots, t\}$ satisfying
$$
\begin{aligned}
P(Z = z)
&= P(Z \leq z) - P(Z \leq z - 1) \\
&= F_Z(z) - F_Z(z - 1)
\end{aligned}
$$
for all $z \in \{1, 2, \ldots, t\}$.
The cumulative distribution function needed for the above computation can be determined using the Proposition above.


Local finite counting measure and local finite subset

Question: Please correct me if I am not correct. On a Borel sigma algebra on a topological space $S$,

a locally finite measure is defined as a measure for which every
point of the measure space has a open neighbourhood of finite
measure.
A local finite subset is defined as a subset with which the
intersection of every compact subset is a finite set. (I think it is a pure topological concept?)

I wonder

why is it that every locally finite counting measure on $S$ is of
the form $\sum_{x\in \Lambda}\delta_x$ where $\Lambda$ is a locally
finite subset of $S$?
For $\sum_{x\in \Lambda}$ to be well-defined, is $\Lambda$
required to be countable, i.e. to avoid being uncountable?
Is the converse true, i.e. is it true that a counting measure on $S$
is locally finite if and only if it is of the form $\sum_{x\in
\Lambda}\delta_x$ where $\Lambda$ is a locally finite subset of $S$?
In general, is a counting measure on a measurable space $X$ defined
as $\mu(B) := \#\{A \cap B\}$ for some fixed and arbitrary subset $A$ of $X$? This is how I infer from "locally finite counting measure", but Wikipedia says a counting measure is defined as the cardinality function of measurable subsets.
Is a measure counting measure if and only if  it is of the form $\sum_{x\in
    A}\delta_x$ where $A$ is a fixed and arbitrary subset of $X$? (Similar to a previous question, does $A$ need to be countable for $\sum_{x\in
    A}$ to be well-defined?)

Thanks and regards!
Comment: The definition of "counting measure" used here is more general than Wikipedia's. The following conditions on a measure $m$ on a space $X$ are equivalent: (1) for all $x \in X$ one has $m(\{x\}) \in \{0,1\}$, (2) there is $S \subseteq X$ satisfying $m(E) = \#(E \cap S)$ for all $E \subseteq X$, where $\#$ is the cardinality (nonnegative integer or $\infty$). (To see (1) implies (2), take $S = \{x \in X: m(\{x\}) = 1\}$.) A counting measure is a measure satisfying (1) or (2), such a measure is finite iff the set $S$ in (2) is finite, and locally finite iff the set $S$ in (2) is locally finite.
Comment: @leslietownes: Thanks! That is clearer! Does it need any other condition for "such a measure is locally finite iff the set S in (2) is locally finite"?
Answer:
If $\mu$ is a locally finite counting measure then every compact set has finite measure as we can cover the compact set with finitely many open sets of finite measure. Thus, $\Lambda\cap K$ must be finite for all compact $K$.
$\sum_{x\in\Lambda}\delta_x$ it is always well-defined as $\sup\sum_{x\in F}\delta_x$, where $F$ ranges over all finite subsets of $\Lambda$. This definition of sum just works for nonnegative terms. In general, we consider the the net of finite subsets of the index set ordered by inclusion then the sum is defined as the limit of the net.
It is true if we assume that the space is locally compact since any precompact neighbourhood would have finite measure, hence $\mu$ would be locally finite measure.
Comment: +1 Thanks! Is the sume of a family of real numbers $\{ x_a: a \in A \}$ also defined via $\sup$ over all finite subcollection of the family?
Comment: I'll edit my post to include a more general version of the sum.
Comment: Thanks! I was wondering if local compactness is necessary for the converse to be true?
Answer: I am adding this as an answer because it is too large to fit as a comment.  But mostly its purpose is to clarify one of my comments (and answer a reply to that comment).
One of the questions raised by the original post concerns the definition of "counting measure" that is implicitly being used in the statements linked above.
My guess is that the definition of "counting measure" used there is equivalent to the following:

A measure $m$ on a measure space $(X, \mathcal{B})$ is said to be a counting measure if and only if there is some $S \subseteq X$ satisfying
  $$
m(E) = \#(E \cap S), \qquad E \in \mathcal{B},
$$
  where $\#$ denotes the set cardinality (either a nonnegative integer or $\infty$).

In my comment on the original question, I stated that this condition was equivalent to the condition that $m(\{x\}) \in \{0,1\}$ for all $x \in X$, but on further thought I realized that this is not true.  For one thing, there is nothing in the above definition which requires or implies that the singleton subsets of $X$ are measurable.  If we assume this, the above definition implies that $m(\{x\}) \in \{0,1\}$ for all $x$ in $X$, but there are measures satisfying this weaker condition which are not counting measures in the above sense.  (For example, fix any uncountable $X$, take $\mathcal{B}$ to be the power set of $X$, fix $p \in X$, and take the measure $m$ to be $\delta_p + \nu$, where $\delta_p$ is the Dirac mass at $p$ and $\nu$ is the measure given by declaring that $\nu(E) = 0$ if $E$ is countable and $\nu(E) = \infty$ otherwise.)  One can, of course, add additional hypotheses to this weaker condition to make it equivalent to the above definition.  But I think the above definition is more fundamental in capturing what a "counting measure" ought to be.
In any case, it is clear that if $m$ is a counting measure in the above sense, then the set $S$ appearing in the definition is uniquely determined by $m$: it must be $\{x \in X: m(\{x\}) = 1\}$.  It is also clear, straight from the definitions, that a counting measure $m$ is finite if and only if its set $S$ is finite.  This is immediate from the equality $m(X) = \#(S)$.
Now suppose that $X$ is a second countable, locally compact Hausdorff space, and that $\mathcal{B}$ is the Borel $\sigma$-algebra of $X$.  Suppose $m$ is a counting measure on $X$, and let $S = \{x \in X: m(\{x\}) = 1\}$.  I claim that the measure $m$ is locally finite (in the sense given in the OP) if and only if the set $S$ is locally finite (in the sense given in the OP).
This is true, but not immediately obvious.  What is immediately obvious is that the measure $m$ is locally finite if and only if the set $S$ has the following property:

For all $x \in X$, there is an open subset $U$ of $X$ containing $x$ with the property that $U \cap S$ is finite.

Indeed, since $m(U)$ is finite if and only if $U \cap S$ is finite, this is a direct transcription of "every point of the space has an open neighborhood of finite measure".  But "$S$ is locally finite", a priori, means something slightly different.  So we need to prove the equivalence of the following properties of a subset $S$ of $X$:

For all $x \in X$, there is an open subset $U$ of $X$ containing $x$ with the property that $U \cap S$ is finite.
For all compact $K \subseteq X$, one has that $K \cap S$ is finite.

If condition (2) fails then we can choose a compact $K \subseteq X$ and an infinite sequence $(k_n)_{n=1}^{\infty}$ of distinct points of $K \cap S$.  Since $X$ is second countable, we know that $K$ is sequentially compact, and so we may assume (by passing to a subsequence as needed) that $(k_n)_{n=1}^{\infty}$ is convergent to some $p \in X$.  But then, for any open subset $U$ of $X$ containing $p$, there is some positive integer $N$ with the property that the infinite set $\{k_n: n \geq N\}$ is contained in $U$.  So $U \cap S$ is infinite for every open subset $U$ of $X$ containing $p$, and condition (1) fails.
Conversely, if condition (1) fails there is some $p \in X$ with the property that every open subset $U$ of $X$ containing $p$ has the property that $U \cap S$ is infinite.  Since $X$ is locally compact, we can find an open subset $U$ of $X$ containing $p$ with the property that there is a compact subset $K$ of $X$ satisfying $K \supseteq U$.  But then $K \cap S$ is infinite (since it has the infinite subset $U \cap S$) and the second condition fails.
This proves that conditions (1) and (2) are indeed equivalent.  So, assuming those topological hypotheses on $X$, one does know that a counting measure $m$ on $(X, \mathcal{B})$ is locally finite if and only if its set $S$ is locally finite.


Evaluting a limit of integral

Question: I am working on the following problem
$$\lim_{n\rightarrow\infty} \sqrt{n}2^n\int_0^\infty x^n(1+x^2)^{-n} \ dx$$
I can rewrite the integral as $$\lim_{n\rightarrow\infty}\int_0^\infty \sqrt{n}\left(\frac{2x}{1+x^2}\right)^n dx$$
Next I want to use the Gaussian integral to evaluate this. I tried a substution of $u=\sqrt{n}x$ but didnt work well. Any other suggestions?
Comment: You could try a trig sub $x=\tan u$.
Answer: Hoping that I did not make any mistake :  for $n>1$, $$\int_0^\infty x^n(1+x^2)^{-n} \ dx=\frac{\sqrt{\pi } 2^{-n} \Gamma \left(\frac{n-1}{2}\right)}{\Gamma
   \left(\frac{n}{2}\right)}$$ So, $$A= \sqrt{n}2^n\int_0^\infty x^n(1+x^2)^{-n} \ dx=\sqrt{\pi n}\frac{ \Gamma \left(\frac{n-1}{2}\right)}{\Gamma
   \left(\frac{n}{2}\right)}$$ For large values of $n$, asymptotic expansion of the $\Gamma$ function gives $$A=\sqrt{2 \pi }+\frac{3 \sqrt{\frac{\pi }{2}}}{2 n}+\frac{25 \sqrt{\frac{\pi }{2}}}{16
   n^2}+O\left(\left(\frac{1}{n}\right)^{5/2}\right)$$

Evaluting a limit of integral


Will this recurrence yield $(4,2,0)$?

Question: Consider the recurrence
$$(a,b,c)\mapsto \left(\frac{3a+4b}{5}, \frac{4a-3b}{5}, c\right)$$
and suppose that we start with $(2,3,2)$, and allow swapping positions before applying the recurrence again.
If we start with $(2,3,2)$, will we  be able to obtain $(4,2,0)$?
Comment: @Arturo Magidin Thanks for the edit.
Answer: Hint: Let $f(A,B,C)=A^2+B^2+C^2$. Note that the transformations leave $f$ invariant.  You can interpret this geometrically (the distance to the origin does not change), or purely algebraically.
Comment: @MaoYiyi: The point is that each idea that you learn in solving problems adds to **your** knowledge.
Comment: You might recognize that your transformation is a rotation by $\arccos(\frac{4}{5})$ followed by a reflection in $y=x$. Thus, the distance to $O$ never change....
Comment: I sort of see how it would be invariant, but I am not getting the idea of $f(A,B,C) = A^2+B^2+C^2$.
Comment: Let $T$ be anyone of your allowed transformations (the main one, or any swap). Let $(A_1,B_1,C_1)=T(A,B,C)$. You can check easily that $A_1^2+B_1^2+C_1^2=A^2+B^2+C^2$. This is trivial if $T$ is a swap. For the main transformation, it is a calculation, since $\left(\frac{3A+4B}{5}\right)^2+\left(\frac{4A-3B}{5}\right)^2+C^2=A^2+B^2+C^2$. Originally, your point is on a sphere centre the origin, radius $\sqrt{17}$, and under the transformations it **stays** on that sphere. But $(4,2,0)$ is not on that sphere!
Comment: @AndréNicolas I bow to your knowledge.

Will this recurrence yield $(4,2,0)$?


Cisco Catalyst 2960 Switches - Can I reverse the air flow?

Question: I have some equipment that will be moved to a new datacenter soon.
At the current datacenter, the switches are mounted in the back of the racks so the air flow for the switches is reverse in comparison to the rest of the equipment on the racks.
Since on the new datacenter they strictly follow the cold/hot aisle setup, I have been asked to move the switches on the front of the racks, something which entails a lot more downtime and I wish to avoid, if possible.
The switches are standard Cisco Catalyst 2960(G).
Is it possible to reverse the airflow of the switches so that can still be left on the back of the racks?
Do the fans and IOS support something like that, or if I mount the fans in reverse on the chassis, would that be ok?
Comment: Cisco switches are usually side to side airflow wise with hot air exiting from the left to allow more room at the front for cable access. Using them in a hot aisle / cold isle data centre usually requires a cabinet with ducts and possibly extra fans to direct the air to/from the isles. Filler panels in racks beside them can work as well.
Answer: Cisco 2960 switches pull in cool air from the sides and exhaust to the rear.
Depth-wise they are 1/3 to 1/2 rack-depth (depending on exact model switch and rack).
This leaves you very few options. If you mount them unmodified backside of the rack just about the entire switch is in the hot zone. That will only be OK if you have cold airflow running on the side of the rack so the switch can get sufficient cooling. Unfortunately this is usually not the case in a strict hot/cold isle setup.
When you mount on the front you will have to run most server-cabling from the back to the front (if your servers have most wiring on the back) which makes for messy cabling.
Reversing the fans is maybe possible. I have no idea if this is electrically feasible and how the firmware would react on a 2960. In most switches that I took apart the fans plug directly into a motherboard connector and are not reversible.
Then you could mount them, ports facing backwards, in the front of the rack. This makes cabling awkward because you will have to reach quite a long way into the rack to reach the RJ45's. It might be OK if you only need to (re-)patch them on very rare occasions. Be prepared to leave 1 U above and below a switch unused, just to give yourself some working room.
Precisely because of these issues nowadays we do it completely different in our bigger server-rooms. We avoid the problem altogether:
 - For each 42U rack we reserve the lower 30U for servers. (Not higher, to difficult to mount/unmount them.)
 - Next 6U is for switches: ports at the front.
On the side of each rack is filler plate, except at the U's with switches so there is some cold airflow to the side-intakes on the switches.
 - Top 6U is for patch-panels: Also ports at the front.
From the back of the patch-panels we just run 8 UTP cables (CAT7) to the back of each of the 30 U's. (Alternating 8 left-side, 8 right-side). That is 30x8= 240 ports which fits in 5x 48 port patch-panels. This cabling is a one-time fixed installation with all the cables made exactly to length and neatly placed in cable-guides/trays in the rack.
The top-most patch-panel is reserved for backbone-cabling to other racks (24x OM3 or OM4 fiber). We have another fiber patchpanel (in some racks 2) backside mounted in the topmost slot(s) for SAN cabling.
We simply hook up all UTP ports (used or not) on the back of the server to the corresponding block of patch-panel ports. (In the rare cases a server needs more than 8 UTP connections we take them from the U above it. Typically such servers are more than 1 U anyway.)
All UTP patching is done front-side. Fiber-SAN stays at the back of the rack.
This way cable management becomes easy: You don't have to thread new cable though the rack every time you change something. The cabling (except for the short patches in the front) is static and can be made exactly to length. There is no over-length to stuff in a corner inside the rack itself. That also helps airflow.
It is so easy you can talk anybody (liek someone from local FCM on-site who has access to the server-room) through a re-wiring job on the phone if necessary:
Find rack number 5. Big yellow number on the front door. Open that front-door. About chest high and higher you'll see a bunch of cables in several colors. On the left and right there are numbers on the sides of the equipment. They go from 31 at the lowest piece of equipment that has cables in it, all the way up to 42 at the top. Find number 33 on the side, look for the cable in port 21 (should be a blue cable). Pull it loose (press on the little lip on the plug to unlock it) and plug it back in at height 35 in port number 17. Thank you for your help, don't forget to close the door of the rack on your way out.
Initial cost of setting up a rack is higher, but you recoup that real quickly in labor and downtime when you need to swap servers later on.
Of course that totally depends on how many changes you expect. In our case about 1 server-replacement per 6 weeks in each rack and we deal with about 300 racks in 35 server-rooms on 21 locations all over Europe.
It really pays of in the long term if you don't need to physically go over to each site for small changes.
I get service-techs from HP, DELL, etc. which I just direct over the phone where to place the new server. As soon as the cables are in and I can see the ILO or DRAC on the LAN I can take it from there.
Comment: A photo would be helpful.
Comment: @ewwhite Sorry: Photos are strictly forbidden on our sites. If I have to make some for documentation purposes there is a security guy with me to verify I only photograph what's needed and every photo is digitally watermarked (by security) before I can take the SD card with me. Security is no joke here. (Military contracts, also banks and insurance companies.) I'll see if I can dig up some samples. Rittal should have some. They demoed something similar on Cebit a few years back.
Comment: Great post! I was designing the racks from scratch to accommodate for the switches positions on the front (since apparently I cannot reverse the airflow of current equipment and I don't want to do 'weird' stuff) and I came up pretty much with what you suggested :) So it gives me comfort to see that my design is already proven in production. The only thing I dislike is the messy cabling from the front of the rack to the back. But as you said this cabling will be done once so I hope there won't be any problems afterwards. Thanks!
Comment: @Cha0s I absolutely hate messy cabling (my OCD talking I guess) but in our racks only the loose patch-cables on the front are somewhat messy. The internal cables (from back of patch-panel to back of servers) are neatly bundled (1 bundle of 8 per U) and tied down except for the last 40" (1 meter) from rack-post to the back of the server.  (1 meter is long enough for a cable-arm.) The ones that are not used are left hanging down (or pushed under the rack at teh very bottom), tied with velcro straps.
Comment: Yeap, that's what I am preparing too. Bundles of 8 cables per U will already be installed for all Us so when servers come and go the cabling will stay the same and will support pretty much any configuration needed with so many available cables per server! The only thing I know I will hate when the time comes, is the power cables for each server. Some server models (even of the same brand) have the PSUs on the left and some on the right :(
Comment: @Cha0s Don't get me started on power-cabling :-) Worst thing is having 2 powerfeeds (left and right, UPS and generator-fed) in the rack and having to cross the rack twice because of the cable-arm. (Left feed to right-mounted cable-arm and at the back of the server from the cable-arm across to the left PSU.) Most vendors these days are smart enough to have dual PSU's next to each so you can attach the cable-arm on the same side. But you still need to cross the rack once if you have separated left-right powerfeeds.
Answer: With the strict hot/cold setup it seems like even if the airflow could be reversed leaving the switches at the back of the racks would have a negative impact since they would be sucking in air from the hot aisle in the datacenter.
Based on the diagrams of the switch that I can see online it is not a full depth switch, so when mounted on the back side of the rack it would be nearly impossible for it to suck cool air in the way a server would.  The hot aisle in a datacenter can be very warm and I have had issues in the past with switches that have been located too close to the hot outflow vents overheating.
So even if it is possible to reverse the flow on the fans it could still have a negative impact on performance.
Comment: You are right, I didn't think of that.


Apache mod_expires question

Question: I'm really confused by all that caching stuff. I'm trying to setup mod_expires to reduce the number of HTTP Requests from my website to the server.
I did well so far, I installed mod_expires and wrote a little .conf file from the instructions on http://httpd.apache.org/docs/2.0/mod/mod_expires.html.
Now, for instance, all my .png, .gif, .jpeg files have a Cache-Control header. My expected result was, that the browser won't do any GET Request within the time period (given from the Cache-Control value). But it does, every single file fires a request and receives HTTP 304 not Modified.
That is the wrong behavior isn't it ? It should load that files from the internal cache.
One thing I don't understand is, that the browser sends a Response header: Cache-Control: max-age=0. Should it be like that?
Here is an complete example Request + Response headers for a single .png file:
Request
Host             dev-mgg.localdomain
User-Agent     Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:188.8.131.52) Gecko/20100722     Firefox/3.6.8
Accept         image/png,image/*;q=0.8,*/*;q=0.5
Accept-Language  de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding  gzip,deflate
Accept-Charset   ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive     115
Connection     keep-alive
Referer       http://dev-mgg.localdomain/css/global/icons.css?18224
Cookie         IR_SQLPwdStore=; IR_SQLUser=sysadm
If-Modified-Since   Thu, 24 Jul 2008 06:24:11 GMT
If-None-Match   "4010127-3c4-452bf1aefd8c0"
Cache-Control   max-age=0

Response
Date         Mon, 02 Aug 2010 14:00:28 GMT
Server     Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny8 with Suhosin-Patch mod_perl/2.0.4     Perl/v5.10.0
Connection   Keep-Alive
Keep-Alive   timeout=15, max=59
Etag         "4010127-3c4-452bf1aefd8c0"
Expires   Mon, 02 Aug 2010 14:04:28 GMT
Cache-Control   max-age=240

Answer: and welcome to the wonderful world of web (servers|browsers)!
How web browsers ultimately behave, that's almost up to the web browser. Some browsers will not request already cached images at all, some will. Some will request them only if tuned for private browsing or something similar.
And if you have a dynamic web page, most likely your browser will still try to load the static images, too, even if the browser would have been told earlier that it does not need to come back for the images. In those cases the browser will try to request for an image, and the server will respond back 304 Not Modified.
But don't worry, that is the only response your browser will get back. No more data is transferred for that particular request, so from the resource side of view that is a very light thing.
Sometimes it helps if you serve the images from a different domain name (say, static.yourdomain.com instead of www.yourdomain.com), but rest assured, the browsers are like Terminator 2, they'll be back sooner than you thought. A simple Ctrl+F5 or Ctrl+Shift+R is enough to force your typical browser to refresh EVERYTHING.
(Please correct me if I'm wrong.)
Comment: Hi there, thanks for the respond. Tho your answer does not really help me at all. Most of the things I already mentioned, and I'm not fairly new to this topic. It's just about the caching, I ran tests on Chrome and Firefox, both showed the same behavior, just returning 304. I got a lot of pictures and each `HTTP request` is so much overhead, I really want to avoid those for static images. So you're saying one can't reach that with headers at all? What about the strange `request header`, which contains the `cache-control: max-age 0` ? I also added the `private` flag, no success.
Comment: It needs to be cache-control: public if you want it to be stored. Private is never cached. You may want to increase the max-age, that can be overridden with mod_headers and its unset/set functions. Still I claim you will see visits from your browsers. Good luck in your journey to caching :)
Comment: whoopa, I meant `Public`. I added that into the `cache-control` header with `mod_headers`. But it also does show no effect on chrome/firefox. I'm really disappointed here, I guess I'll try to use `ANT` to setup the headers for me, but I'm afraid it will not do any magic that I'm not doing right now.
Answer: The Cache-Control max-age=240 you set in server with mod_expires is a little bit low to make tests, it tells browser to keeps stuff in cache for only 4 minutes (240 seconds).
So the 1st thing you could do is to increase such value to something longer like a week so you can do test without running.
#Set caching on image files for 11 months
<filesMatch "\.(ico|gif|jpg|png)$">
  ExpiresActive On
  ExpiresDefault "access plus 1 week"
  Header append Cache-Control "public"
</filesMatch>

Anyway your test was performed after you hit thebrowser relaod page button. Once you do that that browser sends a request to with Cache-Control max-age=0 telling server to give it back the entire resource again.
You should test if caching works NOT by forcing a page relaod but simply:

by navigating to another website and then come back to the test page.
Or you could close the browser and than open it again on the same
page.

Doing the test I listed above you should see browser not asking for the same respurce again because server told browser it must keep the resource in cache and take it out form there for 1 week.

Apache mod_expires question


Substitution Nonlinear Differential Equation Problem

Question: So my problem was to solve the differential equation $y^2y'' = y'$.
Let $u = y'$. Therefore $y^2 u' = u$ and integral $du = \int 1/y^2$.
Case 1: $c=0, y_1 = \int of 1/y^2 = -1/y + c_1$;
Case 2: $c =a^2>0$, $y_2 = \int {1\over y^2+a^2}$, $dy = {1 \over a} \arctan\left(\frac{y}{a}\right) + c_2$
Case 3: $c =-a^2<0$, $y' = {1\over y^2-a^2}\,dy = {1\over (y-a)(y+a)}$
      then $y = \frac{-1}{2a}  [\ln|y+a|-\ln|y-a|] + c_3$
       so $y_3 = \frac{-1}{2a} \ln\left|\frac{x+a}{x-a}\right| + c_3$
Does this seem like a reasonable approach to encasing all the solutions?
Comment: Hi Disha Wan ! You introduces a the constant $c$ which is not defined before being used. You write :  integral $du = \int 1/y^2$ which is non-sens since the non consistancy of notation (integration with respect to what variable ? . $d?$ missing into the integral).
Answer: $$y^2y''=y'$$
$y=0$ is a trivial solution.
Case $y\neq 0$ :
$$y''=\frac{y'}{y^2}$$
After integration :
$$y'=-\frac{1}{y}+c_1$$
With $y'=\frac{dy}{dx}$
$$dx=\frac{y}{c_1y-1}dy$$
After integration :
$$x=\frac{1}{c_1^2}(c_1y+\ln|1-c_1y|)+c_2$$
If necessary, the inverse function $y(x)$ can be expressed thanks to the LambertW function.
$$e^{c_1y}|1-c_1y|=e{c_1^2(x-c_2)}$$
$$(c_1y-1)e^{c_1y-1}=\pm e^{c_1^2(x-c_2)-1}$$
$$c_1y-1=W\left(\pm e^{c_1^2(x-c_2)-1}  \right)$$
$W(X)$ is the LambertW function, where $X=\pm e^{c_1^2(x-c_2)-1}$
$$y(x)=\frac{W\left(\pm e^{c_1^2(x-c_2)-1}  \right)+1}{c_1}$$
Comment: Aren't there two cases when y is not equal to zero?
Comment: Also, how can this be expressed in terms of y(x)?
Comment: Do you know the LambertW function? This is required to express $y(x)$
Comment: Yes, is this the only possible way to express y(x)?
Comment: Sure ! It is. But depending on the boundary conditions (missing in the wording of the question) some particular values of $c_1$ and $c_2$ may lead to simplification of the resulting function in particular cases.


Change third-party application name in Django

Question: I use third-party application (django-flatblocks) in my Django project. How can i change the name of the application in admin interface (grappelli)? I need russian name. I already tried to create localization files (.po.mo) and it is work fine in some parts of admin interface, but in breadcrumbs do not. I think grappelli does not use translation in some templates and the best way to resolve the problem is to replace django-flatblocks verbose_name in apps.py "on the fly". Can i do it somehow?
Answer: Found this in the official documentation did. The solution is so simple: For application users
To quote the Manual:

If you're using "Rock 'n' roll" in a project called anthology, but you
  want it to show up as "Jazz Manouche" instead, you can provide your
  own configuration:

<code># anthology/apps.py

from rock_n_roll.apps import RockNRollConfig

class JazzManoucheConfig(RockNRollConfig):
    verbose_name = "Jazz Manouche"

# anthology/settings.py

INSTALLED_APPS = [
    'anthology.apps.JazzManoucheConfig',
    # ...
]
</code>
Comment: what if the 3rd-party app does not have an `apps.py` file / config?
Comment: Doesn't matter about the name of the file, as per the link, somewhere they will subclass AppConfig to create their own config, just find that Which does that: https://docs.djangoproject.com/en/2.2/ref/applications/#for-application-authors


Silverlight Prism Module Not Ready

Question: I'm building a Silverlight 4.0 application with Prism (a.k.a. Composite Application Guidance).  I have two modules, both defined in my ModuleCatalog.xaml as WhenAvailable.  My Application_OnStart instantiates my Bootstrapper and invokes it's Run() method.  Well after my application is started and up and running (in fact, the user has to click a button in the UI), I then attempt to load the modules:
<code>foreach (ModuleInfo mi in moduleCatalog.Modules)
    ...
    Type moduleType = Type.GetType(mi.ModuleType); // moduleType ends up null!
</code>
Sometimes, moduleType ends up null.  I've verified that when I encounter the null, the ModuleInfo's State is LoadingTypes not ReadyForInitialization.  I assume this means it's still downloading the separate *.xap files for my modules and bringing their types into the application domain.
So what can I do?  I'd happily block if I knew there was some event I could listen to to know they're finally all loaded.
Answer: If you are going to use Prism, you should not bypass it and create your modules yourself. That is not the way Prism is supposed to work. Prism does not provide an event for load completion as that is not something you should need to do.
Simple case:
If you define a module catalogue then all those modules will be loaded progressively, so no need to load any manually in that simple case. You can create a start-up module in your root Silverlight app with a few module dependencies and that will be enough to get the first page visible while to rest of the app loads.
More info needed:
I can't tell what you are actually trying to accomplish from the above snippet, so more information would help, but you should be using Unity to resolve interfaces and never Type.GetType() directly. Your generally should not need to resolve a module itself and there are also methods for triggering load-on-demand loading in Prism (don't have them handy at the moment... will update this).
Thanks:
Your have accidentally provided a clue to the answer to another question I asked in Stack Overflow so thanks for that.

Silverlight Prism Module Not Ready


notify user account creation?

Question: I can't seem to find documentation for notifying a user via email after their account has been created by a script.
$user = \Drupal\user\Entity\User::create();

$user->setPassword('xxx');
$user->enforceIsNew();
$user->setEmail('xxx+'.time().'@gmail.com');
$user->setUsername('xxx'.time());

$user->set('init', 'email');
$user->set('langcode', $language);
$user->set('preferred_langcode', $language);
$user->set('preferred_admin_langcode', $language);
$user->activate();

//$user->notify()? something?

$result = $user->save();

Comment: This is set under `/admin/config/people/accounts`.
Answer: You can find the configuration on admin in the /admin/config/people/accounts but if you want to notify the user programmatically without taking care of what is the config you can use _user_mail_notify function.
_user_mail_notify documentation

notify user account creation?


How to select all text boxes with a specific tag

Question: Using c# 6 windows forms, I want to choose all textBoxes with the tag "txt".
I have confirm that there are several of them with the tag "txt". Then, I want to clear the text. But the following code is not choosing any.
<code>this.Controls.OfType<TextBox>()
             .Where(textBox => textBox.Tag.ToString() == "txt").ToList()
             .ForEach(textBox => textBox.Clear());
</code>
Comment: Maybe they are not direct child of `Form` and you placed them in a some other container controls. - Also be aware of probable `NullReferenceException` here `textBox.Tag.ToString()`.
Comment: what type of control is `this`?
Comment: I have this code for the ones in GroupBoxes -> foreach (var textBox in Controls.OfType().Where(textBox => textBox.Tag?.ToString() == "txt").SelectMany(groupBox => groupBox.Controls.OfType()))
            {

                textBox.Clear();
            }
Comment: they are textboxes
Answer: your code almost work, use this:
<code>        this.Controls.OfType<TextBox>()
            .Where(text =>!(text.Tag == null) && text.Tag.ToString() == "txt").ToList()
            .ForEach(text => text.Clear());
</code>


Save XML file in SQL Azure

Question: Could anyone please say me how to declare a column of xml type in sql azure table and also how to save that file from a local computer to the sql azure table?
Thanks in advance :)
Answer: Not the exact answer you are looking for but here what you can do,

Save the file in BLOB, instead Azure Table. BLOB is structure designed for this purpose only.
Secondly, you can store the BLOB url in your Azure Table.
This will make your application easy to understand and also easy to implement.
This will also help in reducing the size of your database, smaller database better performance

Hope this helps you.
Comment: Check [this](http://msdn.microsoft.com/en-us/library/windowsazure/gg651129.aspx) sample on MSDN. Or http://debugmode.net/2011/09/01/downloading-and-saving-a-file-from-windows-azure-blob-storage/ . You can make `BLOB` public or private. Generally images are stored in Public blob, so that they can be directly download from client machine. In application you can use `WebClient` to fetch file from `BLOB`. Also if you are satisfied with answer, accept them, please read [FAQ](http://stackoverflow.com/faq#howtoask). You didn't accept any answer on your questions.
Comment: Thanks for your information. Could you please tell me how to create a blob and save a file?
Comment: Thank you very much Amar Palsapure. Really the post helped me a lot.
Comment: Glad it worked for you. If you are satisfied with the answer, click "Check Icon" below the up and down arrows, and then click uparrow. This way it helps others in understanding which is the correct answer. There is `Accept-Rate` associated, if that is low guys on SO wouldn't answer your question. Please read the FAQ.
Comment: Why BLOB? XML = XML Right? This query creates an XML column: USE YourDataBaseName
GO

CREATE TABLE Something

([SomethingID] INT PRIMARY KEY IDENTITY,

[TheColumnYouWantToDeclare] XML)

GO
Answer: Here is the short answer:
USE YourDataBaseName

GO
CREATE TABLE Something
([SomethingID] INT PRIMARY KEY IDENTITY,
[TheColumnYouWantToDeclare] XML)
GO
With EntityFramework and LINQ to SQL, you can read the xml content and save that to the column. Here is how you can do this. Of course, you can also write SQL queries but here is how I just solved the problem with LINQPAD.
var myEntityToAdd = new Something();
var xmlContent = System.IO.File.ReadAllText(@"C:\NameOfFile.xml");
var xdoc = XDocument.Parse(xmlContent).Root;
myEntityToAdd.TheColumnYouWantToDeclare = xdoc;
Somethings.InsertOnSubmit(myEntityToAdd);
SubmitChanges();
In Azure SQL tables, you can do a lot of things with XML. Here are three videos to help you:
https://channel9.msdn.com/Series/Using-XML-in-SQL-Server-and-Azure-SQL-Database/01
https://channel9.msdn.com/Series/Using-XML-in-SQL-Server-and-Azure-SQL-Database/02
https://channel9.msdn.com/Series/Using-XML-in-SQL-Server-and-Azure-SQL-Database/03

Save XML file in SQL Azure


Como faço para comparar valores entre duas tabelas e enviar e-mail caso tenha valor novo?

Question: Meu sistema importa todos os dias arquivos CSVs de diversos diretórios em uma tabela chamada TB_ARQUIVO. Nesse arquivo, contém o nome do Hotel(Coluna HOTEL_NOME) e quatro tipos de Canais... SEGMENTO, ORIGEM, COMUNICACAO e VEICULO, fora outras colunas..
Tenho outras tabelas em que já tenho cadastrado previamente as informações que uso para pontuar os clientes. Ou seja, tenho a TB_HOTEl com todos os hotéis cadastrados que são comparados com o arquivo importado na coluna HOTEL_NOME. Assim como tenho as seguintes tabelas TB_SEGMENTO, TB_COMUNICACAO, TB_VEICULO e TB_ORIGEM.
As vezes recebo nomes de hotéis ou nome de canais que não estão cadastrados nessas tabelas. Com isso , tenho que cadastrar manualmente e reimportar o arquivo gerando muito trabalho.
Como faço para gerar um select que me traga todos os nomes dos hoteis + todos os canais e comparo com as tabelas já cadastradas com a finalidade de identificar novos hotéis e novos canais e enviá-los por e-mail ?
Tudo o que existir na TB_ARQUIVO nos campos HOTEL_NOME, SEGMENTO, COMUNICACAO, ORIGEM e VEICULO e não existir na TB_HOTEL, TB_SEGMENTO, TB_COMUNICACAO, TB_VEICULO e TB_ORIGEM deve ser enviado por e-mail.
Alguém conhece uma forma simples de fazer isso ?
Comment: Dê uma olhada aqui: https://stackoverflow.com/questions/173041/not-in-vs-not-exists
Comment: Pode utilizar isso para slectionar os que não existem, agora sobre o email vc tem que descrever quais as possibilidades que vc tem em mãos, como o programa precisaria funcionar, qual seu ambiente, etc
Comment: Obs. eu gero vários emails utilizando o Interop do outlook é muito simples.
Comment: https://stackoverflow.com/questions/11223462/how-to-send-a-mail-using-microsoft-office-interop-outlook-mailitem-by-specifying

Você pode utilizar esse exemplo, criar o body em html, e enviar um relatório bem bacana.
Answer: Recentemente fiz algo parecido para comparar dados, e para o mesmo usei Except, para me retornar apenas os novos registros em uma lista, vê se te atende:
/*Pego todas as descrições da minha lista(esta lista contem descrições novas e já cadastradas no BD)*/
var occurrencesDescription = model.CustomOccurrences.Select(o => o.Description).ToList();

/*Faço uma busca no BD usando as descrições(aqui ele só retornará as já cadastradas no BD)*/
var occurrences =repository.GetNonDeliveryReasonsListByDescriptionList(occurrencesDescription);

/*Uso o Except para me retornar apenas as que não foram localizadas na consulta acima*/
var newsOccurrences = model.CustomOccurrences.Select(o => o.Description).Except(occurrences.Select(o => o.Description)).ToList();

separada apenas as novas você trata como quiser, no meu caso eu cadastro novos registros.
Answer: Caso você queira não cadastrar duplos sugiro que crie uma Trigger para o insert para validar se o registro já a existe e bloquear o insert. Mas se você quer somente enviar o mail no momento do insert, você tambem cria uma trigger porem com o codigo de envio de email, que é um pouco mais complicado mais nada de mais...
caso você use sql server aqui tem um um tutorial de como fazer ai basta implementar na trigger
https://technet.microsoft.com/pt-br/library/ms190437(v=sql.105).aspx
Comment: Mas não vai ficar muito pesado ? REsolvi pra fazer uma trigger para vrificar somente os casos que quero e jogar em outra tabela. Dessa tabela, pretendo jogar via email.
Comment: Não fica pesado. Na empresa onde trabalho tem um caso que, quando uma determinado insert ocorre em uma tabela, ela dispara a trigger que insere a informação em uma tabela de log e desta tabela de log, dependendo da regra, manda email para os responsaveis, este email é disparado da tabeal de log, assim não "sujo" a tabela principal, entendeu?


Predicting occurence of events

Question: If the sampling time interval is 10 sec and 3 events occur during the interval the first event occurs at the 4th sec , the second event occurs at the 7th sec and 8th event occurs at 8sec. Is there a way i could predict when the next event occurs ?? IS there a mathematical formula for this ? Any suggestion what i should be looking into
Comment: I'm not sure if the question you are asking makes sense. If the events occur at different intervals, the formula you posted is still valid.
Comment: IF the events are irregular then the formula is invalid.
Comment: Well, then you can not define a frequency. So exactly which quantity are you interested in?
Comment: @thundersteele Let me rephrase the question if the sampling interval is 10 sec and 3 events occur during the interval the first event occurs at the 4th sec , the second event occurs at the 7th sec and 8th event occurs at 8sec. Is there a way i could predict when the next event occurs ?? IS there a mathematical formula for this ??
Comment: I want something like [link](http://stackoverflow.com/questions/758036/predict-next-event-occurrence-based-on-past-occurrences) but for this scenario
Answer: The simplest possible model that could represent your situation is a Poisson process, where each event is independent from the previous one, and the arrival rate doesn't change. In that case, estimating the arrival rate is fairly straightforward, and you can predict (or simulate) how low it will take for the next event to happen, from any given time.
Two broad situations would make that model somewhat inadequate:
1) Each event is not independent of the previous event(s). For instance, event happen in clusters, or it's less likely to observe an event right after another one happened. In that case, you may look into modeling your process as a Markov chain, where each event depends on the previous state of the system.
2) The arrival rate is not stationary. For instance, the arrival rate increases or decreases over time. In that case, you need to consider how to model that.
Hope this helps!

Predicting occurence of events


python subprocess.call() doesn't work with multiline shell commands

Question: I would like to run this multiline shell commands:
echo 'a=?'
read a
echo "a=$a"

from a python script, using the subprocess.call() method.
I wrote this, in test.py file:
import shlex, subprocess

args = ["echo", 'a=?',"read", "a", "echo", "a=$a"]
subprocess.call(args)

and when I execute it, I have in terminal this report:
Armonicus@MyMacs-iMac MyNewFolder % python test.py
a=? read a echo a=$a

which is not at least close to what I expect.
Can I have some support from anyone, please?
Answer: There are a couple of issues with your approach here.
First, if what you're trying to do is prompt the user for input from the command line, then you can use Python builtins instead of a subprocess:
a = input('a=?')
print(a)

If you do want to call a subprocess with multiple commands, you need to either make separate calls for each command, or invoke a shell and execute the commands within it. For example:
subprocess.call("echo 'a=?'; read a; echo $a", shell=True)


How to transmit parameters to Rules Component upon using Rules Scheduler programmatically?

Question: Now I'm trying to create a Rules Scheduler task programmatically.
I've created a Rules Action with parameters and callback, also I've created a Rules Component with this Rules Action.
But upon trying to create the Rules Scheduler task programmatically I can't transmit it parameters for the Rules Component.
I'm using code, found here.
<code>$now = new DateTime();
    $component = 'yrv_invitation_coupon_test_rule';
    $task_id = $now->getTimestamp();

    rules_action('schedule', ['component' => $component])
        ->executeByArgs([
            'date' => $now->getTimestamp()+10,
            'identifier' => $task_id,
            'param_uid' => 10,
            'param_rid' => 5,
        ]);
</code>
It works, but with default parameters.That is, executed Action in the Component can't get param "uid" with value = 10 and param "rid" with value = 5.
Could ou clarify me, how can I assign parameters ?
Here's my Action
<code>$actions['yrv_invitation_coupon_user_remove_role'] = [
        'label' => t('Remove a role assigned upon activation an invitation coupon'),
        'group' => t('System'),
        'base' => 'yrv_invitation_coupon_remove_role_callback',
        'parameter' => [
            'uid' => [
                'type' => 'integer',
                'label' => t('User ID'),
                'default value' => 1,
            ],
            'rid' => [
                'type' => 'integer',
                'label' => t('Role ID'),
                'default value' => 1,
            ]
        ],
    ];
</code>
And here's my Rule Component
<code>$rule = rule();
    $rule->label = 'YRV Invitation coupon test Rule';
    $rule->class = 'Rule';
    $rule->action('yrv_invitation_coupon_user_remove_role', ['uid' => 1, 'rid' => 1]);
    $rule->active = TRUE;

    $configs['yrv_invitation_coupon_test_rule'] = $rule;
</code>
Answer: Fortunately, I managed to find the solution.
Namely, a Rule component should be created such way.
<code>function yrv_invitation_coupon_default_rules_configuration()
{
    $configs = [];

    $rule = rule([
        'uid' => [
            'type' => 'integer',
            'label' => t('User ID'),
        ],
        'rid' => [
            'type' => 'integer',
            'label' => t('Role ID'),
        ],
    ]);
    $rule->label = 'YRV Invitation coupon test Rule';
    $rule->class = 'Rule';
    $rule->action('yrv_invitation_coupon_user_remove_role', []);
    $rule->active = TRUE;

    $configs['yrv_invitation_coupon_test_rule'] = $rule;

    return $configs;
}
</code>


Questão sobre fila em C

Question: Alguém pode analisar esse meu código e ver o que pode estar errado?. É um exercício de simulação que recebi para fazer na faculdade.
Erro: O código executa, porém entra em looping. Qual while tem problema?
Código:
#include <stdio.h>
#include <stdlib.h>
#define N 10

int suc(int p){
  int temp;
  if (p==N)
        temp=1;
  else
        temp=p+1;
  return(temp);
}

void inserir(char F[], int i, int *f, int *over, int *c, char ch){
    *over= 0;
    if(suc(*f)==i){
        printf("Overflow na fila\n");
        *over=1;
    }
    else{
        *f=suc(*f);
        F[*f]=ch;
        *c++;
      }
}

char remover(char F[], int *i, int f, int *c){
    char temp;
    if(*i==f)
        printf("Underflow na fila");
    else
    {   *i=suc(*i);
        temp=F[*i];
        *c++;
    }
    return(temp);
}

void exibirSomenteFila(char F[], int i, int f){
  int x;
  if (i == f)
    printf ("\nFila vazia");
  else
   { x=i;
     while (x != f)
       { x = suc(x);
         printf(" %c ",F[x]);
       }
   }
   printf ("\n");
}

void main()
{
char F[N+1], ch;
int i,f, minutos, contador, ov, r, k ;

minutos=0;
i=1;
f=1;
contador=0;
ov=0;

while(contador<40){

    minutos++;

    if (minutos % 2==0){
        inserir(F, i, &f, &ov, &contador, 'a');
        if (ov==1){
            printf("A area sera esvaziada");
            exibirSomenteFila(F,i,f);
            while (i != f){
                ch=remover(F, &i, f, &c);
                printf("%d", ch);
            }
            inserir(F, i, &f, &ov, &contador, 'a');
            exibirSomenteFila(F,i,f);
        }
    }

    if (minutos%3==0){
        r=rand() % 3;
        k=1;
        while (k<=r){
            ch=remover(F, &i, f, &contador);
            printf("%c", ch);
            k++;
        }
    }

    if (minutos%8==0)
        exibirSomenteFila(F,i,f);
}
exibirSomenteFila(F,i,f);

}

Comment: `Line 74: [Error] 'c' was not declared in this scope.` Você está passando uma variável 'c' que não existe como parâmetro da função. Declare a variável c e coloque um valor nela antes de usá-la.
Comment: você poderia ao menos dizer alguma coisa sobre o erro que ocorre ? ou será que isso é segredo ?  _"I'm a doctor Jim, not a psychic"_
Comment: José, acho que é um erro na retirada do valor no fim da fila.
Comment: O certo era eu usar contador e não c, já arrumei isso. Porém entra em looping.
Comment: @YgorFraga Coloque as informações solicitadas na própria pergunta, usando o botão [edit].
Answer: O seu contador não está sendo atualizado. Se colocar um printf("\n Contador = %d", contador) dentro do while do main vai ver isso.
Fiz duas alterações no seu código:

Usei int main(), você usa void main()
Usei *c = *c + 1, no lugar de todos os *c++

Ficou assim:
#include <stdio.h>
#include <stdlib.h>
#define N 10

int suc(int p){

    int temp;
    if (p==N)
        temp=1;
    else
        temp=p+1;
    return(temp);
}

void inserir(char F[], int i, int *f, int *over, int *c, char ch){

    *over= 0;
    if(suc(*f)==i){
        printf("Overflow na fila\n");
        *over=1;
    }
    else{
        *f=suc(*f);
        F[*f]=ch;
        *c = *c + 1;
    }

}

char remover(char F[], int *i, int f, int *c){

    char temp;
    if(*i==f)
        printf("Underflow na fila");
    else
    {   *i=suc(*i);
        temp=F[*i];
        *c = *c + 1;
    }

    return(temp);
}

void exibirSomenteFila(char F[], int i, int f){

   int x;
   if (i == f)
     printf ("\nFila vazia");
   else
   {
       x=i;
       while (x != f){
        x = suc(x);
        printf(" %c ",F[x]);
       }
   }
   printf ("\n");
}

int main(){

    char F[N+1], ch;
    int i,f, minutos, contador, ov, r, k ;

    minutos=0;
    i=1;
    f=1;
    contador=0;
    ov=0;

    while(contador<40){

        minutos++;
        if (minutos % 2==0){
            inserir(F, i, &f, &ov, &contador, 'a');
            if (ov==1){
                printf("A area sera esvaziada");
                exibirSomenteFila(F,i,f);
                while (i != f){
                    ch=remover(F, &i, f, &contador);
                    printf("%d", ch);
                }
                inserir(F, i, &f, &ov, &contador, 'a');
                exibirSomenteFila(F,i,f);
            }
        }

        if (minutos%3==0){
            r=rand() % 3;
            k=1;
            while (k<=r){
                ch=remover(F, &i, f, &contador);
                printf("%c", ch);
                k++;
            }
        }

        if (minutos%8==0)
            exibirSomenteFila(F,i,f);
    }

    exibirSomenteFila(F,i,f);

    return 0;
}

Veja funcionando no Ideone.
Uma dica, tome cuidado com a tabulação do código.
Comment: Funcionou, obrigado. Mas por que não estava contando com *c++? e nesse código faria diferença usar o void main()?
Comment: @YgorFraga , sinceramente eu não sei por que *c++, não funcionou. Você pode fazer outra pergunta e outros usuários vão saber te responder isso. Eu sempre uso *x = *x +1. Já sobre o void main(), funções do tipo "void" não retornam nenhum valor, isso quer dizer que elas são apenas procedimentos, são estáticos. O correto é utilizar a função "main" como inteira, pois o seu valor poderá indicar se o programa foi finalizado corretamente ou não.

Questão sobre fila em C


NameError: name 'sc' is not defined

Question: I am working on some code for Face-Recognition. I am trying to combine the csv files that I have into one file that the program will read and once it has an accuracy level of at least 0.8 or higher it will scan my face and determine my expression. When running the program it complains about the variable "sc". Before I was having trouble with the variable "capture" but I was able to fix that now I have this new error and I'm not used to using Random Forest so can someone help me out?
<code>import os
import pandas as pd
from os import path
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import variable_record
import cv2
import face_recognition
import numpy

os.chdir("../csv_files/")

def file_combination():
    extension = 'csv'
    all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
    combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames])
    combined_csv.to_csv("combined_csv.csv", index=False, encoding='utf-8')
    print("Combination is finished")

def create_file():
    print("Prepare for csv files combination...")

    # check whether the combined file is existed
    is_existed = path.exists("combined_csv.csv")

    # ask user whether he/she want to renew the file if the file is already existed
    if is_existed:
        renew = input("The file is already existed, do you renew the file? (Y/N) ")
        if renew.upper() == 'Y':
            os.remove("combined_csv.csv")
            file_combination()
        else:
            print("Program is ended.")
            exit(0)
    else:
        file_combination()
    print("--------------------------------------------")

def main():
    create_file()

    # import dataset
    dataSet = pd.read_csv("combined_csv.csv")

    # preparing data for training
    X = dataSet.iloc[:, 0:7].values
    y = dataSet.iloc[:, 7].values

    # divide data into training data and test data
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

    # scaling features
    sc = StandardScaler()
    X_train = sc.fit_transform(X_train)
    X_test = sc.transform(X_test)

    # train the data
    classifier = RandomForestClassifier(n_estimators=50)
    classifier.fit(X_train, y_train)
    y_pred = classifier.predict(X_test)
    print("Accuracy: ", accuracy_score(y_test, y_pred))

if __name__ == "__main__":
    main()

    while True:
        # turn on the webcam and check the status
        capture = cv2.VideoCapture(0)
        if capture.isOpened() is False:
            print("Camera Error, please check your camera @_@")
            exit()

        # change the BGR frame to gray frame
        ret, frame = capture.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # use face_recognition library to locate the landmarks
        face_marks = face_recognition.face_landmarks(gray, None, "large")

        if face_marks.__len__() != 0:
            # calculate EAR, MAR, PUC, and MOE
            L_EAR = variable_record.cal_EAR(face_marks[0]["left_eye"])
            R_EAR = variable_record.cal_EAR(face_marks[0]["right_eye"])
            MAR = variable_record.cal_MAR(face_marks[0]["top_lip"], face_marks[0]["bottom_lip"])
            PUC = variable_record.cal_PUC(face_marks[0]["left_eye"])
            EBA = variable_record.cal_EBA(face_marks[0]["right_eyebrow"])
            CAR = variable_record.cal_CAR(face_marks[0]["chin"])
            MOE = MAR / L_EAR

            predict_data = numpy.array([[L_EAR, R_EAR, MAR, PUC, MOE, EBA, CAR]])
            predict_data = sc.transform(predict_data)
            expression = classifier.predict(predict_data)

            # transfer expression value to english
            if expression == 1:
                expression = "Neutral"
            elif expression == 2:
                expression = "Happiness"
            elif expression == 3:
                expression = "Sadness"
            elif expression == 4:
                expression = "Fear"
            elif expression == 5:
                expression = "Angry"
            elif expression == 6:
                expression = "Surprise"
            else:
                expression = "Other"
            print(expression)

            # rectangle the face
            face_point = face_recognition.face_locations(gray)
            for pts in face_point:
                cv2.rectangle(frame, (pts[3], pts[0]), (pts[1], pts[2]), (0, 255, 0), 2)

                # show the result on the frame
                cv2.putText(frame, expression, (pts[3], pts[0]), cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 255, 0), 1)

        # press q to exit the loop
        if cv2.waitKey(1) & 0xff == ord('q'):
            break

        # display the frame
        cv2.imshow("Expression Prediction", frame)

    # release the memory
    capture.release()
    cv2.destroyAllWindows()
    exit(0)
</code>
Comment: The variable 'sc' is instantiated in the main() function. It is out of scope by the time you do this:- predict_data = sc.transform(predict_data)
Comment: Python is not C/C++ - you don't *need* a `main()` function. Just combine the logic you've put in `main()` with the code that comes after you call it, and everything should work as expected.
Comment: So what would I need to do? Should I move it somewhere else? @AndyKnight
Comment: So I would get rid of the main() function but the code that is inside of it I would add after the while True: ? @MattDMo
Comment: Take the code that is currently in `main()` and place it where you currently call `main()` - **before** the `while True` loop.
Comment: Notwithstanding the rather unusual structure of your code, what you could do is return sc from main() then sc = main()
Answer: As pointed out in comments, sc is out of scope when you are calling transform.
Either you can remove main mentod and put all logic outside, or return sc from your main function.
Something like this:
<code>...
y_pred = classifier.predict(X_test)
print("Accuracy: ", accuracy_score(y_test, y_pred))
return sc

if __name__ == "__main__":
    sc = main()
    ....
</code>

NameError: name 'sc' is not defined


Monotonic log det function?

Question: I want to claim that the follwoing function is monotonically increasing in $d_j$.
$$\log\det\left\{\mathbf{I}+\frac{1}{d_{j}^{-\alpha}\mathbf{H}_{j}\mathbf{v}_{j}\mathbf{v}_{j}^{H}\mathbf{H}_{j}^{H}+\sigma^{2}\mathbf{I}}\right\}$$
where  $\mathbf{H_j}$ is a complex valued constant matrix. Then  $\mathbf{v_j}$ is complex valued constant vector. $\alpha$ is a real positive constant and $d_j$ is non negative real valued scalar variable, $\mathbf{I}$ is the identity matrix. The superscript $^H$ is the conjugate transpose (Hermitian). The $\sigma^2>0$ and is a real scalar.
Any suggestion is appreciated. Thank you
Comment: What is $\sigma$?
Comment: Try taking this to Math.stackexchange.com Also you can radically simplify the expression you're asking about, so why not do that *before* posting?
Comment: @AnthonyQuas Could you please explain how I can simplify it? My knowledge of matrices is very limited, most I know is taking inverse of a 3 by 3 Thank you.
Answer: I don't write the subscipt $j$. Let $u=H_jv_j$. I assume that $\sigma>0$ and that your $1/Z$ denotes $Z^{-1}$ !!(MLT, your presentation is dismal). Let $f(d)=\log(\det(I+(d^{-\alpha}uu^*+\sigma^2I)^{-1}))$. The eigenvalues of $uu^*$ are $0$ ($n-1$ times) and $u^*u=||u||^2$. Then the eigenvalues of $I+(d^{-\alpha}uu^*+\sigma^2I)^{-1}$ are $1+1/\sigma^2$ $(n-1$ times) and $1+1/(d^{-\alpha}||u||^2+\sigma^2)$. Finally $f(d)=K+\log( 1+1/(d^{-\alpha}||u||^2+\sigma^2))$ where $K$ is a constant scalar. Clearly, it is an increasing function.
Comment: Thank you. Could you please explain how you got the eigenvalues please?
Comment: The rank of $uu^*$ is $1$ and its last eigenvalue is $Trace(uu^*)=Trace(u^*u)$.
Comment: Thank you, appreciate much. I have a similar question http://math.stackexchange.com/questions/489386/monotonicity-of-log-det-rd-i-d-j could you please tell me how to hand that too, if asking so is appropriate.

Monotonic log det function?


How to remove columns in Wordpress backend

Question: My title is pretty general I know that but I hope to explain in more detail here.
In the default wordpress backend users who have the right permissions can manage comments on their own posts. In the overview of this page there you see in this case some detailed data from the comment author, that is his name and his e-mailaddress. Is there a way to remove them in a decent way as in not hacking the Wordpress core.
Kind regards,
Pim
Comment: Please try to improve your question; with specifics for a most accurate answer.
Answer: You can try a reputable 'Admin User Role Management' plugin. Based on your needs.
Example 1:
Adminimize (Personal Recommendation)
https://wordpress.org/plugins/adminimize/screenshots/
Example 2:
User Role Editor
https://wordpress.org/plugins/user-role-editor/screenshots/
If you want to customize manually with hard-code; reference the codex docs on how to do so.
ie:
https://codex.wordpress.org/Function_Reference/add_role
https://codex.wordpress.org/Roles_and_Capabilities