text:
Q: The Operation could not be completed. The system cannot find the path specified I created a C# Website using Visual studio 2015 in my laptop, i copied the same folder to my desktop system and open in Visual studio 2015, when i try to run the application its suddenly gives following error.

The operation could not be completed. The system cannot find the path specified

Anybody feel same error in your latest Visual Studio 2015? I updated all the latest patches.
following trial are done

*

*Re created the soluition file(.sln)

*Deleted Web.config and added new one

Still the error exists, so i cant able to debug or run the application.

A: Create manually (Windows Explorer if necessary) a folder with name "Service References". Even if the folder does not appear in the Solution Explorer, is there.
Try adding the wsdl (xml) file again.

A: I had the same problem, resolved by creating a Connected Services folder in my project.
So juste create a Connected Services folder or a Service References folder in your project

A: (1) Run VS as an admin (or elevated access) and open the solution.
(2) Set up a project as Start up Project (if you have multiple proj)
(3) Set up page as start up page.
this should help you run it

A: I experienced this error. When I shorten the file path of the solution, the error disappear. I think you may put your solution to a folder with too long path name or your solution have some file with too long name.

A: I got a more specific project-load error message when I removed the project from the solution and tried to re-add it. In my case, it was because the URL/address of the application had changed in my local IIS. When I updated the  tag in the .vbproj (or .csproj) file to the new value, then the project loaded successfully.


text:
Q: Use the Jenkins build log variable ${BUILD_LOG} as a substring in the Post Build Actions I want to expose the Jenkins build log as part of the Post Build Actions.  Ideally, I just want to use some of the log, and I'm thinking that I can do this by using a substring of what is produced from the build log.
${BUILD_LOG, maxLines, escapeHtml}

Reference: How can I take last 20 lines from the $BUILD_LOG variable?
The reason that I want to use substring over maxlines is because I just want to output some of the log, in this case from ERROR:, and the length is variable.
Any help on this would be much appreciated!

A: Doable. This post covers off the hurdles / issues you will need to consider and deal with.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ARR The request cannot be routed because it has reached the Max-Forwards limit. The server may be self-referencing itself in request routing topology I have two Windows 2008 R2 Standard Server on which IIS 7.5 is installed (Server1 and Server2). On Server1 I have installed Web Farm Framework 2.2 and created a server Farm "myFarm.com". I have also installed ARR on the Server1.
In the server farm, I have added Server2 and Server1 as the secondary servers. I have configured the ARR with default option. Load balancing is configured to "Round Robin so that request can go to both of the server randomly.
To test my setup I have created a Test.ASPX page and deployed it in both servers.  This is a simple page which returns serverName on which server page is executed. This way I would know that load balancing is working or not.
Then I opened Internet Exlorer and tried to browse my Test.ASPX page from server1 which hosts Web Farm and ARR. Everytime I hit the page request goes to Server2 only. I made my server2 has unhealthy in the webfarm to check if Server1 handle the request or not. When I tried to hit the Test.aspx in the browser, I was surprised to add following error:
The request cannot be routed because it has reached the Max-Forwards limit. The server may be self-referencing itself in request routing topology.
From the error message it appears that when my server2 is not available ARR is sending the request to Server1 which is again sending it to itself causing loopback. I couldn't find a way to stop this loopback.
One of the solution which I found after searching is that I should not add Server1 to the web farm as it is hosting ARR, but I have only two servers and I don't want to use one server just for ARR.
As soon as I mark my server2 healthy request starts getting executed by server2.
Could someone suggest what should be configured to resolve this error?
Thanks

A: You can do a self reference ARR and avoid to get the max-fowards limits if you configure ARR on port 80 and your web farm on another port : ex 8080
So when ARR route the request to itself he will do it on another port so avoid to foward and foward again the request.
Enjoy :-)

A: I had the same problem recently and this is the configuration that helped me (following what Cedric suggested in another post).
So, here is what you can do:

*

*In your web-site configuration, add additional binding for Server2, for example, to port 88 (i.e. you should be able to get response by navigating to http://Server2:88/Test.ASPX).

*In your server farm configuration, add condition to your routing (Routing Rules -> URL Rewrite) to avoid processing requests that go to port 88:


text:
Q: Why is my new BitArray initializing with the wrong value? Background
I have a console application here where the following things happen...

*

*The user/operator enters a string of bits into the console i.e. "0101". - Works

*The string of bits gets converted into a byte. - Works

*The byte array gets reversed using my reverse method. - Works

*I print out the reversed String in the console window. - Doesn't Work
My issue is with number 4 here. I create a bit array out of the newly reversed reversedBits value, and this is where things seem to go wrong. It's as if reversedBitArray is being initialized with the old/un-reversed bits value instead of reversedBits, as my output always seems to be the un-reversed String. This bug seems like it should be so trivial, the reversedBits is the correctly reversed value, so there is some issue with declaring the reversedBitArray but I can't figure out what. Below is all of my source code, including:
The main console application.
static void Main(string[] args)
{
    BitArray reversedBitArray = null;
    String bitString = String.Empty;
    byte reversedBits = 0;
    byte bits = 0;

    // prompt the user to enter a string of bits
    Console.WriteLine("Enter a string of bits here: ");

    // wait for the user to enter the string of bits
    bitString = Console.ReadLine();

    // convert the string of bits into an integer
    bits = Convert.ToByte(bitString, 2);

    // reverse all of the bits
    reversedBits = ReverseBits(bits);

    // display the reversed bits
    Console.WriteLine("\nThe reversed bit string is...");
    reversedBitArray = new BitArray(new byte[] { reversedBits });
    foreach (bool value in reversedBitArray)
    {
        Console.Write(Convert.ToInt32(value));
    }

    // wait for the user to exit
    Console.WriteLine("\n\nPress any key to exit...");
    while (!Console.KeyAvailable)
    {
        Thread.Sleep(100);
    }

    // exit the console application
    Environment.Exit(0);
}

The bit reversal method.
static byte ReverseBits(byte x)
{
    BitArray myBitArray
    byte[] singleElementArray = null;
    int bitArrayMidPoint = 0;
    int bitArrayLength = 0;

    // get a bit array
    myBitArray = new BitArray(new byte[] { x });

    // get the length and mid-point
    bitArrayLength = myBitArray.Length;
    bitArrayMidPoint = (bitArrayLength / 2);

    // start the reversal
    for (int i = 0; i < bitArrayMidPoint; i++)
    {
        bool bit = myBitArray[i];
        myBitArray[i] = myBitArray[bitArrayLength - i - 1];
        myBitArray[bitArrayLength - i - 1] = bit;
    }

    // back to a byte
    singleElementArray = new byte[1];
    myBitArray.CopyTo(singleElementArray, 0);

    // return the reversed value
    return singleElementArray[0];
}

Here is my sample output running in the console window.

A: As suggested by other users, here is the fix I used that worked for me.
static void Main(string[] args)
{
    BitArray reversedBitArray = null;
    String bitString = String.Empty;
    byte reversedBits = 0;
    byte bits = 0;

    // prompt the user to enter a string of bits
    Console.WriteLine("Enter a string of bits here: ");

    // wait for the user to enter the string of bits
    bitString = Console.ReadLine();

    // convert the string of bits into an integer
    bits = Convert.ToByte(bitString, 2);

    // reverse all of the bits
    reversedBits = ReverseBits(bits);

    // display the reversed bits
    Console.WriteLine("\nThe reversed bit string is...");
    reversedBitArray = new BitArray(new byte[] { reversedBits });
    for (int i = (reversedBitArray.Length - 1); i > 0; i--)
    {
        Console.Write(Convert.ToInt32(reversedBitArray[i]));
    }

    // wait for the user to exit
    Console.WriteLine("\n\nPress any key to exit...");
    Console.ReadKey();

    // exit the console application
    Environment.Exit(0);
}

This simply prints the BitArray's values in the reverse order. Here is the new sample output.


text:
Q: Using "this" in jquery after a .next() call I am making a simple scrolling image loop, the first image goes across the screen just fine but nothing follows, am I using "this" incorrectly?
Code:
var width = $(window).width();
var height = $(window).height();

var size = (height + width)/2;

$( document ).ready(function()
{
    $('#pictureFrame').children('img').each(function(){$(this).css('left', '100%')});
});
window.onload = function(){startSlideshow($('#pictureFrame > img'))};
function startSlideshow(myobj) {
    $(myobj).next().animate({left: "-=" + (width + 2000)},{
        duration: 30000,
        queue: false,
        easing: 'linear',
        complete: function() {
            $(myobj).css('left', '100%')
        }
    });
    time = ($(this).width()* 10)/(width + 2000);
    setTimeout(startSlideshow($(this)),time);
}

HTML:

A: I think something like this is closer to what you want:
window.onload = function() {
    startSlideshow($('#pictureFrame > img:first'))
};

function startSlideshow(myobj) {
    myobj.animate({left: "-=" + (width + 2000)},{
        duration: 30000,
        queue: false,
        easing: 'linear',
        complete: function() {
            $(myobj).css('left', '100%')
        }
    });
    var next = myobj.next();
    if (!next.length) {
        next = myobj.siblings().first();
    }
    time = ($(this).width()* 10)/(width + 2000);
    setTimeout(function() {
        startSlideshow(next)
    }, time);
}

Each call to startSlideshow goes to the next image in the DIV. When it runs out, it goes back to the first.


text:
Q: Coldfusion cflog not adding any text to log file I feel ridiculous for even having to ask this question but not being able to print to a simple log file after an hour and a half is absurd. All I am trying to do is write "okok" to a log file and I can't even get that to work. I am using Lucee coldfusion. Here is my code:
 <cflog file="logFile" application="no" text="okok" type="information">

The file "logFile" is in the same directory as everything else. What in the world am I missing? There are no errors there is just never anything added to the log file.

A: The documentation on cflog has the answer.  Look at the description of the file attribute.  The key sentence is, The file must be located in the default log directory.
This link, will help you find that directory.


text:
Q: Convex set of huber's contamination model In the celebrated Huber's robust estimation paper, he considered the following model
$x_i \sim (1-\epsilon) P_\theta + \epsilon G$ where $P_\theta$ is assume to be standard normal. Under this model, data is contaminated by some unknown distribution $G$ with probability of $\epsilon$. The goal for the original paper is to estimate $\theta$ robust to the contamination from Q. Considering $G$ to be all possible probability density function, is the set of functions $(1-\epsilon)P_\theta + \epsilon G$ convex?
I understand that the space of all cdfs is convex so $G$ by itself is a convex set. What about this mixture of $P_\theta$ and $G$?

A: This space is indeed convex.
Using the definition for what is a convex set, for any $t \in [0,1]$,let $G_1,G_2$ be two probabilities, we want to know whether the following distribution is in Huber's contamination model:
$$t ((1-\varepsilon)P_{\theta}+\varepsilon G_1)+(1-t)((1-\varepsilon)P_{\theta}+\varepsilon G_2).$$
This is equal to
$$(1-\varepsilon)P_{\theta}+\varepsilon (tG_1+(1-t)G_2)$$
which is indeed again a corrupted Gaussian distribution with outlier probability $tG_1+(1-t)G_2$.


text:
Q: Optimization across markets - How can I solve? I am unsure how to solve problems involving several markets and optimizing the price across all my markets. Note: I am looking to be pointed in a specific direction of study, not a solution to the problem below.
A simple example: Imagine there are  $n = 2$ markets. $M1$ and $M2$. Each market has a supply and demand function, where:
$y : price $
$x : quantity $
$M1$
$Supply_{M1} : y = -2 + x$
$Demand_{M1} : y = 8 - x$
$M2$
$Supply_{M2} : y = -2 + 2x$
$Demand_{M2} : y = 10 - x$
Now solving for each market is where the lines intersect, very straight forward. But how do you do this, if you allow for markets to trade with each other? Meaning $M1$ can supply units to $M2$? And vice versa.
The real problem has at around 20 markets, that are connected to $1 - 4$ other markets. They can only trade a certain limit.
The real-life example is electricity prices that are calculated across several areas, but each have a specific price determined by interconnections.

A: Not entirely sure how to best answer your question.
Looking specifically at your example with electricity prices, I immediately think of Cournot Competition.
It is essentially quantity competition between a set number of firms. I have seen applications of it involving electricity pricing.
See the wiki: http://en.wikipedia.org/wiki/Cournot_competition/

A: In your example, you are correct that it is easy to solve each market.  The first operates at $x=5,y=3$ and the second at $x=4,y=6$.  The fact that the price is higher in the second says we should buy in the first and sell in the second.  We no longer have the fact that the demand quantity equals the supply quantity in each market, only that the totals are the same.  Let $x_1$ be the amount produced in market $1$, $x_2$ the amount produced in market $2$ and $z$ be the amount shipped from market $1$ to market $2$.  We still have a common price (we assume no transport cost).  Now the equations become
$$y=-2+x_1\\y=8-(x_1-z)\\y=-2+2x_2\\y=10-(x_2+z)\\
2y=18-(x_1+x_2)\\\frac 32y=-3+(x_1+x_2)\\2y=-4+\frac43(x_1+x_2)\\x_1+x_2=\frac {66}7$$ so the total quantity has increased.  That makes sense, as we are producing more in the low cost place and selling more in the high value place. We can solve for the other variables.  If you have a limited transport capacity (so a maximum $z$) you can solve while ignoring the limit.  If the limit is exceeded, set $z$ to the maximum and solve again.


text:
Q: New Attribute values don't show on product page I have a problem with the values of attributes in my Magento installation.
I have created an attribute with the weight of the products and have created some configurable products with these attribute and those were shown correctly on the webshop.
Today I tried to add new values to the same attributes, and I tried to create new products with more values (some values are the values inserted today, and some values older).
Basically, on the product page only the old one and not the new values are shown. Is there someone who knows why this happens?

A: Have you tried running below commands:

php bin/magento indexer:reindex
php bin/magento cache:clean

Also make sure you have assigned this attribute to attribute set.


text:
Q: how to make circle view? I want to make a circle view  in android

A: Solution:-

   class CircleView : View {
        private var paint: Paint? = null
        private var bgpaint: Paint? = null
        private var drawable: Drawable? = null
        private var text1: Paint? = null
        private var rect: RectF? = null
        private var negativeValue = 50f
        private var positiveValue = 50f

     }


text:
Q: Issue In Adding Class To TextBox Using Jquery Basically I'm working on a simple functionality. But stuck on a part when I try to addClass to any HTML Element it's not working.
I've two HTML elements

*

*Dropdown for DocType

*TextBox for DocNumber.

Based on selected value in DocType I need to change class for DocNumber which will handle validation part for DocNumber textBox.
Here is code of my script.
$(document).ready(function () {
    $(".number").keydown(function (e) {
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
        (e.keyCode >= 35 && e.keyCode <= 40)) {
        return;
    }
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
        }
    });
 });

$('#ddlDoctype').on('change', function () {
    var validateCriteria = $(this).find("option:selected").val();
    if (validateCriteria == "A") {
    $("#txtDocNumber").addClass("minSize[8]");
    $("#txtDocNumber").addClass("number");
    $("#txtDocNumber").removeClass("minSize[12]");
} else if (validateCriteria == "E") {
    $("#txtDocNumber").addClass("minSize[12]");
    $("#txtDocNumber").removeClass("minSize[8]");
    $("#txtDocNumber").addClass("number");
} else if (validateCriteria == "C") {
    $("#txtDocNumber").removeClass("number");
} else {
    $("#txtDocNumber").removeClass("number");
}
});

Here a good thing to notice is that when I add minSize[8] to textbox it gets assigned but number class is not getting assigned to the textbox. When I added that part in watch I get a result that number class is getting assigned but it's not working and allowing user to enter alphabets too.
I can't get out of it even after trying many ways to solve this. If any help is possible then I'll be grateful to you.

A: You need to put change event in document ready and need to register keydown event of .number with on.
       $(document).ready(function () {
            $(document).on('keydown', '.number', function (e) {
                if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
                    (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                    (e.keyCode >= 35 && e.keyCode <= 40)) {
                    return;
                }
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });
            $('#ddlDoctype').on('change', function () {
                var validateCriteria = $(this).find("option:selected").val();
                if (validateCriteria == "A") {
                    $("#txtDocNumber").addClass("minSize[8]");
                    $("#txtDocNumber").addClass("number");
                    $("#txtDocNumber").removeClass("minSize[12]");
                } else if (validateCriteria == "E") {
                    $("#txtDocNumber").addClass("minSize[12]");
                    $("#txtDocNumber").removeClass("minSize[8]");
                    $("#txtDocNumber").addClass("number");
                } else if (validateCriteria == "C") {
                    $("#txtDocNumber").removeClass("number");
                } else {
                    $("#txtDocNumber").removeClass("number");
                }
            });
        });

A: As per provided fiddle, You have forgot two thing
1. You have missed jquery library
2. $('#ddlDocType') should be inside $(document).ready
check updated snippet below..

    $(".number").keydown(function (e) {
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
        (e.keyCode >= 35 && e.keyCode <= 40)) {
        return;
    }
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
        }
    });

    $('#ddlDocType').on('change', function () {
        var validateCriteria = $(this).val();

        if (validateCriteria == "A") {
        $("#txtDocNumber").addClass("number");
    } else if (validateCriteria == "E") {
        $("#txtDocNumber").addClass("number");
    } else if (validateCriteria == "C") {
        $("#txtDocNumber").removeClass("number");
    } else {
        $("#txtDocNumber").removeClass("number");
    }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Document Type:
<select id="ddlDocType">
  <option value="A">Pan</option>
  <option value="E">Adhar</option>
  <option value="E">Passport</option>
  <option value="D">Driving Licence</option>
</select>
  </br>
  </br>
  Document Number: <input type="text" name="docNum" id="txtDocNumber"><br>


text:
Q: How to position 2nd element center when 1st element pushing to right in CSS I am very new to CSS and I created a call directory that displays a icon at left side and name of the person next to it. In next line i am printing his phone number. Phone number is aligned to center, but the name is not always.
To make it center I wrapped all my content in a div

I created a jsfiddle: http://jsfiddle.net/rajeevgurram/LmU5a/
How can I center the name of the person when that little icon pushing the name to right ?

A: As you learn more, you'll find you rarely want to use an actual img tag. In this case, the image should be a background on the element it's next to. This way, you can position it wherever you want without it pushing around your content. While you're changing it, you may want to make the markup more semantic (simple as possible and defined by function rather than style). I suggest something like:
HTML

Name 1

Description 1

Name 2

Description 2

CSS
dt {
  background: url('icon.png') no-repeat left center;
}


text:
Q: Using ReadList to import specific arrays of a multi-dimensional variable Consider a large numerical variable (almost 1GB) which was constructed like below:
output={scalar1,{Matrix1,Matrix2,Matrix3,scalar2}};

I used Export to save output variable as a .csv file. Now I want to import specific array of output variable to notebook, say row 1 of Matrix1, and do some post-processing operations. Clearly, Import command is not an effective and  applicable choice due to high time & memory usage. Hence, one may use OpenRead and then ReadList to read desired arrays. The question is, how I can implement ReadList to import specific array of a multi-dimensional variable. Here is a simple example of output:
output = {0.049003,
{{{0, 0., -1.97949}, {0, 5., 9.01025}},
{{0, -1.97949, -6.53072}, {10, 9.01025, 5.13141}},
{{0, -7.91796, -10.287}, {0, -3.95898, -11.5564}},
0.048003}};

and the corresponding .csv file:
0.049003
"{{0, 0., -1.9794901687515782}, {0, 5., 9.01025491562421}}","{{0, -1.9794901687515782, -6.530723746803215}, {10, 9.01025491562421, 5.131408741303968}}","{{0, -7.917960675006313, -10.286973637200234}, {0, -3.9589803375031565, -11.556404359777813}}",0.048003

A: After some digging, somehow I have found my solution. I developed a module for this purpose. But since I'm a beginner in Mathematica,  the algorithm may seem elementary.  Here it is:
GetArray[fName_, rowIndex_, matIndex_] :=
Module[{fileName = fName, matID = matIndex, row = rowIndex, stream,
tempArray, mat, outputList},

stream = OpenRead[StringJoin[NotebookDirectory[], fileName]];
tempArray =
ReadList[stream, Record, 3, RecordSeparators -> {{"{{"}, {"}}"}}];
Close[stream];
mat = ToString[tempArray[[matIndex]]];
Clear[tempArray];
mat = StringSplit[mat, "}, {"];
outputList =
StringSplit[
StringReplace[
mat[[row]], {"}" -> "", "{" -> "", WhitespaceCharacter -> ""}],
 ","];
Return[ToExpression[outputList]];
];

for a 511mb csv file, in order to extract fourth row of Matrix1:
GetArray["myFile.csv", 4, 1] // AbsoluteTiming

Utilizing this module, It took 23.460668 seconds to process the file on a 4GB Ram with Intel Core i5-2410M CPU, while it's almost impossible to load myFile.csv using Import on this machine.


text:
Q: Probability of a bin with at least $1+\biggl(\frac{2}{3}+\epsilon \biggr) \ln n$ balls
Suppose we throw uniformly and independently $n$ balls into $n$ bins. Then for $\epsilon > 0$ holds
$$\mathbb{P}\bigg[\exists \text{ a bin with at least } 1+\biggl(\frac{2}{3}+\epsilon \biggr) \ln n \text{ balls} \bigg] = \mathcal{o}(1)$$

In class we have just done Lovasz Lemma (the assymetric case as Wikipedia calls it), but I do not see how to use this here. Could you please give me a hint?
EDIT: Using leonbloy's suggestion I have come up with the following:
Let $X_i$ be the event that the $i$-th bin has at least $1+\biggl(\frac{2}{3}+\epsilon \biggr) \ln n$ balls, so we have
$$\mathbb{P}\bigg[\exists \text{ a bin with at least } 1+\biggl(\frac{2}{3}+\epsilon \biggr) \ln (n) \text{ balls} \bigg] =\mathbb{P} [ \cup_{i = 1}^n X_i ] \le \sum_{i=1}^n \mathbb{P}[X_i] = n \cdot \mathbb{P}[X_1]$$
Since $X_1 \sim \operatorname{Bin}(n,1/n)$ we have $\mathbb{E}[X_1] =1$. However, I fail to use Chernoff's bound to estimate $\mathbb{P}[X_1]$:
$$\mathbb{P}\bigg[X_1 \ge 1 + \biggl(\frac{2}{3}+\epsilon \biggr) \ln (n) \bigg] \le \exp \Bigg(- \frac{\biggl(\frac{2}{3}+\epsilon \biggr)^2 \ln^2 (n) }{2\bigg(1 + \biggl(\frac{2}{9}+\frac{\epsilon}{3} \biggr) \ln (n)\bigg)}\Biggr)$$
I do not see what to do with this term. Could you please give me another hint?

A: Since you are OK with not using the Lovasz lemma, we can apply the simple method used in this answer. There is nothing special about $2/3$; for any constant $C$, the probability there exists a bin with $C\log n$ balls is $o(1)$.
Let $k\ge 1$ be any integer, let $M$ be the maximum number of balls in any bin, and let $Z$ be the number of balls in the first bin. Using the union bound,
$$
P(M\ge k)\le n\cdot P(Z\ge k)
$$
In order for $Z\ge k$ to occur, there must exist a subset of $k$ balls which all fall in the first bin. There are $\binom nk$ subsets of $k$ balls, and the probability that $k$ particular balls land in the first bin is $n^{-k}$, so using the union bound again,
$$
P(Z\ge k) \le \binom{n}{k}\cdot \frac1{n^k}=\frac{1}{k!}(1+o(1))\qquad \text{as $n\to\infty$}$$
Therefore,
$$
P(M\ge k)\le \frac{n}{k!}(1+o(1))
$$
Using Stirling's approximation, you can show that if $k$ grows like $ C\log n$ for any constant $C>0$, then $n/k!\to 0$.
\begin{align}
\log(n/k!)
  &=\log n-\log(k!)
\\&=\log n-k\log k+O(k)
\\&=\log n-(C\log n)\log(C\log n)+O(\log n)
\\&=-C\log n\cdot \log\log n+O(\log n)
\end{align}
The dominant term is $-C\log n \cdot \log \log n$, which approaches $-\infty$. Since $\log(n/k!)\to -\infty$, we get $n/k!\to 0$.
We conclude that $P(M\ge k)\to 0$, which is equivalent to $P(M\ge k)=o(1)$.


text:
Q: ReSharper Test Runner runs all test within assembly instead of running just under only the selected folder I am trying to run NUnit unit tests within VS 2015 using ReSharper test runner.
What am I doing:

*

*Right click on a folder say "MyFolder" in VS 2015 Solution Explorer

*In the context menu I click on "Run Unit Tests" menu item. The "Unit
Test Sessions" panel opens with the correct title "All tests from
MyFolder".

*The "Unit Test Sessions" panel correctly shows the tree
with only the TestFixtures and their Test cases within MyFolder
However not only those test cases will be run instead all tests in
the assembly.

Please note: In many cases it will be hard to notice that other test cases are also run, because no visual feedback on those. I mean no red / green, because the unwantedly ran tests are not in the unit test session tree. However if your tests say launching external process, you will see that something unwanted is happening. Also you can run the tests in debug mode, an place a breakpoint some other tests (what are not in the tree) your breakpoint will be hit.
As I have many unit tests in the assembly and they launches external process (Selenium driver for various browsers) this issue makes me run "all or nothing".
(Except I open a test file individually and run via the source window. That feature works correctly, only the right clicked test will run)
Is it a known issue, or just me?
Thanks in advance.
Additional info:

*

*Using VS  2015 Enterprise 14.0.23107

*JetBrains Resharper Ultimate 10.0.2

*NUnit 3.0.1

*Windows 7 x64


text:
Q: time conversion to numeric format I have data in time format, e.g. "15:57:41". After converting it into numeric format using as.numeric() in R, the converted value is 0.6650579. Can anybody please explain the logic in the manual calculation behind this? How is the time getting converted to this numeric value?

A: It's a fraction of a day:
library(chron)
as.numeric(times("15:57:41"))
## [1] 0.6650579

Manually convert hours/minutes/seconds to fraction of day:
## (hours + (minutes + seconds/60)/60)/24
(15+(57+41/60)/60)/24
## [1] 0.6650579


text:
Q: How to prove a sequence diverges? $a_n^\infty,$ defined by $a_{n+1}=-1-a_n^{2},\qquad a_1=1$ So I'm given a sequence $a_n^∞$ that is defined in a recursive formula as follows:
$$a_{n+1}=-1-a_n^{2},\qquad a_1=1$$
and they're asking prove/disprove that this sequence converges, so I'm thinking it diverges because as you plug in numbers you go further into negative values. The question is how to disprove it.. like I want to try contradiction but I don't know how to contradict this.
Every help is appreciated!

A: $a_1$ is a real number, and it's clear from the recurrence $a_{n+1} = -1 - a_n^2$ that $a_n$ must be real for all $n$. Hence, if $a_n$ converges, it must converge to a real limit.
Suppose that $a_n$ does converge, say to a limit $L$. Taking limits of both sides of $a_{n+1} = -1 - a_n^2$, we obtain $L = -1 - L^2$, or equivalently $L^2 + L + 1 = 0$. You can easily check that this equation has no real solutions (the $b^2 - 4ac$ term in the quadratic formula is $1 - 4 = -3$), so $L$ is not real. This contradiction implies that $a_n$ does not converge.

A: Let $b_n = -a_n$ for $n\ge 2$ and $b_1=1$.
Then $b_{n+1}=b^2_n+1 \ge 2b_n$, because $b_n^2-2b_n+1=(b_n-1)^2 \ge 0$.
Therefore, $b_n \ge 2^{n-1} b_1 = 2^{n-1}$ and so $a_n \le - 2^{n-1}$ and $a_n$ diverges to $-\infty$.

A: I think that the "best" answers are those already given, as they imply explicit bounds on $a_n$ that quantify the blow-up rate of the sequence, that is, the speed at which it diverges to infinity.
(EDIT What follows in the gray box is exactly the same as Bungo's answer)

However, there is another method of proof. Observe that the sequence $a_n$ is integer. Assume for a contradiction that $a_n\to x$. Since the sequence $a_n$ is integer, $x$ must be integer. Moreover, since $\lim_{n\to \infty} a_{n+1}=\lim_{n\to \infty} a_n$, we obtain for $x$ the equation
  $$
x^2+x+1=0.$$
  Completing the square this equation can be rewritten as $(x+\tfrac12)^2+\tfrac34=0$ so it cannot have any real solution, let alone an integer one. (Thank you Daniel Wainfleet for the suggestion). We have reached the desired contradiction.

NOTE. We did not really use the assumption that $a_n$ is integer, we only used that it is real. It is therefore the case that the given recurrence relation $a_{n+1}=-1-a_n^2$ does not produce convergent sequences whatever the initial condition $a_0\in\mathbb R$ is.
It is interesting to compare with the recurrence relation $a_{n+1}=1 - a_n^2$. This leads to the equation $x^2+x-1=0$, with roots $x_\pm=\tfrac12(-1\pm\sqrt 5)$. These roots are not integer, and consequently the sequence $a_n$ cannot converge if $a_0$ is integer; to prove this, just apply the argument above.
However, this argument does not say anything in the case of noninteger $a_0$. This is no coincidence, for in this case there do exist noninteger initial data such that $a_n$ converges: taking $a_0=x_+$ or $a_0=x_-$, where $x_\pm$ are the roots found above, yields two constant sequences, hence convergent.

Changing a $+1$ to a $-1$ in the original recurrence produced a dramatic change in the behavior of the solutions.

A: For convenience we can safely ignore the minus signs and consider
$$a_{n+1}=a^2_n+1.$$
It is obvious that
$$a_n\ge2\implies a_{n+1}=a_n^2+1>a^2_n\ge2a_n$$ so that the sequence is bounded below by a diverging geometric progression.


text:
Q: Installing Appium server on Windows -- how to get past grunt errors? I'm using this guide:
https://github.com/appium/appium/blob/master/docs/running-on-windows.md
And on this step:
grunt configAndroidBootstrap

I can't get it to run. I've tried:

*

*Running it inside node.

*GitHub\appium\node_modules\.bin\grunt.cmd configAndroidBootstrap

Running \appium\node_modules\.bin\grunt.cmd by itself works, it does something at least. But when I add the configAndroid.. part it does:
Running "configAndroidBootstrap" task
The system cannot find the path specified.
Warning: Task "configAndroidBootstrap" failed. Use --force to continue.

Aborted due to warnings.

Ideas?
Thanks.

A: Two options.
1.) Install pre-built Appium for Windows (no grunting required)(https://bitbucket.org/appium/appium.app/downloads/AppiumForWindows.zip)
2.) Run reset.bat instead of the grunt commands. I've updated the doc you referenced to mention that.


text:
Q: ... moral conscience about those in the new cities Does "a moral conscience about those in the new cities" mean:

*

*To feel guilty about the workers in new cities

*To make the workers in new cities feel guilty

*To feel responsible about the workers in new cities

*To make the workers in new cities feel responsible
Context:
There was an unresolved tension between a reverence for wild nature and the desire to colonise it. This led to a lyrical nostalgia for an untainted countryside and a revulsion at its increasing industrialisation, to the view
that rural people possessed a natural nobility and to a moral conscience
about those in the new cities whose labours were necessary to keep the profitable new industries flourishing.
(Art and Science by Sian Ede)

A: That whole sentence is very badly constructed or, if not, the punctuation is wrong. Was this book ever independently proof-read?

conscience noun [C or U] uk    /ˈkɒn.ʃəns/  us    /ˈkɑːn-/
           C2 the part of you that judges how moral your own actions are and makes you feel guilty about bad things that you have done or
  things you feel responsible for:
http://dictionary.cambridge.org/dictionary/british/conscience

Ede has perpetrated a pleonasm with the phrase "moral conscience". I'm losing respect for this author.
Answer
I think it is supposed to mean 3.


text:
Q: Getting error that Conversion from String to Long is Not Valid in VB.net I'm trying to make an error handler, but am getting an error. With my limited English, I do not know how to explain the details of the problem. I hope it is possible that after you see my code you will understand.
I have looked at this, [Conversion from string "" to long is not valid and think the trouble might be with "&" and "Or", but it may be something different.
My code is below. Note that Date1.text, Date2.text, etc.. is datetimepicker.
Dim No1, No2, No3 No4 As String
    No1 = Date1.Text
    No2 = Date2.Text
    No3 = Date3.Text
    No4 = Date4.Text
Select Case CmbNumber.Text
    Case "1 (ONE)"
        No2 = "-"
        No3 = "-"
        No4 = "-"
    Case "2 (TWO)"
        No1 = "-"
        No3 = "-"
        No4 = "-"
    Case "3 (THREE)"
        No1 = "-"
        No2 = "-"
        No4 = "-"
    Case "4 (FOUR)"
        No1 = "-"
        No2 = "-"
        No3 = "-"
End Select
    If CmbNumber.Text = "4 (FOUR)" Then
        If No1 Or No2 Or No3 = No4 Then 'ERROR Conversion From String to Long
            MsgBox("Not allowed the same date", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "ERROR")
            Exit Sub
        End If
    End If

A: You need to be aware of what an operator is in computer programming and Operator Precedence in Visual Basic.
From that, you can determine that the computer sees No1 Or No2 Or No3 = No4 as No1 Or No2 Or (No3 = No4) (items in parentheses, i.e. () are evaluated first), which is not what you want.
Instead, you want No1 = No4 Or No2 = No4 Or No3 = No4.
Now, when you use Or it evaluates every condition, even if it is not mathematically necessary. A new operator, OrElse, was introduced which only does the evaluations which are needed, so your code would be more efficient using No1 = No4 OrElse No2 = No4 OrElse No3 = No4.
Incidentally, you could shorten your code by only setting the value when necessary:
Dim No1 As String = "-"
Dim No2 As String = "-"
Dim No3 As String = "-"
Dim No4 As String = "-"
Select Case CmbNumber.Text
    Case "1 (ONE)"
        No1 = Date1.Text
    Case "2 (TWO)"
        No2 = Date2.Text
    Case "3 (THREE)"
        No3 = Date3.Text
    Case "4 (FOUR)"
        No4 = Date4.Text
End Select

A: The expressionIf No1 Or No2 Or No3 = No4 assumes that No1 and No2 are of type Boolean. You cannot apply the Or operator to something which is not boolean.


text:
Q: How can I process an image data uri and upload to S3 via paperclip? I'm writing a Rails app that captures an image from the webcam, overlays it on an image in /public, and uploads the result to Amazon S3 via paperclip. I wrote some Javascript to get the webcam image as a data uri but I don't know how I would send it to my server to process it and upload the result to S3 via paperclip.
I've looked at https://gist.github.com/WizardOfOgz/1012107, How to save a raw_data photo using paperclip, and read the paperclip source code but I still haven't been able to figure it out.

A: I ended up sending an AJAX request with my model's image attribute set to the data uri. Paperclip automatically detects that it's a data uri and handles it appropriately. I wrote a custom paperclip processor to do the image editing and make the edited image available on S3.

A: I just ran into this problem myself. The solution I came up with works for modern browsers (IE9+/chrome/FF/Safari). Not sure if that's something you can live with. If so:
1) You have to post the dataURI to your server. I don't think that's possible via standard form submission, but you can do it using HTML5 FormData sent via an XHR. Check out this SO entry on the basics of asynchronously posting a form using jQuery: How can I upload files asynchronously?
Alternatively, if you happen to be using Angular like me, you can use the angular-file-upload library https://github.com/danialfarid/angular-file-upload
Once you've created a formData object as described in that post, you can add your dataURI to it:
var formData = new FormData($('form')[0]);
formData.uploadImage = yourDataURI;
$.ajax({ // ... set up your ajax post as described in https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery
});

2) Once you post the data uri, the server-side is easy. Paperclip supports data uris out of the box, just set the paperclip attachment equal to your data uri. If you had an ActiveRecord object named ImagePost, with a paperclip attachment property named overlayed_image you controller might look like:
def update
  image_post = ImagePost.find(params[:id])
  if params['uploadImage']
    image_post.overlayed_image = params[:uploadImage]
  end
  # rest of your controller code goes here
end


text:
Q: Indexing a MYSQL table with many columns I have a table posts with the following columns:
start_at, sun, mon, tue, wen, thu, fri, sat
start_at is of date type, the others - tinyint.
I make a query the following way:
SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1

That is after second AND I set proper day of week dynamically.
What is the best way to index this table? Do I need to make a composite index for each day of a week, for example:
CREATE INDEX mon_index ON posts(start_at,mon);
CREATE INDEX sun_index ON posts(start_at,sun);

If I create 7 indexes for each day of the week, I think INSERT and UPDATE will be really slow.
UPDATED: I do need column for each day of week, because a user sets on which days post will be published. There can be a few days at the same time.

A: Your schema has been oddly designed. Your current setup may make for easy reporting, but you're correct, indexing like you've suggested will create terrible insert and update performance.
My suggestion would be to refactor this table. Instead of your current setup, I would suggest that you change the posts table to have the columns (start_at, day). In this design, day can be Sun through Sat, and you only need one index (start_at, day).
If you really need the current format for reading/reporting reasons (I wouldn't blame you), you could always setup a view that pivots the data in that manner.

All of that being said, not every field you qualify on needs to be in an index. My estimation is that the vast majority of your table's rows will be filterable simply by the date. The few that are left probably don't need to be indexed for decent read performance.

In a different vein, why even store the day? That can be calculated based off the date.

A: AS another said, may be it should be sufficient to index for start_at only.
If you want to investigate on index which include the post publishing day (in particular if your table has lot of field and you want to list only fields start_at and the day of publishing), you could create a table like this:
CREATE TABLE XX (start_at ..., which_day tinyint UNSIGNED);

and an index like this
CREATE INDEX XX_IX01 (start_at, which_day);

where which_day can be, using a sort of coding:
0=no day
2^0=sun
2^1=mon
2^2=..
...
2^6=sat
So, for example if the mon and sat are 1, the value should be 2^1 +2^6=2+64=66.
If possibile avoid SELECT *   and write the field you need.
Use EXPLAIN   to check how db engine use your index/tables.
This link could be useful: How can I index these queries?
Sample data:
CREATE table et1 (start_at DATE, which_day tinyint UNSIGNED);
CREATE INDEX ET1_IX1 ON et1(start_at, which_day);

INSERT INTO et1 VALUES ('20170701', 132);
INSERT INTO et1 VALUES ('20170702', 3);
INSERT INTO et1 VALUES ('20170704', 5);
INSERT INTO et1 VALUES ('20170630', 2);

SELECT start_at, which_day, which_day & 128 AS X FROM et1;
SELECT start_at, which_day, which_day & 128 AS X FROM et1 WHERE start_at>'20170630' AND which_day & 128 =128;
EXPLAIN SELECT * FROM et1 WHERE start_at>'20170630' AND which_day & 128 =128;

DROP table et1;

A: You are over complicating your database schema, there is no need to add all those columns, nor to create a ton of indexes.
You can simplify your post table as:
id | title | (...) | start_at

You can then replace this query:
SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1

and instead use the DAYOFWEEK function:
SELECT * FROM posts WHERE start_at >= '2017-02-01' AND DAYOFWEEK(start_at) = 2

(1 = Sunday, 2 = Monday, …, 7 = Saturday).
You can then keep a single index on the start_at column.


text:
Q: Use custom cursor over an iFrame I am using the following code to change the cursor when clicking on a button:
$("#mybutton").click(function(){
       $("*").css("cursor", "url('images/cur_circle_01.png'), auto");
   });

The cursor changes as expected, but as soon as I move the mouse over the iframe, the cursor reverts to normal.
Is there a way to fix this? The intended behavior is to change the mouse pointer based on button clicks.

A: You cannot control the cursor when it is over an . This is because the browser is rendering a completely different web page, with it's own HTML and JS executing within your main HTML document.

A: Old question, but deserves an answer. I use a div as an overlay and instead of adding cursor to the elements I just have it on the div. This way the iframe has the appearance of having a cursor over it. The important thing is to toggle it off once loading is complete otherwise you won't be able to click on anything. (Adjust size and position to fit over iframe window).

<input id="mybutton" type="button" value="Click Me" />

Google won't load in an Iframe on JSFiddle but this gives you a working idea. https://jsfiddle.net/tbkyjwLn/2/


text:
Q: Async Validators Angular 2 Service undefined? Bug? I have a problem with calling the backend from my Angular2 async validator. I'm using the "final" version of Angular2.
constructor(private formBuilder: FormBuilder,
          private profileService: ProfileService,
          private authService: AuthService,
          private router: Router) {

}
ngOnInit() {
this.registerForm = this.formBuilder.group({
username:  ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9_]*$'), Validators.minLength(6),
  Validators.maxLength(20)], this.validateUsername],
email: ['', [Validators.required, this.validateEmail, Validators.maxLength(30)]],
password: ['', [Validators.required, Validators.pattern('^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*)(?=.*[!#$%&? "]).*$')]],
confirmPassword: ['', [Validators.required]]},
    {
      validator: this.matchingPasswords('password', 'confirmPassword')
    });

}
  validateUsername(control: FormControl): {[key: string]: any} {
    return new Promise((resolve, reject) => {
      this.profileService.isUsernameAvailable(control.value).subscribe(res => {
        if (res) {
          resolve(null);
        } else {
          resolve({ validateUsername: {valid: false} });
        }
      });
    });
  }

The service gets initialized and even if I call it inside the validateUsername Function it works for console.log().
Error is:
Can't read property "profileService" from undefined.
Is this a bug? Or did i mess something up? Looking into this for hours already.
Service Code:
   isUsernameAvailable(username: string): Observable<string> {
   return this.http.get('user?name=').map(res => res.json()).catch(this.handleError);;
  }

Edit:
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

Full Error Msg:
main.bundle.js:44225 EXCEPTION: Cannot read property 'profileService' of undefinedErrorHandler.handleError @ main.bundle.js:44225next @ main.bundle.js:29109schedulerFn @ main.bundle.js:30625SafeSubscriber.__tryOrUnsub @ main.bundle.js:574SafeSubscriber.next @ main.bundle.js:523Subscriber._next @ main.bundle.js:476Subscriber.next @ main.bundle.js:440Subject.next @ main.bundle.js:2027EventEmitter.emit @ main.bundle.js:30617onError @ main.bundle.js:31257onHandleError @ main.bundle.js:64707ZoneDelegate.handleError @ main.bundle.js:89163Zone.runTask @ main.bundle.js:89095ZoneTask.invoke @ main.bundle.js:89260
main.bundle.js:44230 ORIGINAL STACKTRACE:ErrorHandler.handleError @ main.bundle.js:44230next @ main.bundle.js:29109schedulerFn @ main.bundle.js:30625SafeSubscriber.__tryOrUnsub @ main.bundle.js:574SafeSubscriber.next @ main.bundle.js:523Subscriber._next @ main.bundle.js:476Subscriber.next @ main.bundle.js:440Subject.next @ main.bundle.js:2027EventEmitter.emit @ main.bundle.js:30617onError @ main.bundle.js:31257onHandleError @ main.bundle.js:64707ZoneDelegate.handleError @ main.bundle.js:89163Zone.runTask @ main.bundle.js:89095ZoneTask.invoke @ main.bundle.js:89260
main.bundle.js:44231 TypeError: Cannot read property 'profileService' of undefined
    at http://localhost:4200/main.bundle.js:50624:18
    at new ZoneAwarePromise (http://localhost:4200/main.bundle.js:89434:29)
    at RegisterComponent.validateUsername (http://localhost:4200/main.bundle.js:50623:16)
    at http://localhost:4200/main.bundle.js:7776:49
    at Array.map (native)
    at _executeAsyncValidators (http://localhost:4200/main.bundle.js:7776:23)
    at FormControl.asyncValidator (http://localhost:4200/main.bundle.js:7763:28)
    at FormControl.AbstractControl._runAsyncValidator (http://localhost:4200/main.bundle.js:21641:41)
    at FormControl.AbstractControl.updateValueAndValidity (http://localhost:4200/main.bundle.js:21615:22)
    at FormControl.setValue (http://localhost:4200/main.bundle.js:21878:14)ErrorHandler.handleError @ main.bundle.js:44231next @ main.bundle.js:29109schedulerFn @ main.bundle.js:30625SafeSubscriber.__tryOrUnsub @ main.bundle.js:574SafeSubscriber.next @ main.bundle.js:523Subscriber._next @ main.bundle.js:476Subscriber.next @ main.bundle.js:440Subject.next @ main.bundle.js:2027EventEmitter.emit @ main.bundle.js:30617onError @ main.bundle.js:31257onHandleError @ main.bundle.js:64707ZoneDelegate.handleError @ main.bundle.js:89163Zone.runTask @ main.bundle.js:89095ZoneTask.invoke @ main.bundle.js:89260
main.bundle.js:50624 Uncaught TypeError: Cannot read property 'profileService' of undefined


text:
Q: Powershell: Copy and modify filename I have a requirement to copy files from a network drive to local drive based on minutes. Once copied over then I need to modify the filename as per below requirements:
Sample filename:
Ser1-PRD-CL4$Entreprise_AG2_MyCompany-NA_DB_Name_02_LOG_20191217_094501.trn

*

*Copy all files created 35 minutes ago from a Network Directory e.g. \Server\Path to Local directory D:\NameofDB
(I was able to achieve the copy part but wondering if there is any flag that I should put to prevent the same file being copied over again, the copied file will have their name modified so not sure how we can track that)

*Once copied modify the name of all copied only files as following:
a. Remove all characters appearing before word "MyCompany"
b. Remove underscore along with word LOG   "_LOG"
c. Remove  underscore (_) between date and transaction number: 20191217_094501
I have achieved the copy and removal of "_LOG" from the filenames but having trouble with the remaining requirement.
Any input will be appreciated:
Important Note: There will be other files in the destination that were moved name and have their names modified in the destination directory and those file names should not be modified.
$Sourcefolder= "D:\Temp"
$Targetfolder= "D:\Temp2"
Get-ChildItem -Path $Sourcefolder -Recurse|
Where-Object {
  $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-60)
}| Copy-Item -Destination $Targetfolder
Get-ChildItem -Path $Targetfolder | Rename-Item -NewName {$_.Name -replace "_LOG", ""}
Get-ChildItem -Path $Targetfolder | Rename-Item -NewName {$_.Name -replace '^MyCompany'} #This is not working

A: For your first question on the repeated copying of the same files see: Powershell script that can log already scanned files and ignore them on next run?
For 2a)
Get-ChildItem -Path $Targetfolder | Rename-Item -NewName {$_.Name.substring($_.Name.indexof("MyCompany"))}

Please notice that the string is case sensitive.

A: You can use Copy-Item to specify a new name while copying (so no need to rename afterwards).  Look at the code below to get the idea:
$Sourcefolder= "D:\Temp"
$Targetfolder= "D:\Temp2"
Get-ChildItem -Path $Sourcefolder -Recurse |
    Where-Object {
        $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-60)
    } | ForEach-Object {
        $newname = $_.Name.Replace('_LOG','')                       # removes _LOG
        $newname = $newname -Replace "(\d)_(\d)","$1$2"             # replace underscore between the digits
        $newname = $newname -Replace "(.*)Mycompany","MyCompany$1"  # gets rid of anything before the word "MyCompany"
        Copy-Item -Path $_ -Destination (Join-Path $Targetfolder $newname)
    }

A: I'm trying it here with regex lookahead and lookbehind https://www.regular-expressions.info/lookaround.html, so -replace only gets rid of the part that actually matches.
dir |
copy-item -destination {
  $_.name -replace '.*(?=MyCompany)' -replace '_LOG' -replace '(?<=\d)_(?=\d)' } -whatif

What if: Performing the operation "Copy File" on target
Item:        /Users/js/foo/MyServer$Entreprise_AG2_MyCompany-NA_DB_Name_LOG_20191217_094501.trn
Destination:                         /Users/js/foo/MyCompany-NA_DB_Name_20191217094501.trn".

A: You can try this:
get-childitem-path "\\server\share\path" -recurse | foreach {
  if ($_.LastWriteTime -gt [DateTime]::NowAddMinutes(-60)) {
    $TheName = $_.Name -replace "_LOG", ""
    $TheName = $TheName -replace "\d_\d", "$1$2"
    $TheName = $TheName -replace ".*MyCompany", "MyCompany"
    Copy-Item -path $_ -destination {join-path "TargetPath" $TheName}
  }
}


text:
Q: Downloading a segment of a youtube video and cropping it precisely I have an interesting little problem.
I want to download a specific section of a youtube video, this is easy enough to do with the magic of yt-dlp:
yt-dlp -f "(bestvideo+bestaudio)[protocol!*=dash]" --external-downloader ffmpeg
  --external-downloader-args "ffmpeg_i:-ss 672.46 -to 677.15" "https://www.youtube.com/watch?v=7U7Sbl-DXcI"

The problem is, this often results in extra content at the start or end of the video due to where the keyframes are.
A solution to this is to re-encode the video with a specific start and end point.
Again, this is quite straightforward:
ffmpeg -i input.webm -ss 672.46 -to 677.15 -c:v libvpx -c:a copy
  -crf 40 -b:v 500k -vf scale=480:-2 output.webm

The thing is, I don't want to have to download the entire video only to extract a small segment.
The solution I thought of was to do the following:

*

*download the imprecise video+audio segment as before

*download a precise audio only segment (I'm assuming this is possible because there are no keyframes)

*now the tricky bit. somehow figure out how the audio file aligns with the audio track in the imprecise video segment.

*use the offset to re-encode the right portion of the imprecise video segment.

Does anyone have any idea of how I can approach step 3? Or maybe can suggest an alternative approach?
Edit:
It doesn't seem like it's straightforward to download a precise segment of audio using yt-dlp.. does anyone know if this is a limitation of the tool, or just not possible? I'm guessing the seeking depends on the video track and the audio track can't be seeked in the same way?


text:
Q: SQL - Procedure function Trying to create a Procedure to (Insert, Delete and, Update) values in employee_details.
CREATE DEFINER=`root`@`localhost` ALTER PROCEDURE `alter_employeedetails`(in employee_id int(11), employee_name VARCHAR(30), employee_join_date date,
employee_desgination varchar(30), employee_salary bigint(20), employee_address varchar(30),
employee_contact varchar(30), employee_email_id varchar(30)
BEGIN
IF @StatementType = 'Insert'
BEGIN
insert into employee_details values
(employee_id, employee_name, employee_join_date, employee_desgination, employee_salary, employee_address, employee_contact, employee_email_id)
END
IF @StatementType = 'Update'
BEGIN
UPDATE employee_details SET
(employee_name = @employee_name, employee_join_date = @employee_join_date, employee_designation = @employee_desgination,
employee_salary = @employee_salary, employee_address = @employee_address, employee_contact = @employee_contact, employee_email_id = @employee_email_id)
WHERE employee_id = @employee_id
END
else IF @StatementType = 'Delete'
BEGIN
DELETE FROM employee_details where employee_id = @employee_id
END
end

A: Quite a few errors in that code...

*

*You forgot to prefix all the parameters with the "@" symbol.

*Forgot to include "@StatementType" as a parameter.

*Update had brackets around it.

*You cannot specify int(11) (employee_id) or bigint(20)
(salary). It's either int / bigint (you don't specify the length
for int/bigint datatypes). And is salary correct as bigint?  MSSQL has a "money"
datatype, or you could use decimal(8,2) or something similar. You
might be multiplying the salary by 100 to shift the decimal place for
all I know?

*When inserting, do you really want to insert a employee Id? This would normally be an auto-incrementing primary key

*Insert statement missing the fields you were populating. Required if using the "values" keyword like you had specified.

Hopefully this is closer to what you want.
ALTER PROCEDURE alter_employeedetails
    (@StatementType as varchar(25), @employee_id int, @employee_name VARCHAR(30), @employee_join_date date,
    @employee_designation varchar(30), @employee_salary bigint, @employee_address varchar(30),
    @employee_contact varchar(30), @employee_email_id varchar(30))
AS
BEGIN
    IF @StatementType = 'Insert'
    BEGIN
        insert into employee_details
        (employee_id, employee_name, employee_join_date, employee_designation, employee_salary, employee_address, employee_contact, employee_email_id)
        values
        (@employee_id, @employee_name, @employee_join_date, @employee_designation, @employee_salary, @employee_address, @employee_contact, @employee_email_id)
    END
    ELSE IF @StatementType = 'Update'
    BEGIN
        UPDATE employee_details
        SET
            employee_name = @employee_name,
            employee_join_date = @employee_join_date,
            employee_designation = @employee_designation,
            employee_salary = @employee_salary,
            employee_address = @employee_address,
            employee_contact = @employee_contact,
            employee_email_id = @employee_email_id
        WHERE employee_id = @employee_id
    END
    ELSE IF @StatementType = 'Delete'
    BEGIN
        DELETE FROM employee_details where employee_id = @employee_id
    END
END


text:
Q: Physical interpretation of $Q^i = \partial _\nu T^{i \nu}$ I'm trouble with exercise 1.8 of Carroll's Space-Time and Geometry:

If $\partial_\nu T^{\mu \nu} = Q^\mu$, what physically does the spatial vector $Q^i$ represent? Use the dust energy momentum tensor to make your case.

*

*First of all, since the momentum energy tensor of dust $T^{\mu \nu}=\rho U^\mu U^\nu$ is symmetric, one has the energy-momentum conservation law
$$ \partial_\nu T^{\mu \nu} = \partial_\nu T^{\nu \mu}  =0.$$
A vector $Q$ is constant in any frame related by a Lorentz transformation, while this isn't the case for the components $Q^\mu$. But here $Q=0$ and hence $Q^\mu=0$ also for every component $\mu =0,\cdots,4$?

*Even if a straightforwardly apply the equation:
$$ Q^i = \partial_\nu T^{i \nu} = (\partial_\nu \rho) U^i U^\nu + \rho(\partial_\nu U^i)  U^\nu + \rho U^i(\partial_\nu  U^\nu ),$$
doesn't seems to yield something...
Is my first reasoning right ? Otherwise: can someone give me a hint ?
Thanks

A: If the dust does not interact with anything, momentum and energy are conserved. Otherwise, the general equation reads $$ \partial_0 T^{i0} = - \sum_{k=1}^3\partial_k T^{ik} +Q^i\:. $$
If you integrate it in a regular volume $\Omega$ at rest with the reference frame defined by the used Minkowskian coordinates, exploiting the theorm of divergence you have:
$$\frac{d}{dt}\int_\Omega T^{i0} d^3x = - \oint_{+\partial \Omega} T^{ik} n_k dS +\int_\Omega Q^i d^3x\:.$$
You see that the momentum in $\Omega$ changes in time in view of two independent  reasons. One is the flux of momentum across the boundary of $\Omega$ due to the dust itself, the other is due to external interactions.  $Q^i$ is nothing but the source of momentum, i.e., density of external force along the $x^i$ direction caused by the external interactions. If the dust does not interact with anything, then $Q^i=0$. Otherwise it can be re-written in terms of the external interaction.
For instance, if the dust is electrically charged, there is a charge density $\nu = e \rho$ (I am assuming that the mass is proportional to the charge, i.e., there is a unique type of charges in the continuum). In this case, up to signs and multiplicative constants depending on your conventions, you find the density of Lorentz' force:
$$Q_\mu = J^\sigma F_{\mu \sigma}$$
where $F_{\mu\sigma}$ is the electromagnetic tensor and $J^\mu = \nu V^\mu$.


text:
Q: Adding two distributions with proportional means and standard deviations I need to know the mean $\mu_z$ and standard deviation $\sigma_z$ of a log normal distribution $Z(\mu_z,\sigma_z)$ which is the sum of two other log normal distributions--$X(\mu_x,\sigma_x)$ and $Y(k\mu_x,k\sigma_x)$--each of which has the same mean and standard deviation up to a factor $k$.
$$Z(\mu_z,\sigma_z)=X(\mu_x,\sigma_x)+Y(k\mu_x,k\sigma_x)$$
$Z(\mu_z,\sigma_z)$ might be, for example, a distribution of net revenues, where $X(\mu_x,\sigma_x)$ and $Y(k\mu_x,k\sigma_x)$ are revenue and cost distributions, respectively.
I would think that $\mu_z$ and $\sigma_z$ are proportional to $\mu_x$ and $\sigma_x$, but not sure how to derive the constant of proportionality.


text:
Q: Creating scopes based on multiple models I'm trying to create a scope that's a little out of the ordinary.  I've got an app that deals with websites.  There's a model called "sites", which has_many pages.  The sites model has a column called homepage.  The list of pages for each site contains the homepage and additional pages (about, pricing, whatever).
I'd like to create two scopes for the pages model.  One identifies the homepage and the other identifies all the additional pages.  I was thinking of something like this.
my_homepage =  Site.find_by_id(self.site_id).homepage
scope :homepage, where(url: my_homepage)
scope :additional_pages, where(url != my_homepage)

Unfortunately, these don't work.  In fact, when I try to play with them in console, I can't.  I get this error.
(Object doesn't support #inspect)

Is there a smarter way to do this?

A: Try this :
scope :homepage, joins(:sites).where("sites.homepage = pages.url")
scope :additional_pages, joins(:sites).where("sites.homepage <> pages.url")


text:
Q: node js zerorpc crashes on windows 10 I have a windows 10 machine. First I installed ZMQ 4.0.4 from a binary file, then I ran npm install --save zerorpc. The installed zerorpc version is 0.9.7. Then when I add the line:
var zerorpc = require("zerorpc");

my app crashes and exits without printing any message at all. If run through nodemon it prints:
[nodemon] app crashed - waiting for file changes before starting...

This must be something specifically related to windows, but I don't know what. Thanks for your help.


text:
Q: Change the username ModelForm field to only accept letters and numbers? I have a ModelForm that uses Django's User model. I want to change the field to only accept letters and numbers. I can change some behaviours by using this to set fields to required (see code). So could I use it to change the username field to that?
def __init__(self, *args, **kwargs):
    super(UserForm, self).__init__(*args, **kwargs)
    self.fields['first_name'].required = True

How could I change the username field?

A: Yes you can. You might need a validator though. I haven't tried this but it might just work:
def __init__(self, *args, **kwargs):
    super(UserForm, self).__init__(*args, **kwargs)
    self.fields['first_name'].required = True

    validator = RegexValidator(r'^[a-zA-Z0-9]*$',
                               'You can only enter alphanumerics')
    self.fields['username'].validators = [validator]

A: You can define a clean_field method for the first name field
def clean_first_name(self):
    name = self.cleaned_data['first_name']
    if not name.isalnum():
        raise forms.ValidationError('Only alphanumeric')
    return super(UserForm, self).clean_first_name()


text: Q: Cannot reference assembly in Monodevelop I am using F# 4.1 with Monodevelop on Linux Mint 18 and for some reason I no longer can use the #r directive to reference a dll. No matter where I install/store the package and the permissions, I just get "... (file may be locked by F# Interactive process)" and I won't be able to "open" and use the component (I just get "The namespace ... is not defined"). I appreciate the help ...


text:
Q: Discovering public IP programmatically I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)
Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?
P.S. I'm planning on writing a short python script to do it

A: Whenever I wanted to do this, I would just scrape whatismyip.org. When you go to the site, it gives you your plain text public IP. Plain and simple.
Just have your script access that site and read the IP.
I don't know if you were implying this in your post or not, but it isn't possible to get your public IP from your own computer. It has to come from an external source.
2013 edit: This site returns an image now instead of text, so it's useless for this purpose.

A: As mentioned by several people, STUN is indeed the proper solution.

*

*a list of public STUN servers

*a free software STUN client

*The STUN standard
Here's a code example using pynat Python module:
>>> import pynat
>>> pynat.get_ip_info()
('UDP Firewall', '192.0.2.2', 54320)

A: EDIT: curlmyip.com is no longer available. (thanks maxywb)
Original Post:
As of writing this post, curlmyip.com works. From the command line:
curl curlmyip.com

It's a third-party website, which may or may not be available a couple years down the road. But for the time being, it seems pretty simple and to the point.

A: Your simplest way may be to ask some server on the outside of your network.
One thing to keep in mind is that different destinations may see a different address for you. The router may be multihomed. And really that's just where problems begin.

A: If the network has an UpNp server running on the gateway you are able to talk to the gateway and ask it for your outside IP address.

A: To get your external ip, you could make a dns query to an opendns server with the special hostname "myip.opendns.com":
from subprocess import check_output

ip = check_output(["dig", "+short", "@resolver1.opendns.com",
                   "myip.opendns.com"]).decode().strip()

On Windows, you could try nslookup.
There is no dns module in Python stdlib that would allow to specify custom dns server. You could use third party libraries e.g., Twisted to make the dns query:
from twisted.internet     import task # $ pip install twisted
from twisted.names.client import Resolver
from twisted.python.util  import println

def main(reactor):
    opendns_resolvers = [("208.67.222.222", 53), ("208.67.220.220", 53)]
    resolver = Resolver(servers=opendns_resolvers, reactor=reactor)
    # use magical hostname to get our public ip
    return resolver.getHostByName('myip.opendns.com').addCallback(println)
task.react(main)

Here's the same using dnspython library:
import dns.resolver # $ pip install dnspython

resolver = dns.resolver.Resolver(configure=False)
resolver.nameservers = ["208.67.222.222", "208.67.220.220"]
print(resolver.query('myip.opendns.com')[0])

Here's asyncio variant using aiodns library:
$ pipenv install aiodns
$ pipenv run python -m asyncio
...
>>> import asyncio
>>> import aiodns  # pip install aiodns
>>> resolver = aiodns.DNSResolver()
>>> resolver.nameservers = "208.67.222.222", "208.67.220.220"
>>> await resolver.query("myip.opendns.com", "A")
[<ares_query_a_result> host=192.0.2.2, ttl=0]

To get IPv6 address:
>>> resolver.nameservers = "2620:119:35::35", "2620:119:53::53"
>>> await resolver.query("myip.opendns.com", "AAAA")

A: This may be the easiest way. Parse the output of the following commands:

*

*run a traceroute to find a router that is less than 3 hops out from your machine.

*run ping with the option to record the source route and parse the output. The first IP address in the recorded route is your public one.

For example, I am on a Windows machine, but the same idea should work from unix too.
> tracert -d www.yahoo.com

Tracing route to www-real.wa1.b.yahoo.com [69.147.76.15]
over a maximum of 30 hops:

  1    <1 ms    <1 ms    <1 ms  192.168.14.203
  2     *        *        *     Request timed out.
  3     8 ms     8 ms     9 ms  68.85.228.121
  4     8 ms     8 ms     9 ms  68.86.165.234
  5    10 ms     9 ms     9 ms  68.86.165.237
  6    11 ms    10 ms    10 ms  68.86.165.242

The 68.85.228.121 is a Comcast (my provider) router. We can ping that:
> ping -r 9 68.85.228.121 -n 1

Pinging 68.85.228.121 with 32 bytes of data:

Reply from 68.85.228.121: bytes=32 time=10ms TTL=253
    Route: 66.176.38.51 ->
           68.85.228.121 ->
           68.85.228.121 ->
           192.168.14.203

Voila! The 66.176.38.51 is my public IP.
Python code to do this (hopefully works for py2 or py3):
#!/usr/bin/env python

def natIpAddr():
  # Find next visible host out from us to the internet
  hostList = []
  resp, rc = execute("tracert -w 100 -h 3 -d 8.8.8.8") # Remove '-w 100 -h d' if this fails

  for ln in resp.split('\n'):
    if len(ln)>0 and ln[-1]=='\r': ln = ln[:-1]  # Remove trailing CR
    if len(ln)==0: continue
    tok = ln.strip().split(' ')[-1].split('.') # Does last token look like a dotted IP address?
    if len(tok)!=4: continue
    hostList.append('.'.join(tok))
    if len(hostList)>1: break  # If we found a second host, bail

  if len(hostList)<2:
    print("!!tracert didn't work, try removing '-w 100 -h 3' options")
    # Those options were to speed up tracert results

  else:
    resp, rc = execute("ping -r 9 "+hostList[1]+" -n 1")
    ii = resp.find("Route: ")
    if ii>0: return resp[ii+7:].split(' ')[0]
  return none

def execute(cmd, showErr=True, returnStr=True):
  import subprocess
  if type(cmd)==str:
    cmd = cmd.split(' ')
  # Remove ' ' tokens caused by multiple spaces in str
  cmd = [xx for xx in cmd if xx!='']
  proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = proc.communicate()
  if type(out)==bytes:  # Needed for python 3 (stupid python)
    out = out.decode()
    try:
      err = err.decode()
    except Exception as ex:
      err = "!!--"+str(type(ex))+"--!!"

  if showErr and len(err)>0:
    out += err
  if returnStr and str(type(out))=="<type 'unicode'>":
    # Trying to make 'out' be an ASCII string whether in py2 or py3, sigh.
    out = out.encode()  # Convert UNICODE (u'xxx') to string
  return out, proc.returncode

if __name__ == "__main__":
  print("(This could take 30 sec)")
  print(natIpAddr())

Use it from the command line (on Windows) or from a python program:
import natIpAddr
myip = natIpAddr.natIpAddr()
print(myip)

A: I have made a program that connects to http://automation.whatismyip.com/n09230945.asp
it is is written in D an getting someone else to tell you what they see your ip as is probably the most reliable way:
/*
    Get my IP address
*/

import tango.net.http.HttpGet;
import tango.io.Stdout;

void main()
{
      try
      {
          auto page = new HttpGet ("http://automation.whatismyip.com/n09230945.asp");
          Stdout(cast(char[])page.read);
      }
      catch(Exception ex)
      {
          Stdout("An exception occurred");
      }
}

Edit python code should be like:
from urllib import urlopen
print urlopen('http://automation.whatismyip.com/n09230945.asp').read()

A: I like the ipify.org:

*

*it's free to use (even programmatically and allows even heavy traffic)

*the response contains only the IP address without any garbage (no need for parsing)

*you can also request a response in JSON

*works for both IPv4 and IPv6

*it's hosted in a cloud

*it's open-source

$ curl api.ipify.org
167.220.196.42

$ curl "api.ipify.org?format=json"
{"ip":"167.220.196.42"}

A: Targeting www.whatsmyip.org is rude. They plea not to do that on the page.
Only a system on the same level of NAT as your target will see the same IP.
For instance, your application may be behind multiple layers of NAT (this happens more as you move away from the US, where the glut of IPs are).
STUN is indeed the best method.
In general, you should be planning to run a (STUN) server somewhere that you
application can ask: do not hard code other people's servers.  You have to code
to send some specific messages as described in rfc5389.
I suggest a good read of, and related links.
http://www.ietf.org/html.charters/behave-charter.html
You may prefer to look at IPv6, and Teredo to make sure that you always have IPv6 access.
(Microsoft Vista makes this very easy, I'm told)

A: Duck Duck Go gives free access to their API according to their own page here:
https://duckduckgo.com/api
Here's the URL you hit if you want your IP address:
http://api.duckduckgo.com/?q=my+ip&format=json
That returns a JSON object. The Answer attribute has a human readable string with your ip address in it. Example:
{
    ...
    "Answer": "Your IP address is ww.xx.yyy.zzz in aaaaa(bbbbb)"
    ...
}

You could extract the ip address from that string by using split()[4], if you think that it's a safe assumption that this string won't ever change or you're willing to need to periodically fix it.
Alternatively, if you want to have a more future proof method, you could loop over everything returned by split() and return the first item that is an ip address. See here for validating IP addresses:
How to validate IP address in Python?

A: curl api.infoip.io - full details
curl api.infoip.io/ip - just the ip address
curl api.infoip.io/country - just the country name
... and more of the same
you can view the docs at http://docs.ciokan.apiary.io/

A: I'm sharing you my method of retrieving a server's public IP address without having to use external APIs (which is a security risk of course)
INTERFACE=`ip route get 8.8.8.8 | grep 8.8.8.8 | cut -d' ' -f5`
HOSTIP=`ifconfig $INTERFACE | grep "inet " | awk -F'[: ]+' '{ print $4 }'`

Or in python if you prefer:
import subprocess
public_ip = subprocess.check_output(["ifconfig `ip route get 8.8.8.8 | grep 8.8.8.8 | cut -d' ' -f5` | grep \'inet \' | awk -F'[: ]+' '{ print $4 }'"], shell=True)

It works like this:

*

*determines the best interface to reach the google dns server

*greps public IP from the ifconfig entry for that interface

A: Here are a few public services that support IPv4 and IPv6:

*

*curl http://icanhazip.com

*curl http://www.trackip.net/ip

*curl https://ipapi.co/ip

*curl http://api6.ipify.org

*curl http://www.cloudflare.com/cdn-cgi/trace

*curl http://checkip.dns.he.net
The following seem to support only IPv4 at this time:

*

*curl http://bot.whatismyipaddress.com

*curl http://checkip.dyndns.org

*curl http://ifconfig.me

*curl http://ip-api.com

*curl http://api.infoip.io/ip
It's easy to make an HTTP call programmatically. So all should be relatively easy to use, and you can try multiple different URLs in case one fails.

A: It's now quite cheap to host your own "serverless" API. All the major cloud providers have a service for this. For example, using Google Cloud Functions all it takes is:
exports.requestIP = (req, res) => {
    res.status(200).send(req.ip)
}

This approach is probably more reliable than using the public services above and you can add a long random string to the function's name to keep it private.

A: another cheeky way:
if your router has got the option to update it's web IP on DynDNS, you can get your own IP with something like:
IP=`resolveip -s myalias.dyndns-home.com`


text:
Q: Hibernate mapping: many to many with fk not having the same name? I'm trying to map a many-to-many relationship but my middle table is giving me trouble because the names don't match.
table1:
**userId**
firstname
lastname

table2:
**user_id** <= fk to table1.userId
x_id
create_date

table3:
x_id
private1
private2

Could anyone give me a pointer how I should map this?
<list name="xlist" table="table2" lazy="false">
                <key column="user_id"/>
                <index column="creatie_dt"/>
                <many-to-many column="x_id" class="X"/>
        </list>

Doesn't seem like the solution.

A: Switching to a set solved my problems.


text:
Q: Spatial Mapping of assets inside a building using ARKit I know my question sounds very broad but that's the nature of the problem statement I am working on. I am not looking for code samples (unless it helps explain the solution) but an explanation more from a technology perspective and challenges therein.
My company has indoor positioning figured out from a 3rd party vendor using beacons. Accuracy is about 3-5m which is acceptable for the kind of use case we have. What we also want to try and do is map few fixed assets in 3D space based on their 2D position (x,y) information that we receive from the indoor positioning solution. We would like to use ARKit for doing the spatial mapping of these assets in AR view. What we have with us in order to realise a solution like this is real-time position information of the user in (x, y), real-time azimuth as observed on the user's device hence giving the user's bearing and as stated earlier the position information in (x, y) of the fixed assets in the building.
I would like to know, for doing spatial mapping of these assets in 3D space (assuming a fixed elevation for these assets), would the data that we have suffice? What else does ARKit need in order to accurately map these assets in AR view? I have done some reading on AR sessions and world tracking configurations in ARKit and not very sure if we should be using world alignment of gravity or gravity/heading? Should we be converting the x, y coordinates as received from the indoor positioning software to lat, long?
Any pointers towards the correct approach would be much appreciated. And sorry again if the questions sound too broad, I will try to be as specific in my responses to your questions if need be.
Thanks,
Myra


text:
Q: Why does Django add "IS NULL" here? Consider the following model:
class ProductCountry(models.Model):
    product = models.OneToOneField('Product')
    country_code = models.CharField(max_length=2)
    count = models.IntegerField()

And an expression print(ProductCountry.objects.filter(product__product_id=request.GET.get('product').query).
Why does it give me the following?
SELECT "precomputed_product_country"."id", "precomputed_product_country"."product_id", "precomputed_product_country"."country_code", "precomputed_product_country"."count" FROM "precomputed_product_country" WHERE "precomputed_product_country"."product_id" IS NULL

A: Apparently I didn't have a product key in GET, as user "soon" pointed out. Fixing the request solved the problem.


text:
Q: loop thru folders using linq I am trying to loop though directories and show the files on a webpage.
I have managed to find a script, but it doesnt do the loop
any advice? At the moment I can only view whats on the current folder
thanks in advance
Hesh
Controller
 public ActionResult Index()
    {

        DirectoryInfo assetsDirectory = null;
        FileInfo[] files = null;

            //string salesFTPPath = dirPath;
            assetsDirectory = new DirectoryInfo( Server.MapPath("~/assets/img"));
            files = assetsDirectory.GetFiles();
            Response.Write(assetsDirectory);

        var MaterialFiles = (from c in files
                          select c);

        return View(MaterialFiles);

    }

View
@model IEnumerable<FileInfo>

 @foreach (var item in Model) {

              @item.DirectoryName - @item.Name.ToString()

    }

A: Using LINQ:
FileList.Select(f => f.FullName).ToArray();

Alternatively, using Directory you can get filenames directly.
string[] fileList = Directory.GetFiles(DirPath, "*.*",
                                       SearchOption.AllDirectories);


text:
Q: A less complex solution maybe If $a$ and $b$ are the roots of the equation $x^2-x+1=0$, then $a^{2009}+b^{2009}$ is
One way to solve this is to multiply the equation by $x+1$ and obtain the cubic $x^3+1=0$ and then the roots will be $-1$, $-w$, $-w^{2}$ where $w$ is the cube root of unity, so $a$ and $b$ will be equal to $-w$, and $-w^{2}$.
I wanted to solve this using a method which did not involve complex numbers but couldn't think of any, can anybody please help me.

A: $$x^2 - x + 1 = 0 \implies x^3 - x^2 + x = 0$$
But $$x^2 - x = -1$$
(using the quadaratic again)
Thus $$x^3 = -1$$
So $a^3 = -1$ and $b^3 = -1$.
Thus $$a^{2009} + b^{2009} = a^{3 \cdot 669} a^2 + b^{3 \cdot 669} b^2 = -a^2 - b^2 = 2ab - (a + b)^2 $$
($2007 = 3\cdot669$)
But $a+b = 1$ (sum of roots of quadratic)
and $ab = 1$ (product of roots of quadratic)
Thus the answer is $$1$$

A: Take root $a$ for example and note that $\,a^2-a+1=0\,$ since it's a root of the equation. Then:
$$a^2 = a-1 \tag{1}$$
$$a^2 - a = -1 \tag{2}$$
Multiply $(1)$ by $\,a \ne 0\,$ and use $(2)\,$ to get:
$$
a^3 = a^2-a = -1
$$
It follows that $a^{2009}=\left(a^3\right)^{669} \cdot a^2=(-1)^{669} \cdot a^2=-a^2\,$. Same goes for b, so the sum is:
$$-a^2-b^2=-a+1-b+1=-(a+b)+2=1$$

A: You can't choose the roots of a polynomial . There may be no roots in the real numbers.  if you look at the equation you can get $$x^2-x=-1 \implies (x-1)x=-1 \implies \text {x is negative or x-1 is negative}$$ if x is negative so is x-1 so that's out, as a negative times a negative is a positive. x-1 being negative shows that x is in the half open interval from 0 to 1, x=0 implies 0=-1  , which is false. x=1 causes both x and x-1 to be non-negative (slightly different from positive, and x=1 wouldn't be in the half open interval). if x is rational then we have that the absolute values of x and x-1 are flipped fractions ( aka $x={a\over b}, x-1 = -{b\over a}$). otherwise the solutions would have to be irrational ( which then begs the question can two irrational numbers multiplied together equal a rational). if this last ditch effort fails ( admittedly I don't know) then there would be no solutions in the reals ( the set union of the rationals and irrationals)

A: $$a^{2009}+b^{2009}=a^2(a^3)^{669}+b^2(b^3)^{669}=-(a^2+b^2)=-((a+b)^2-2ab)=-(1-2)=1$$

A: Let $k_n = a^n+b^n$ for integer $n$. Consider the proposition

$$k_n = a^n + b^n = 2\cos\frac{2\pi n}6$$

For $n = 0$, $a^0 + b^0 = 2 = 2\cos 0$.
For $n = 1$, $a + b = 1 = 2\cos \frac{2\pi}6$.
Assume the proposition is true for $m-1$ and $m$, where $m\ge 1$ is an integer,
$$k_i = a^i + b^i = 2\cos \frac{2\pi i}6,\quad i = m-1, m$$
For $n = m + 1$,
$$\begin{align*}
a^{m+1} + b^{m+1} &= a(a^m+b^m) + b(a^m+b^m) - ab^m - a^mb\\
&= (a+b)(a^m+b^m) - ab(a^{m-1}+b^{m-1})\\
&= k_m - k_{m-1}\\
&= 2\cos\frac{2\pi m}6 - 2\cos\frac{2\pi(m-1)}6\\
&= 2\cdot(-2)\sin\left(\frac{2\pi}{6}\cdot\frac{2m-1}{2}\right)\sin\left(\frac{2\pi}{6}\cdot\frac{1}{2}\right)\\
&= -2\sin\left[\frac{2\pi}{6}\left(m -\frac{1}{2}\right)\right]\\
&= 2\cos\left[\frac {2\pi}6\left(m -\frac{1}{2}\right) +\frac{2\pi}{4}\right]\\
&= 2\cos\left[\frac {2\pi}6\left(m -\frac{1}{2}\right) +\frac{2\pi}{6}\cdot\frac{3}{2}\right]\\
&= 2\cos\frac {2\pi(m+1)}6
\end{align*}$$
So the proposition is true by induction for non-negative integers $n$, and
$$a^{2009}+b^{2009} = 2\cos\frac{2\pi\cdot2009}6 = 2\cos\frac{2\pi\cdot5}6 = 1$$


text:
Q: How do you use "WHERE x IN y" clauses with clojure/java.jdbc? I am trying to get a simple DB query working, but I can't get clojure/java.jdbc to select from an IN clause.
The code looks like this:
(sql/with-connection db
  (sql/with-query-results rows
    ["select  f.name        name
          ,   f.id          file_id
      from    FileCategory  fc
      join    File          f
          on  fc.file       = f.id
      where   fc.category   in ?
      having  count(1)      >= ?"
     [1 2]    ; This is the bit which does not work.
              ; I have tried (to-array) and (set) too
     2]
    (into [] rows)))

Any Ideas as to how I may pass the set to the query?
Running the query directly under mysql I get no problems:
mysql> select f.name, f.id from FileCategory fc join File f on fc.file = f.id where fc.category in (1, 2) having count(1) >= 2;
+-----------+----+
| name      | id |
+-----------+----+
| some name |  1 |
+-----------+----+
1 row in set (0.02 sec)

mysql>

In case it makes a difference I'm using: org.clojure/clojure 1.4.0, org.clojure/java.jdbc 0.2.3 and mysql/mysql-connector-java 5.1.6.

A: Try this:
(sql/with-connection db
  (sql/with-query-results rows
    ["select  f.name        name
          ,   f.id          file_id
      from    FileCategory  fc
      join    File          f
          on  fc.file       = f.id
      where   fc.category   in (?, ?)
      having  count(1)      >= ?"
     1 2 2]
    (into [] rows)))

A: If you use SQL you must generate a SQL query with the correct number of '?' unfortunately.
You may find that working at a higher level of abstraction works better. eg. your query in korma looks like this:
(defentity file)
(defentity filecategory)

(def categories ["movie" "tv" "news"])

(as-sql (select file
       (fields :name :file_id)
       (join filecategory (= :file.id :filecategory.file))
           (where { :filecategory.category [in categories]} )
       (having (> (sqlfn :count 1) 1))))

; SELECT `file`.`name`, `file`.`file_id` FROM `file` LEFT JOIN
;        `filecategory` ON `file`.`id` = `filecategory`.`file`
;         WHERE (`filecategory`.`category` IN (?, ?, ?))
;         HAVING COUNT(?) > ?  ::  [tv movie news 1 1]

You can tidy this up further by moving the FK declarations into the defentity calls if desired.


text:
Q: PHP loop through array and check dates I have a form in my app. This form consists of 2 textfields type='date'. Now, when two dates are given, the dates are send to a PHP-script that translates the dates with strtotime.
The PHP-script makes a connection to a mySQL database that returns a result with requests. I would like to loop through all requests and check if the date of the request is BETWEEN the two dates that where sent by the form.
What happens now:
$sql = "SELECT * FROM Requests";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

if($result) {

foreach ($result as $row){
    $return[]=array('employeeid'=>$row['employeeid']
                    'id'=>$row['id'],
                    'startdate'=>$row['startdate'],
                    'enddate'=>$row['enddate'],
                    'type'=>$row['type'],
                    'reason'=>$row['reason']);
}

header('Content-type: application/json');
echo '' . json_encode($return) .'';
return true;

} else {
    return false;
}

The code above generates a perfect json-file with the requests. But as I mentioned I would like to check whether the startdate of the requests above is between the two dates that are send by the form.
Something like this:
if (($request_startdate >= $startdate) && ($request_startdate <= $enddate)) {
  //generate array with the requests
} else {
  //no requests between dates.
}

But how to loop through the requests and check the startdate?
Thanks in advance.
Jan

A: You are taking the hard way, it's easier to add a where statment to your select query:
I assume that your form have two fields named date1, date2
$sql = "SELECT * FROM Requests where startdate>:date1 and enddate<:date2";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(':date1',$_POST['date1'],PDO::PARAM_STR);
    $stmt->bindValue(':date2',$_POST['date2'],PDO::PARAM_STR);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

A: Convert your string inputs to DateTime and format it to ISO date format (or at least make sure they are in a format that mySQL accepts)
$sdt = DateTime::createFromFormat('format of your input', $request_startdate);
$edt = DateTime::createFromFormat('format of your input', $request_enddate);

Modify your sql to query only the rows that you want to use:
SELECT * FROM Requests
WHERE startdate <= :sdt AND :edt >= :edt

Then bind your parameters (see php doc):
$stmt->bindParam(':sdt', $sdt->format('YYYY-mm-dd 00:00:00'), PDO::PARAM_STR);
$stmt->bindParam(':edt', $edt->format('YYYY-mm-dd 23:59:59'), PDO::PARAM_STR);


text:
Q: Involution $\Rightarrow$ Hermitian & Unitary I've been learning about unitary diagonalization and this question has been on my mind for a while, unanswered by the text I'm using.
Would it be true to say that if a square matrix represents an involution, i.e. $A^2=I$ (or $A=A^{-1}$), then it is Hermitian ($A=A^*$) and Unitary ($A^{-1}=A^*$). The reverse implication is definitely true, but is it an equivalence?
If so, then why? And if not, could it be true for real matrices? (Involution $\Rightarrow$ Symmetric & Orthogonal)
Thanks for help!

A: First, let $A \in M_n(\mathbb{C})$, and suppose that $A^2 = I$. I claim that $A$ is a self-adjoint unitary if and only if $A$ is normal. On the one hand, if $A$ is self-adjoint and unitary, then it is trivially normal. On the other hand, suppose that $A$ is normal. Then by the finite-dimensional spectral theorem, $A = U \Delta U^\ast$ for $\Delta$ a diagonal matrix (i.e., with diagonal entries the eigenvalues of $A$ counted with multiplicity), and $U$ a unitary. Since $A^2 = I$, it therefore follows that $\Delta^2 = I$, so that the diagonal entries of $\Delta$ (viz, eigenvalues of $A$) are $\pm 1$. Thus, $\Delta$ is a self-adjoint unitary, so that since $A = U \Delta U^\ast$ for $U$ unitary, $A$ too is a self-adjoint unitary.
Let us now see that the normality condition is not redundant. Consider
$$
 A = \begin{pmatrix} 1 & 1\\ 0 & -1\end{pmatrix},
$$
and observe that
$$
 A^2 = \begin{pmatrix} 1 & 1\\ 0 & -1\end{pmatrix}\begin{pmatrix} 1 & 1\\ 0 & -1\end{pmatrix} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} = I_2.
$$
However, $A$ is neither self-adjoint nor unitary, and indeed
$$
 A A^\ast = \begin{pmatrix} 1 & 1\\ 0 & -1\end{pmatrix}\begin{pmatrix} 1 & 0\\ 1 & -1\end{pmatrix} = \begin{pmatrix} 2 & -1 \\ -1 & 1 \end{pmatrix},\\
 A^\ast A = \begin{pmatrix} 1 & 0\\ 1 & -1\end{pmatrix}\begin{pmatrix} 1 & 1\\ 0 & -1\end{pmatrix} = \begin{pmatrix} 1 & 1\\ 1 & 2 \end{pmatrix} \neq A A^\ast,
$$
as expected.
Let us now consider $A \in M_n(\mathbb{R})$, and suppose that $A^2 = I$. I claim that $A$ is symmetric and orthogonal if and only if $A^T A = A A^T$. By viewing $A$ as a complex matrix, we see that $A$ is self-adjoint and unitary if and only if $A$ is normal; since $A$ is real, this means that $A$ is symmetric and orthogonal if and only if $A^T A = A A^T$. Once more, the explicit example above shows that the "normality" condition is not redundant.

A: If $A^2=I$, you know that $A$ is diagonalizable and its eigenvalues are $\pm 1$. To find a counterexample, an idea is to take $A= P \left( \begin{array}{cc} 1 & 0 \\ 0 & -1 \end{array} \right) P^{-1}$, where $P$ is not orthogonal. For example, $P= \left( \begin{array}{cc} 1 & 2 \\ 0 & 1 \end{array} \right)$.
And indeed, $A= \left( \begin{array}{cc} 1 & -4 \\ 0 & -1 \end{array} \right)$ is a counterexample.


text:
Q: Fixing Syntax For using SQL insert in go I am getting an error when I try to use ? arguments when using the go sql library.
Whe I do something like:
_, err = db.Query(
    `INSERT INTO user_account (username, password_hash) VALUES ("username", 'passwordhash');`,

everything works fine.
But when I do the following:
_, err = db.Query(
    `INSERT INTO user_account (username, password_hash) VALUES (?, 'passwordhash');`,
    `'username'`)

I get the error:
pq: syntax error at or near ","

How can I fix this error? I suspect it has something to do with the single quotes around the variables.
If it matters, I'm using postgreq with the pq driver.


text:
Q: Group by a factor and then summarise a different variable I have data in this format, where samples are in groups (in this example A or B), have a numerical quantity and a quality score (which is a factor).
I would like to summarise the qual_score by each group_name.
Example Data:
group_name <- rep(c("A","B"),5)
qual_score <- c(rep("POOR",4),rep("FAIR",1),rep("GOOD",5))
quantity <- 5:14

df <- data.frame(group_name, qual_score, quantity)

> df
   group_name qual_score quantity
1           A       POOR        5
2           B       POOR        6
3           A       POOR        7
4           B       POOR        8
5           A       FAIR        9
6           B       FAIR       10
7           A       GOOD       11
8           B       GOOD       12
9           A       GOOD       13
10          B       GOOD       14

Desired Output:
desired_output <- data.frame(c("2","2"),c("1","0"),c("2","3"))
colnames(desired_output) <- c("POOR", "FAIR", "GOOD")
rownames(desired_output) <- c("A", "B")
desired_output

  POOR FAIR GOOD
A    2    1    2
B    2    0    3

I can do summary() of qual_score for the entire dataframe:
> summary(df$qual_score)
FAIR GOOD POOR
   2    4    4

And can group_by() to summarise mean(quantity) according to each group:
> df %>%
+     group_by(group_name) %>%
+     summarise(mean(quantity))
# A tibble: 2 x 2
  group_name `mean(quantity)`
  <fct>                 <dbl>
1 A                         9
2 B                        10

But when I try to use group_by() with summary() I get a warning and the following output:
> df %>%
+     group_by(group_name) %>%
+     summary(qual_score)
 group_name qual_score    quantity
 A:5        FAIR:2     Min.   : 5.00
 B:5        GOOD:4     1st Qu.: 7.25
            POOR:4     Median : 9.50
                       Mean   : 9.50
                       3rd Qu.:11.75
                       Max.   :14.00
Warning messages:
1: In if (length(ll) > maxsum) { :
  the condition has length > 1 and only the first element will be used
2: In if (length(ll) > maxsum) { :
  the condition has length > 1 and only the first element will be used

A: library(dplyr)

df %>%
  group_by(group_name) %>%
  select(-quantity) %>%
  table()

#>           qual_score
#> group_name FAIR GOOD POOR
#>          A    1    2    2
#>          B    0    3    2

If you want a solution completely in tidyverse:
library(dplyr)
library(tidyr)

df %>%
  group_by(group_name, qual_score) %>%
  tally() %>%
  spread(qual_score, n, fill=0)

#> # A tibble: 2 x 4
#> # Groups:   group_name [2]
#>   group_name  FAIR  GOOD  POOR
#>   <fct>      <dbl> <dbl> <dbl>
#> 1 A              1     2     2
#> 2 B              0     3     2


text:
Q: How to right-align a flip toggle switch in jQuery mobile How can a flip switch be right aligned within a jQuery mobile list view?
Here's what I'm working with:  http://jsfiddle.net/bthj/ry799/
The switch can be seen there clinging to the label at left, but I would like to have it on the right to make better use of space on a narrow mobile screen.
Setting "float:right" on the div.ui-slider around the switch doesn't work, the switch then floats out of the list view.

A: This should do the trick. Live example: http://jsfiddle.net/tw16/ry799/1/
.ui-li .ui-btn-inner a.ui-link-inherit, .ui-li-static.ui-li {
    display: block;
    padding: 0.9em 75px 0.9em 15px;
}
div.ui-slider-switch {
    position: absolute;
    right: 0;
    width: 44%;
}

A: div.ui-slider-switch {
 float:right; }


text:
Q: $a_{n}=1+\frac{1}{2}+\cdots+\frac{1}{n}-\log(n)$ converges
Prove that $$a_{n}=1+\frac{1}{2}+\cdots+\frac{1}{n}-\log(n)\  \text{ converges.}$$

any hints.
I am trying to upper and lower bound it by a sequence that converges to the same number.

A: Hint:
$$
\log k - \log(k-1) = \int_{k-1}^k \frac{dt}t$$
detail:
$$
\log k - \log(k-1) = \int_{k-1}^k \frac{dt}t
\\
\int_k^{k+1}\frac{dt}t <\frac 1k < \int_{k-1}^k \frac{dt}t
\\
\log(n+1) - \log 2 < \sum_{k=2}^n \frac 1k <\log n
\\
1-\log 2<1-\log 2 + \log(n+1)-\log n < \sum_{k=1}^n \frac 1{k} -\log n < 1
$$so the sequence is bounded.
$$
a_{n}-a_{n-1} = \frac 1n  - \log{n}+ \log(n-1)
=\frac 1n - \int_{n-1}^n\frac{dt}t<0
$$so the sequence is monotonic. Hence it is convergent.
another solution:
Let $$b_n = 1+\frac 12+\cdots+\frac 1n -\log(n+1)$$
Then $$b_n - b_{n-1} = \frac 1n  - \log(n+1)+ \log n >0$$ so $(b_n)$ is increasing.
$$
a_n - b_n = \log(n+1) - \log n \to 0
$$
so, as $(a_n)$ is decreasing,
$(a_n)$ and $(b_n)$ are both convergent.

A: $$
\begin{align}
& \Big( \log 1 - \log 2 \Big) + \Big( \log 2 - \log 3 \Big) + \Big( \log 3 - \log 4 \Big) + \cdots\\
& \cdots+\Big( \log(n-3) - \log (n-2) \Big) +\Big( \log(n-2) -\log(n-1) \Big)+\Big(\log(n-1)-\log n\Big)
\end{align}
$$
Everything above cancels except the first term and the last, and the first term, $\log 1$, is $0$, so the whole thing adds up to $-\log n$.
If we now add $1/n$ to the last term, and $1/(n-1)$ to the term before that, and $1/(n-2)$ to the term before that, and so on, we will add $1/2$ to the first term, and then just add $1$ and we've got just your sum.
The typical term is $\log k - \log (k+1) + \dfrac 1 {k+1}$.  This is the same as
$$
\frac1{k+1} - \left( \log(k+1) - \log k\right) = - \left(\int_k^{k+1} \frac{dx}{x} - \frac 1 {k+1} \right).
$$
Next:
$$
\begin{align}
& \int_k^{k+1} \frac{dx}{x} - \frac 1 {k+1} = \int_0^1 \frac{dx}{x+k} - \frac{1}{1+k} \\[8pt]
= {} & \text{area of that part of the square $0<x<1,\  0<y<1$ that is} \\
& \text{above the line $y=1/(k+1)$ and below the curve $y=1/(x+k)$.}
\end{align}
$$
Now notice that those parts of the square do not overlap!!  That means they're total area must be no bigger than the area of the whole square, i.e. their sum converges.


text:
Q: Теория вероятности и математическая статистика: задача о билетах Преподаватель предложил на досуге подумать над следующей задачей:
Есть n учеников. Ученик выучил m билетов. Всего билетов больше, чем n.
Найти вероятность того, что если он зайдет в аудиторию k-ым, то ему попадется билет, который он выучил.

A: Эххх... представь себе, что ты расписАл ВСЕ варианты расположения билетов в "колоде". В виде офигительной таблицы из X! строк, где X - количество билетов. Соответственно, колонка номер k этой таблицы отображает для каждого отдельного варианта номер билета, который возьмёт k-й студент.
Надо ли объяснять, что если вырезать из этой таблицы всю эту колонку и посчитать, какое количество записей каждого номера вопросов в ней присутствует, то обнаружится, что оно одинаково для всех номеров?
Надо ли объяснять, что описанное выше никак не зависит от того, какую из колонок мы вырежем?
Надо ли объяснять, что результат не зависит от того, что мы какие-то колонки поменяем местами (ну скажем чтобы они располагались в том порядке, в каком студенты тащат билеты из пачки)?
А в общем, вероятность равна A/B, где A - количество выученных билетов, а B - их общее количество. А от количества студентов и того, каким пойдёт конкретный студент, эта вероятность в принципе не зависит.

A: Вероятность будет одна и та же - потому что предыдущие студенты будут тянуть билеты с точно такой же вероятностью :) Так что вероятность должна быть одна и та же - m/N, где N - количество билетов.
Если не верите - вот эксперимент. Выученные билеты - от 0 до m-1. Билеты перемешиваются. Если k-й билет меньше m - это и есть успех.
Почему эта модель адекватна - подумайте сами.
Код привожу, результаты смотрите тут. Можете поэкспериментировать самостоятельно...
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

double experiment(int n, int m, int k, int count = 10000)
{
    int succ = 0;
    vector<int> b;
    for(int i = 0; i < n; ++i)
        b.push_back(i);
    for(int j = 0; j < count; ++j)
    {
        random_shuffle(b.begin(), b.end());
        if (b[k] < m) succ++;
    }
    return double(succ)/count;
}

int main()
{
    for(int k = 0; k < 30; ++k)
    {
        cout << "k = " << setw(2) << k << " Success = " << setw(10) << experiment(50,10,k) << endl;
    }
}