text:
Q: Does C# 7 have array/enumerable destructuring? In JavaScript ES6, you are able to destructure arrays like this:
const [a,b,...rest] = someArray;

where a is the first element in the array, b is the second, and rest is an array with the remaining elements.
I know in C#7 that you can destructure tuples during assignment, but could not find anything related to destructuring arrays/enumerables like this:
var (a,b) = someTuple;

I have an IEnumerable where I need the first and second elements as variables, and I need the rest of the elements as another IEnumerable. I have a solution, but feel that destructuring will look cleaner.

A: It turns out not only tuples can be deconstructed but any type which has Deconstruct static (or extension) method with matching signature. Doing deconstruction correctly for IEnumerable is not trivial (see library suggested by David Arno in this answer), so let's see how it works with simple IList instead (implementation is irrelevant, this one is for example and of course can be better/different):
public static class Extensions {
    public static void Deconstruct<T>(this IList<T> list, out T first, out IList<T> rest) {
        first = list.Count > 0 ? list[0] : default(T); // or throw
        rest = list.Skip(1).ToList();
    }

    public static void Deconstruct<T>(this IList<T> list, out T first, out T second, out IList<T> rest) {
        first = list.Count > 0 ? list[0] : default(T); // or throw
        second = list.Count > 1 ? list[1] : default(T); // or throw
        rest = list.Skip(2).ToList();
    }
}

Then (after adding relevant using statements if necessary) you can use exactly the syntax you want:
var list = new [] {1,2,3,4};
var (a,rest) = list;
var (b,c,rest2) = list;

Or you can chain deconstruction like this (because last returned value can itself be deconstructed):
 var (a, (b, (c, rest))) = list;

With last version, you can deconstruct to any number of items using single Deconstruct method (that one which returns first item and the rest).
For real usage for IEnumerables, I'd suggest to not reimplement the wheel and use David Arno's library mentioned in this answer.

A: In C# you will need to write your own, like this one I'm using:
public static class ArrayExtensions
    {
        public static void Deconstruct<T>(this T[] array, out T first, out T[] rest)
        {
            first = array.Length > 0 ? array[0] : default(T);
            rest = array.Skip(1).ToArray();
        }

        public static void Deconstruct<T>(this T[] array, out T first, out T second, out T[] rest)
            => (first, (second, rest)) = array;

        public static void Deconstruct<T>(this T[] array, out T first, out T second, out T third, out T[] rest)
            => (first, second, (third, rest)) = array;

        public static void Deconstruct<T>(this T[] array, out T first, out T second, out T third, out T fourth, out T[] rest)
            => (first, second, third, (fourth, rest)) = array;

        public static void Deconstruct<T>(this T[] array, out T first, out T second, out T third, out T fourth, out T fifth, out T[] rest)
            => (first, second, third, fourth, (fifth, rest)) = array;

// .. etc.
    }

Then simply do:
var (first, second,_ , rest) = new[] { 1, 2, 3, 4 }

A: If you want a solution that is fully integrated with the C# language features, use Evk's answer, which hides some of the implementation detail. If you don't care about that, you can use either of the answers.

To my knowledge there is not. However, it is not very hard to make something similar.
What about an extension method like this:
public static class EX
{
    public static void Deconstruct<T>(this T[] items, out T t0)
    {
        t0 = items.Length > 0 ? items[0] : default(T);
    }

    public static void Deconstruct<T>(this T[] items, out T t0, out T t1)
    {
        t0 = items.Length > 0 ? items[0] : default(T);
        t1 = items.Length > 1 ? items[1] : default(T);
    }
}

And you can use it like so:
int[] items = { 1, 2 };

items.Deconstruct(out int t0);

The drawback is that you need an extension method per number of items to return. So if you have more than a few variables to return, this method might not be very useful.
Note that I left out checking the length, and related stuff, but you understand what needs to be done I guess.

A: What you are describing is generally known in functional languages as "cons", which often takes the form:
let head :: tail = someCollection

I did propose this be added to C#, but it didn't receive very favourable feedback. So I wrote my own, which you can use via the Succinc<T> nuget package.
It uses deconstruction to achieve that splitting of the head and tail of any IEnumerable<T>. Deconstructs can be nested, so you can use it to extract multiple elements in one go:
var (a, (b, rest)) = someArray;

This potentially could provide the functionality you are after.

A: There is no special syntax for it in the language.
You could leverage the tuple syntax, though, to arrive at this
class Program
{
    static void Main(string[] args)
    {
        int[] ints = new[] { 1, 2, 3 };

        var (first, second, rest) = ints.Destruct2();
    }
}

public static class Extensions
{
    public static (T first, T[] rest) Desctruct1<T>(this T[] items)
    {
        return (items[0], items.Skip(1).ToArray());
    }

    public static (T first, T second, T[] rest) Destruct2<T>(this T[] items)
    {
        return (items[0], items[1], items.Skip(2).ToArray());
    }
}

(which should be extended with error handling for obvious error scenarios before being used in production code).

A: To extend the solutions hinted by other contributors, I provide an answer that uses IEnumerable. It might not be optimized but it works quite well.
public static class IEnumerableExt
{
    public static void Deconstruct<T>(this IEnumerable<T> seq, out T first, out IEnumerable<T> rest)
    {
        first = seq.FirstOrDefault();
        rest = seq.Skip(1);
    }

    public static void Deconstruct<T>(this IEnumerable<T> seq, out T first, out T second, out IEnumerable<T> rest)
        => (first, (second, rest)) = seq;

    public static void Deconstruct<T>(this IEnumerable<T> seq, out T first, out T second, out T third, out IEnumerable<T> rest)
        => (first, second, (third, rest)) = seq;

    public static void Deconstruct<T>(this IEnumerable<T> seq, out T first, out T second, out T third, out T fourth, out IEnumerable<T> rest)
        => (first, second, third, (fourth, rest)) = seq;

    public static void Deconstruct<T>(this IEnumerable<T> seq, out T first, out T second, out T third, out T fourth, out T fifth, out IEnumerable<T> rest)
        => (first, second, third, fourth, (fifth, rest)) = seq;
}

Then just use these deconstructors like this:
var list = new[] { 1, 2, 3, 4 };
var (a, b, rest1) = list;
var (c, d, e, f, rest2) = rest1;
Console.WriteLine($"{a} {b} {c} {d} {e} {f} {rest2.Any()}");
// Output: 1 2 3 4 0 0 False

A: Really quick: No.
C# does not support destructuring for Arrays yet.
Currently, I cannot find any information of this on the roadmap, either. Seems like there will be a lot of waiting involved until we get this syntactic sugar by default.
As @Nekeniehl added in the comments, it can be implemented though: gist.github.com/waf/280152ab42aa92a85b79d6dbc812e68a

A: You need to be slightly careful if you want to handle infinite streams, as from a while(true) yield return block for example. In that case, you can't practically check the length of the stream to make sure you have enough items to populate the requested tuple.
If your source is actually infinite a combination of the above approaches would work -- rather than counting the length of the IEnumerable<T>, just check that it has any content at all, and then implement the multi-parameter overloads in terms of the single-parameter overload:
    public static void Deconstruct<T>(this IEnumerable<T> list, out T head, out IEnumerable<T> tail)
    {
        head = list.First(); // throws InvalidOperationException for empty list

        tail = list.Skip(1);
    }

    public static void Deconstruct<T>(this IEnumerable<T> list, out T head, out T next, out IEnumerable<T> tail)
    {
        head = list.First();

        (next, tail) = list.Skip(1);
    }

The critical question is what you want to happen when the stream runs out. The code above will throw an InvalidOperationException. Returning default<T> might not be what you want instead. In a functional context you'd typically be doing a cons, and splitting the stream into a single head an stream tail - and then checking for empty streams outside of your cons implementation (so outside of the Deconstruct method).

A: I tried to make it more shorter and performance effective. So I avoided the calling of IEnumerable<T>.ToList() method, which would be expensive if we had a large list.
public static void Deconstruct<T>(this IEnumerable<T> list, out T first, out IEnumerable<T> rest) {
    first = list.FirstOrDefault();
    rest = list.Skip(1);
}

public static void Deconstruct<T>(this IEnumerable<T> list, out T first, out T second, out IEnumerable<T> rest) {
    first = list.FirstOrDefault();
    (second, rest) = list.Skip(1);
}

public static void Deconstruct<T>(this IEnumerable<T> list, out T first, out T second, out T third, out IEnumerable<T> rest) {
    first = list.FirstOrDefault();
    (second, third, rest) = list.Skip(1);
}

A: We have it in C# 11 now as part of list patterns.
Usage examples:
List<int> list = new() { 1, 2, 3 };

// Here array must contain exactly 3 elements to match
// taking first element, disregarding last 2 ("_" disregards a single element)
if (list is [var firstElm, _, _])
{
  // Do stuff with firstElm
}

// Do stuff with firstElm here too

Or
public void SomeFunc(int[] arr)
    {
        // guard
        if (arr is not [var a, var b, var c]) return;

        // act
        a = b - c;
    }

Or
Queue<int[]> queue = new ();
queue.Enqueue(new int[] { 1, 2, 3 });

// Here matching an array with length >= 2
// and taking first 2 elements (".." matches and disregards 0 or more elements)
// Arrays with less then 2 elements won't match
while (queue.TryDequeue(out var arr) && arr is [var a, var b, ..])
{
  // Do stuff with a & b
}

See language reference on topic for full info.
As what such code is lowered to.
Or more pattern examples like
[var a, .., var y, _] for first and (second to last) elements
[_, >= 0, .., >=0, var z] to check & assign simultaneously
[.., [.., var zz]] to match last element of last subarray

PS Atm using stuff mentioned in first 2 examples is plenty for me.
Would be nice to have optional elements, but this already saves a lot of boilerplate.


text: Q: Classification of groups of order $2p^3$ and $2p^4$. Where can I find these two result? And how to charicterize $Z_2$-extension of an Abelian group? If not, can we conunt the number of $Z_2$-extension of an Abelian group? Thank you for your help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with sklearn k nearest neighbors I wonder if there is a way to force sklearn NearestNeighbors algorithm, to take into account the order of a point in the input array, when there are duplicate points.
To illustrate:
>>> from sklearn.neighbors import NearestNeighbors
>>> import numpy as np

X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X)
distances, indices = nbrs.kneighbors(X)
indices
>>>> array([[0, 1],
     [1, 0],
     [2, 1],
     [3, 4],
     [4, 3],
     [5, 4]])

Because the query set matches the training set, the nearest neighbor of each point is the point itself, at a distance of zero. If however, I allow for duplicate points in X, the algorithm, understandably, does not distinguish between the duplicates:
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1],[3, 2],[-1,-1],[-1,-1]])
nbrs = NearestNeighbors(n_neighbors=2, algorithm='auto').fit(X)
distances, indices = nbrs.kneighbors(X)
indices
>>>> array([[6, 0],
   [1, 0],
   [2, 1],
   [3, 4],
   [4, 3],
   [5, 4],
   [6, 0],
   [6, 0]])

Ideally, I would like the last output to be something like:
    >>>> array([[0, 6],
   [1, 0],
   [2, 1],
   [3, 4],
   [4, 3],
   [5, 4],
   [6, 0],
   [7, 6]])

A: I think you cannot do that, since from the ref we got:

Warning: Regarding the Nearest Neighbors algorithms, if two neighbors,
  neighbor k+1 and k, have identical distances but different labels, the
  results will depend on the ordering of the training data.


text:
Q: dark theme in gnome There is problem with dark themes and inputs ...
When i use dark theme for gnome2 (gtk-2), I have problem in the input, the color of fonts in input always dark or black (for example in an application like gnome-applets) and also input background always black or dark too.
What can i do to solve this problem? Can i set it to don't change input color? or force all program use custom color?


text:
Q: Issue with Intellisense for VSCode for Unity on Ubuntu 18.04LTS Problem
I am trying to use Unity on Ubuntu 18.04 using Visual Studio Code.
To set it up, I followed the steps put here:
https://medium.com/@sami1592/set-up-visual-studio-code-for-unity-in-linux-69b7f4352e0b
Some additional steps not mentioned in the article:

*

*I installed vscode with snap (from the software center) and redirected Unity's external coding program to it.

*I ran the installation commands while logged in as an administrator using su.

On the first day I was using this, I had no problems; Intellisense worked perfectly.
The next day, after I powered on my computer and opened my project, I found that Intellisense stopped working well.
VSCode output this error in the Omnisharp terminal:

Starting OmniSharp server at 11/4/2020, 4:51:19 PM
Target: /home/fakeusername/Code/FakeProjectName/FakeProjectName.sln
OmniSharp server started.
Path: /home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/run
PID: 3364
Starting OmniSharp on ubuntu 18.4 (x64) info: OmniSharp.Services.DotNetCliService
DotNetPath set to dotnet info: OmniSharp.MSBuild.Discovery.MSBuildLocator
Located 1 MSBuild instance(s)
1: StandAlone 16.8.0 - "/home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin"
info: OmniSharp.MSBuild.Discovery.MSBuildLocator
MSBUILD_EXE_PATH environment variable set to '/home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin/MSBuild.exe'
info: OmniSharp.MSBuild.Discovery.MSBuildLocator
Registered MSBuild instance: StandAlone 16.8.0 - "/home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin"
CscToolExe = csc.exe
MSBuildToolsPath = /home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin
CscToolPath = /home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin/Roslyn
BypassFrameworkInstallChecks = true
MSBuildExtensionsPath = /home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/omnisharp/.msbuild
info: OmniSharp.Cake.CakeProjectSystem
Detecting Cake files in '/home/fakeusername/Code/FakeProjectName'. info:
OmniSharp.Cake.CakeProjectSystem
Could not find any Cake files info: OmniSharp.MSBuild.ProjectSystem
Detecting projects in '/home/fakeusername/Code/FakeProjectName/FakeProjectName.sln'. info:
OmniSharp.MSBuild.ProjectManager
Queue project update for '/home/fakeusername/Code/FakeProjectName/Assembly-CSharp.csproj'
info: OmniSharp.Script.ScriptProjectSystem
Detecting CSX files in '/home/fakeusername/Code/FakeProjectName'. info:
OmniSharp.Script.ScriptProjectSystem
Could not find any CSX files info: OmniSharp.WorkspaceInitializer
Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider,
Order: 0 info: OmniSharp.MSBuild.ProjectManager
Loading project: /home/fakeusername/Code/FakeProjectName/Assembly-CSharp.csproj info:
OmniSharp.WorkspaceInitializer
Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.Completion.CompletionOptionsProvider,
Order: 0 info: OmniSharp.WorkspaceInitializer
Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider,
Order: 100 info: OmniSharp.WorkspaceInitializer
Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.ImplementTypeWorkspaceOptionsProvider,
Order: 110 info: OmniSharp.WorkspaceInitializer
Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.BlockStructureWorkspaceOptionsProvider,
Order: 140 info: OmniSharp.WorkspaceInitializer
Configuration finished. info: OmniSharp.Stdio.Host
Omnisharp server running using Stdio at location '/home/fakeusername/Code/FakeProjectName' on host 3236. fail:
OmniSharp.MSBuild.ProjectLoader
The reference assemblies for .NETFramework,Version=v4.7.1 were not found. To resolve this, install the Developer Pack (SDK/Targeting
Pack) for this framework version or retarget your application. You can
download .NET Framework Developer Packs at
https://aka.ms/msbuild/developerpacks [warn]:
OmniSharp.MSBuild.ProjectManager
Failed to load project file '/home/fakeusername/Code/FakeProjectName/Assembly-CSharp.csproj'.
/home/fakeusername/Code/FakeProjectName/Assembly-CSharp.csproj
/home/fakeusername/.vscode/extensions/ms-dotnettools.csharp-1.23.5/.omnisharp/1.37.3/omnisharp/.msbuild/Current/Bin/Microsoft.Common.CurrentVersion.targets(1180,5):
Error: The reference assemblies for .NETFramework,Version=v4.7.1 were
not found. To resolve this, install the Developer Pack (SDK/Targeting
Pack) for this framework version or retarget your application. You can
download .NET Framework Developer Packs at
https://aka.ms/msbuild/developerpacks
Attempted to update project that is not loaded: /home/fakeusername/Code/FakeProjectName/Assembly-CSharp.csproj

What I've tried

*

*Reinstalling Mono:
I repeated the installation steps for 18.04 specified here: https://www.mono-project.com/download/stable/#download-lin
I tried to a number of times, sometime uninstalling mono-devel first.
After doing so, I would test the installation with the Hello World example on this page, which always worked: https://www.mono-project.com/docs/getting-started/mono-basics/

*Reinstalling .NET Core SDK:
I repeated the installation steps for 18.04 specified here, following the steps under '18.04' and the corresponding 'Install the SDK': https://learn.microsoft.com/en-us/dotnet/core/install/linux-ubuntu#1804-
I first did this without any un-installation, and it had no effect.
I then did it after removing the 'usr/share/dotnet' and 'home/fakeusername/.dotnet' directories. This did not fix the issue, and an additional problem: the console no longer recognized the dotnet command in the terminal; it showed the error:

Command 'dotnet' not found, but can be installed with:
sudo snap install dotnet-sdk

Despite this issue and the new one that arose later, I have not had any issues running the Unity game itself.


text:
Q: Measuring the size of bubbles from a picture of material particles - Python-OPenCV I am trying to measure the size and count of bubbles available in image taken from real world material particles.
I have tried the approach present Here (second one with opencv). But some how it doesnt work probably because of the bubbles, because image is kind of an average quality.
Can some one please direct me to correct direction or provide recommendation?
The reference image, i am trying process is

Result:
It doesn't detects the circles, in fact at finding contours step, it gets a zero therefore the test is not passed.
Made some changes. Able to detect some bubbles but still not good. Detected bubble image is below

Thanks
Code:
import cv2

image = cv2.imread('....')

# Gray, blur, adaptive threshold
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (11,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Morphological transformations
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
# Find contours
cnts = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    # Find perimeter of contour
    perimeter = cv2.arcLength(c, True)
    # Perform contour approximation
    approx = cv2.approxPolyDP(c, 0.04 * perimeter, True)
    if len(approx) > 6:

            # Obtain bounding rectangle to get measurements
            x,y,w,h = cv2.boundingRect(c)

            # Find measurements
            diameter = w
            radius = w/2

            # Find centroid
            M = cv2.moments(c)
            cX = int(M["m10"] / M["m00"])
            cY = int(M["m01"] / M["m00"])

            # Draw the contour and center of the shape on the image
            cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),4)
            cv2.drawContours(image,[c], 0, (36,255,12), 4)
            cv2.circle(image, (cX, cY), 15, (320, 159, 22), -1)

            # Draw line and diameter information
            cv2.line(image, (x, y + int(h/2)), (x + w, y + int(h/2)), (156, 188, 24), 3)
            cv2.putText(image, "Diameter: {}".format(diameter), (cX - 50, cY - 50), cv2.FONT_HERSHEY_SIMPLEX, 3, (156, 188, 24), 3)
cv2.imwrite('...', image)
cv2.imwrite('...', thresh)
cv2.imwrite('...', opening)


text:
Q: Riemann integral of a certain function Let $\{q_n\}$ be an enumeration of the rationals in $[0,1]$. Define $f$ on $[0,1]$ by $f(x):=\sum_{q_n<x}2^{-n}$.
It has already been shown by Lebesgue's Criterion that $f$ is Riemann integrable. Now we're supposed to compute the integral. We've tried constructing partitions based on the enumeration, but nothing has worked out.

A: Note that
$$ f = \sum_{n \in \mathbb N} 2^{-n}\chi_{(q_n, 1]} $$
and the convergence is uniform, hence integration and summation can be exchanged, giving
$$ \int_0^1 f(x) \, dx = \sum_n 2^{-n} \int_0^1 \chi_{(q_n, 1]}(x)\, dx = \sum_n 2^{-n}(1 - q_n). $$


text:
Q: Creating 2 boxes side by side with tcolorbox I want to create 2 boxes side by side (image below) in order to have the red box on the right of the blue one :

I wrote this code but I don't know how to do it (I am just specifying the width to fit in the general page):
\documentclass{article}

\usepackage{pgf, tikz, adjustbox}
\usepackage{tcolorbox}

\begin{document}
\tcbset{colback=blue!5!white,colframe=blue!75!black,fonttitle=\bfseries, width = 12cm}
\begin{tcolorbox}[before=\adjustbox{valign=t}\bgroup, after=\egroup]

\textbf{Démonstration}

\end{tcolorbox}

\tcbset{colback=red!5!white,colframe=red!75!black,fonttitle=\bfseries, width = 5cm}
\begin{tcolorbox}[before=\adjustbox{valign=t}\bgroup, after=\egroup]

\gap
A écrire
\end{tcolorbox}
\end{document}

Any help would be appreciated ! Thank you very much.

A: I found the option box align in the package documentation on page 86 in the PDF. You can set this to top, bottom and center. Here is an example using center:
\documentclass{article}
\usepackage{pgf, tikz, adjustbox}
\usepackage{tcolorbox}
\usepackage{xcolor}
\begin{document}

\tcbset{colback=blue!5!white,colframe=blue!75!black,fonttitle=\bfseries,width=5cm,nobeforeafter}

\begin{tcolorbox}[box align=center]
\textbf{Démonstration}
\end{tcolorbox}
\tcbset{colback=red!5!white,colframe=red!75!black,fonttitle=\bfseries,width = 5cm}
\begin{tcolorbox}[box align=center]
\vspace{1cm}
A écrire
\end{tcolorbox}

\end{document}

This produces the output:


text:
Q: Regular expression that finds and replaces a long string of words I am new to Regular Expressions.
What is the expression that would find a long string of words that begin with a 3-digit number and place spaces at the beginning of capitalized words:
REPLACE:
013TheBlueCowJumpedOverTheFence1984.jpg

WITH:
013 The Blue Cow Jumped Over The Fence 1984

Note: removes the .jpg at the end
This will save me ooooodles of time.

A: I would not use regular expressions for this task. It's going to be ugly and hard to maintain.  A better approach would be to loop through the string and rebuild the string as you go based on your input.
string retVal = "";
foreach(char s in myInput){
    if(IsCapitol(s)){
        reVal += " " + s;
    }
    //insert the rest of your conditions
}

A: try use this regular expression \d+|[A-Z][a-z]*
it will collect all matches, and you must join them with spases

A: match:
'[A-Z][a-z]*'

replace with
' \0'

Note that this doesn't put a space before 1984, and it doesn't remove .jpg.
You can do the former by matching on
'[0-9]+|[A-Z][a-z]*'

instead. And the latter by removing it in a separate instruction, for example with a regexp replacement of '\.jpg$' with ''
Note that \'s need to be written as \\ in many languages.

A: This will need two operations since the replacement is different for each.
The first:
/(((?<![\d])\d)|((?<![A-Z])[A-Z](?![A-Z])))/

Replace with: ' $1' (note the space)
Will put spaces between the words. The second:
/\s*(.*)\s*\..*$/

Replace with: '$1'
Will remove trailing spaces and the extension.
The first expression can be taken into parts: (?<![\d])\d finds a digit not preceded by another digit, the second: ((?<![A-Z])[A-Z](?![A-Z])) finds an uppercase letter not preceded or followed by an uppercase lettter.
You'll likely have more rules that you will want to incorporate into this, such as how are you dealing with the string: 'BackInTheUSSR.jpg'?
Edit: This should handle that example:
/(((?<![\d])\d)|((?<![A-Z])[A-Z](?![A-Z]))|((?<![A-Z])[A-Z]+(?![a-z])))/


text:
Q: Mixed moments for the birthday problem Let $X_1,X_2,\dots$ be iid draws from the uniform distribution on $\{1,2,...,m\}$, and let the random variable $N$ be the minimum $j$ such that $X_j = X_i$ for some $i<j$.
I'm aware that the expected value of $N \choose 2$ (I call this a "mixed moment" since it's 1/2 times the second moment minus 1/2 times the first moment) is exactly $m$. Who first noticed/proved this?
Also, I've heard that, more generally, the expected value of $N \choose k$ is a degree-$k/2$ polynomial function of $m$ when $k$ is even. Where can I learn more about this?

A: $\newcommand{\N}{\mathbb N}
\newcommand{\R}{\mathbb R}
\newcommand{\B}{\mathcal B}
\newcommand{\F}{\mathcal F}
\newcommand{\X}{\mathcal X}
\newcommand{\ep}{\epsilon}
\newcommand{\la}{\lambda}
\newcommand{\si}{\sigma}
\newcommand{\Si}{\Sigma}
\renewcommand{\c}{\circ}
\newcommand{\tr}{\operatorname{tr}}
\newcommand{\E}{\operatorname{\mathsf E}}
\newcommand{\PP}{\operatorname{\mathsf P}}$
For any natural $n$,
\begin{multline*}
 \PP(N>n)=\PP(X_1,\dots,X_n\text{ take distinct values })=\frac{m(m-1)\cdots(m-n+1)}{m^n} \\
 =\frac{(m-1)\cdots(m-n+1)}{m^{n-1}},
\end{multline*}
whence
\begin{equation}
 \PP(N=n)=\PP(N>n-1)-\PP(N>n)
 =\frac{(m-1)\cdots(m-n+2)}{m^{n-1}}\,(n-1).
\end{equation}
So,
\begin{multline*}
 \mu_k(m):=\E \binom Nk \\
 =\frac1{k!}\sum_{n=k}^{m+1}\frac{n-1}{m^{n-1}}\,n(n-1)\cdots(n-k+1)(m-1)\cdots(m-n+2). \tag{1}
\end{multline*}
From here, with the help of Mathematica, I do get
\begin{equation}
 \E \binom N2=m.
\end{equation}
However, $\mu_4(10)-3\mu_4(9)+3\mu_4(8)-\mu_4(7)=0.0126\ldots\ne0$, so that $\mu_4$ is not a polynomial of degree $4/2=2$. That is, in general the statement that $\E \binom Nk$ is a polynomial of degree $k/2$ in $m$ is false.
Let us now show that $\mu_4(m)$ is not a polynomial in $m$ of any degree. Let  $X_m$ be a random variable (r.v.) with the Gamma distribution with parameters $m$ and $1$, so that $X_m$ has the distribution of the sum of $m$ iid standard exponential r.v.'s, each of those r.v.'s with mean $1$. Then, by the central limit theorem, $\PP(X_m>m)\to1/2$ as $m\to\infty$.
An expression for $\mu_4(m)$ for any natural $m$ (also obtained with the help of Mathematica) is
$\frac{1}{3} m \left(-2 e^m m E_{1-m}(m)+m+1\right)$, where $E_n(z)=\int_1^\infty t^{-n}e^{-tz}\,dt$ is "the exponential integral function"; I have verified numerically that for $m=1,\dots,100$ the latter expression for $\mu_4(m)$ matches the special case of (1) for $k=4$. So, if $\mu_4(m)$ were a polynomial in $m$, then so would be $e^m m^2 E_{1-m}(m)$. But
\begin{multline*}
 e^m m^2 E_{1-m}(m)=e^m m^2 \frac1{m^m}\int_m^\infty u^{m-1}e^{-u}du
 =m\,\frac{e^m m!}{m^m}\,\PP(X_m>m) \\
 \sim m\,\sqrt{2\pi m}\,\frac12
\end{multline*}
as $m\to\infty$,
by Stirling's formula and because $\PP(X_m>m)\to1/2$.
So, $e^m m^2 E_{1-m}(m)$ cannot be a polynomial in $m$. Thus, $\mu_4(m)$ is not a polynomial in $m$, of any degree.

A: Here is an approach via Lagrange inversion.
Let $N$ denote the time of the first repeat, and let $T(z)$ (the ``tree function'') be the formal power series satisfying $T(z)=z\,e^{T(z)}$.
If $F$ is a formal power series  the coefficients of $G(z):=F(T(z))$ are given by (Lagrange inversion)
$$[z^0]G(z)=[z^0] F(z) \mbox{ , }  [z^k]G(z)=\tfrac{1}{k} [y^{k-1}] F^\prime(y)\,e^{ky} =[y^k](1-y)F(y)\,e^{ky}\mbox{ for } k\geq 1\;.$$
In particular
$$[z^m] T(z)^k=\frac{k}{m} \frac{m^{m-k}}{(m-k)!}\mbox{ and }
            \frac{1}{1-T(z)}=\sum_{n\geq 0}\frac{n^{n}}{n!}z^n$$
        Using the first relation it is easily seen that the generating function of $N$ may be written as
        $$\mathbb{E} t^N=\frac{m!}{m^m} [z^m]\frac{t}{1- tT(z)}$$
        Thus the binomial moments $\mathbb{E}{N \choose k}$ of $N$ can be obtained as
        $$\mathbb{E}{N \choose k} = \frac{m!}{m^m} [z^m t^k]\frac{1+t}{1- (1+t)T(z)}=\frac{m!}{m^m} [z^m ]\frac{T(x)^{k-1}}{(1- T(z))^{k+1}}$$
        Differentiation shows that $z\,T^\prime(z)= \frac{T(z)}{1-T(z)}$.
        Therefore
        \begin{align*} \mathbb{E}{N \choose 2} &=\frac{m!}{m^m} [z^m ]\frac{T(z)}{(1- T(z))^{3}}\\
           &=\frac{m!}{m^m} [z^{m-1} ]\frac{T^\prime(z)}{(1- T(z))^{2}}\\
           &=\frac{m!}{m^m} [z^{m-1} ]\big(\frac{1}{1- T(z)}\big)^\prime\\
           &=\frac{m!}{m^m} m\,[z^{m} ]\frac{1}{1- T(z)}
                                       =m\end{align*}
        (I don't know who first observed that.)
       Similarly
        \begin{align*} \mathbb{E}{N \choose 4} &=\frac{m!}{m^m} [z^m ]\frac{T(z)^3}{(1- T(z))^{5}}\\
      &=\frac{m!}{m^m} [z^{m-1} ] T^\prime(z)\frac{T(z)^2}{(1- T(z))^{4}}\\
      &=\frac{m!}{m^m} [z^{m-1} ]\big(\frac{1}{1- T(z)}-\frac{2}{3}\frac{1}{(1-T(z))^2}+\frac{1}{3}\frac{T(z)}{(1-T(z))^3}\big)^\prime\\
      &=\frac{m!}{m^m} m\,[z^{m}]\big(\frac{1}{1- T(z)}-\frac{2}{3}\frac{1}{(1-T(z))^2}+\frac{1}{3}\frac{T(z)}{(1-T(z))^3}\big)\\
      &=\frac{m^2}{3} +m -\frac{2}{3} m\,\mathbb{E}(N)\end{align*}
Clearly other binomial moments can be treated in the same way.


text:
Q: Import controller and view to web project I want to create a code library that has a controller (FooController) and an accompanying view (Foo.cshtml) and import it to a web project. The idea is to create a nuget package out of this project so that it can be imported to other web projects. But when I test to import this project in another web project and navigate to the controller, the controller hits, but I get a view engine exception when it tries to load the view. Any ideas on if this is possible and how to do it?

A: Because on default it only loads controllers out of the main dll/project.
You can extend/overwrite this part of code (from .Net MVC) that discovers the controllers: the ControllerFactory
The router matches url for a route and tells the ControllerFactory the name of the controller it wants.
This controllerFactory on default only reflects your Startup DLL (code project) and not external nuget packages.


text:
Q: Variables overriden into a for loop I'm trying to add markers to a Google maps using V3. I have my places into an json object (places):
var num_places = places.length;
for(var i = 0; i < num_places; i++)
{
    place_lat_lng = new google.maps.LatLng(places[i].lat, places[i].lng);
    var infowindow = new google.maps.InfoWindow({
        content: '
' + places[i].name + '

' + places[i].body + '
'
    });
    var marker = new google.maps.Marker({
        position: place_lat_lng,
        map: mymap,
        title: places[i].name,
        zIndex: i
    });
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(mymap, marker);
    });
}

The code insert the markers, but when I click on any of them the infoWindow show (and move the map) always to the last marker in the list.
I tryed to use an array to for the infoWindow:
var infoWindow = new Array();
for(var i = 0; i < num_places; i++)
{
    [...]
    var infowindow[i] = new google.maps.InfoWindow({
        content: '
' + places[i].name + '

' + places[i].body + '
'
    });
    [...]
    google.maps.event.addListener(marker, 'click', function() {
        infowindow[i].open(mymap, marker);
    });
}

But nothings change.
Where am I mistaking?

A: In JavaScript, only functions create a new scope/closure. Therefore you only ever have one infowindow variable, which is captured into the inner function, but which in the end will point to the last window. Use a self-calling function to set up a new closuse:
for (var i = 0; ...) {
    (function() {
        var infowindow = ...;
    })();
}

Note that the value of i will still not be captured separately. Currently you don't seem to need it, but if you do, pass it to the function to create a local version of it inside the function:
(function(i) { // this is the new local i with the value passed in from the outside
    // ...accessible here
})(i); // this is the outer i

A: Change this:
google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(mymap, marker);
    });

to:
google.maps.event.addListener(marker, 'click', function(infowindow) {
        function() {
            infowindow.open(mymap, marker);
        });
    }(infowindow);

The problem is that your infowindow variable is getting recreated in the loop each time, and when the click handler fires, it is looking in a local closure for the most recent version.  The updated code creates a new closure that will contain the version of infowindow that is unique to that iteration of the loop.


text:
Q: How to get Jquery UI Autocomplete working with Rails 4? I'm using Rails 4.0.2 with jquery-rails (3.1.0) and jquery-ui-rails (4.1.1) gems. I'm trying to add Autocomplete to the search form (using Bootstrap 3.1.0):
<%= form_tag products_path, method: :get, class: 'navbar-form navbar-left' do %>

     <%= text_field_tag :query, params[:query], id: "navbar-search-input", class: 'form-control', placeholder: 'Product name.....' %>

   <%= button_tag(type: 'submit', id: 'navbar-search-btn', class: 'btn btn-default') do %>
      Search
   <% end %>
<% end %>

Here are my application JS and CSS files:
application.js
//= require jquery
//= require jquery_ujs
//= require jquery.ui.autocomplete
//= require turbolinks
//= require_tree .

var ready;
ready = (function() {
  $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
  $("#navbar-search-input").autocomplete({
    source: '/products/autocomplete.json',
  });
});

$(document).ready(ready);
$(document).on('page:load', ready);

application.css.scss
*= require bootstrap
*= font-kit-rails/ubuntu
*= require jquery.ui.autocomplete
*= require_self
*= require_tree .

Than my controller and route for the autocompletion:
class ProductsController < ApplicationController

  def autocomplete
    @products = Product.order(:name)
    respond_to do |format|
      format.html
      format.json {
        render json: @products.where("name ILIKE ?", "%#{params[:q]}%")
      }
    end
  end

routes.rb
  resources :products do
    collection do
      get 'autocomplete'
    end
  end

Now with all of this, my json file with all of my products at /products/autocomplete.json are there. The problem is if I type in anything, it gives me a blank dropdown and if I click on any area of the dropdown it will reset the search form field. Do you know how to get this to work?
EDIT
NOTE: I have a Product named Rice
Started GET "/products/autocomplete.json?term=ric" for 127.0.0.1 at 2014-03-19 10:06:51 -0400
Processing by ProductsController#autocomplete as JSON
  Parameters: {"term"=>"ric"}
  Product Load (0.9ms)  SELECT "products".* FROM "products" WHERE (name ILIKE '%%') ORDER BY "products"."name" ASC
Completed 200 OK in 16ms (Views: 14.3ms | ActiveRecord: 0.9ms | Search: 0.0ms)

A:   def autocomplete
    @products = Product.order(:name).where("name LIKE ?", "%#{params[:term]}%")
    respond_to do |format|
      format.html
      format.json {
        render json: @products.map(&:name).to_json
      }
    end
  end

A: Judging by your note, it looks like you're not fetching the param correctly in your controller, so try:
render json: @products.where("name ILIKE ?", "%#{params[:term]}%")


text:
Q: how to convert excel file to CSV file (pipe delimited) using excel vba I want to convert the simple excel files into CSV(pipe delimited)
using excel vba
I tried to many code but cant get expected output
following code I tried

      Sub mergeFiles()
        Dim xlwkbInput1  As Workbook
        Dim xlshtInput1  As Worksheet
        Dim xlwbfinalrpt As Workbook
        Dim xlshtfinalrpt As Worksheet

        Dim rcount1 As Long

        Dim xlwkbInput2  As Workbook
        Dim xlshtInput2 As Worksheet
        Dim xlapp As Excel.Application

        Set xlapp = New Excel.Application
        xlapp.Visible = True

           Set xlwkbInput1 = xlapp.Workbooks.Open(ActiveWorkbook.Path & "\Output\Operative_CashFlow_Report.xlsx")
           Set xlwkbInput2 = xlapp.Workbooks.Open(ActiveWorkbook.Path & "\Output\Collection_CashFlow_Report.xlsx")

           xlwkbInput2.Sheets("Sheet1").Activate
           xlwkbInput2.ActiveSheet.UsedRange.Copy

           xlwkbInput1.Sheets("Sheet1").Activate
           rcount = xlwkbInput1.ActiveSheet.UsedRange.Rows.Count

           xlwkbInput1.Sheets("Sheet1").Range("A" & CStr(rcount + 1)).PasteSpecial

           xlwkbInput1.UsedRange("$A$1:$I$274").AutoFilter Field:=1, Criteria1:=Array( _
           "LIC106", "LIC107", "LIC134", "LIC138", "="), Operator:=xlFilterValues
           xlwkbInput1.UsedRange.Delete
           xlwkbInput1.SaveAs ActiveWorkbook.Path & "\Output\final_report.xlsx"
           Set xlwbfinalrpt = xlapp.Workbooks.Open(ActiveWorkbook.Path & "\Output\final_report.xlsx")
           xlwbfinalrpt.Sheet("Sheet1").Activate

            xlwbfinalrpt.SaveAs ActiveWorkbook.Path & "\Output\final_report.xlsx"

    xlwbfinalrptwb = Workbooks.Open (ActiveWorkbook.Path & "\Output\final_report.xlsx"

         xlwbfinalrptwb .SaveAs fileName:=ActiveWorkbook.Path & "\Output\final_report.xlsx"
    , FileFormat:=xlCSV, CreateBackup:=False

' here I m doing conversion of excel to CSV file
End Sub

A: You can save an Excel file as comma delimited or tab delimited but not pipe delimited.
Here is how you can achieve pipe delimited export.
Basic Sample
Just to show here the fundamentals.
Sub Writing_to_a_text_file()
    Dim N As Integer
    Dim FileName As String

    'Define where to save the output file.
    FileName = Environ("USERPROFILE") & "\Desktop\" & "Sample1.csv"

    'Get a free file number
    N = FreeFile

    Open FileName For Output As #N
        '"Print" print data into the file. Another method is "Write".
        'Both do the same job but behave slightly differently. Try Google it.
        Print #N, "This is a test"
        Print #N, "Writing another line here"
        Print #N, Join(Array("Pipe", "delimited", "line", "here"), "|")
        Print #N, vbNullString '<- this create an empty line
    Close N
End Sub

Export a range of data in pipe delimited format into a text file
Sub ExportToTextFile()
'Export range("A1:E10") data to a text file in pipe delimited format.
    Dim N As Integer
    Dim FileName As String
    Dim R As Long, C As Long, DataLine As String

    FileName = Environ("USERPROFILE") & "\Desktop\" & "TextOutput.csv"

    N = FreeFile

    Open FileName For Output As #N
        For R = 1 To 10
            DataLine = vbNullString
            For C = 1 To 5
                DataLine = DataLine & "|" & Cells(R, C).Value2
            Next C
            DataLine = Right(DataLine, Len(DataLine) - 1)
            Print #N, DataLine
        Next R
    Close N
End Sub

A: If you just want to save a sheet out as a pipe delimited file then this should work for you:
Sub DelimFile()

Open "C:\output.txt" For Output As 1 'Change this path

rowno = 1
colcount = Application.CountA(ActiveSheet.Rows(1))
While activesheet.Cells(rowno, 1) <> ""
    dataout = ""
    For c = 1 To colcount
        If c <> colcount Then
            dataout = dataout & """" & Trim(activesheet.Cells(rowno, c)) & """|"
        Else
            dataout = dataout & """" & Trim(activesheet.Cells(rowno, c)) & """"
        End If
    Next c
    Print #1, dataout
    rowno = rowno + 1
Wend
Close #1
End Sub


text:
Q: Soft-Keyboard intercepting my onClickListener? In Android I have the following code to blank an EditText box when clicked.
This is to remove any existing information in the box and start with a blank slate.
It sort off works. When you first click in the edit box the soft keyboard appears, but the existing information in the EditBox is still there. If you click a second time in the EditBox the information dissapers.
How can I get it to clear the data on the first click? I am guessing the first click is intercepted by the soft keyboard.
Many thanks for any help.
// Blank EditText field when clicked
        myEditBox.setOnClickListener( new OnClickListener(){

        @Override
        public void onClick(View v) {

            tcA.setText("");
            }

        });

A: Im not sure, but try clearing it when the EditText gets focus.
myEditBox.setOnFocusChangeListener( new onFocusChangeListener(){
   @Override
   public void onFocusChange(View arg0, boolean hasFocus){
      tcA.setText("");
   }
});


text:
Q: Simplest way to receive email to a lambda - AWS Simple Email I am new to SES and thought it would be a quick setup but its looking a bit more involved than expected. I also have to go through a client so I want to make sure I understand my options before I make any requests.
So I have a client who has set up an email mailbox in outlook, dev@clientdomain.com. I want to have emails sent to this go into a lambda for processing, so I was looking at SES. Do I need to go through the same setup as if I was going to be sending emails? That is do I need to verify a domain identity or can I get away with verifying just an email? Do I need to ask the client to publish an MX record on their domain?
Tbh I was hoping I could just some email address in AWS that is linked to a lambda, and then have the client email forward to this. Is there nothing straight forward like this in AWS? I am able to send emails with the client email following this, but how can I receive an email and parse it with a lambda the easiest way?

A: AWS Workmail offers exactly this functionality (email on hosted test domain that routes to lambda of choice)


text:
Q: How to automatically update woocommerce products with a csv I'm currently stuck on my websites with a csv product import. I want the csv to sit on the server where i can simply update the csv and all the data will be transferred over to my products instantly without having to consistently upload the csv.
Does anyone know any way how to make this happen automatically ?
Thanks for your help!

A: A simple way to this can be a function which will be executed on every page load. This function checks if there is a csv-file, and if so, starts the import. But there a weaknesses by doing it this way. The import process will stuck the page load. And if the functions checks whether there is a cs-file, it can be that this csv-file is not completely uploaded, because the ftp-transfer is still running in this moment. (see here)
A better way is to use a Webhook to invoke the import function. The Webhook ideally should triggered by the process which transfer the csv-file (after completion) to the server.


text: Q: Is $\int_0^{\infty} \frac{\prod_{n-1}^m \sin (x^n)}{f(x)}dx$ convergent if $f(x) \to \infty$ is strictly positive increasing? This question is motivated by this question How to show whether these integrals converge or not? where exact integral reformulation and Dirichlet's test is used to give an answer. However suppose we just have a positive increasing continuous function $f(x)$ such that $f(x) \to \infty$. Then is $\int_0^{\infty} \frac{\prod_{n-1}^m \sin (x^n)}{f(x)}dx$ convergent? It seems like it should be, but the alternation of the numerator from positive to negative seems so unpredictable I can't see how to show it, except for the case $m = 1$.


text:
Q: how to stop pandas from inferring string value "Infinity" as inf and changing datatype to float64 I have a dataset with a column "Vendor" and it has multiple values as "Infinity", when I use read_csv, pandas automatically converted the Vendor column values to inf and changed its datatype to float64.
This is the test dataset I am using
Vendor, Value
Infinity,1
Infinity,2
Infinity,3
Infinity,4
Infinity,5

This is the result I am getting with inf value and datatype as float64
Vendor  Value
inf     1
inf     2
inf     3
inf     4
inf     5
Name: Vendor, dtype: float64

Is there a way to avoid default infering of Infinity to inf?

A: You can pass the dtype argument to set explicit column types for particular column names, like so:
pd.read_csv(file_name, dtype={'Vendor': str})


text:
Q: How can I use the routes, but not change the URL? I am building a Single Page Application(SPA), whose domain is http://teachme.com. The routes could be seen as
teachApp.config(['$routeProvider', '$locationProvider', function($routeProvider,       $locationProvider) {
    $routeProvider.
        when('/teach/', {templateUrl: 'views/login_view.html'}).
        when('/teach/overview', {templateUrl: 'views/overview_view.html'}).
        when('/teach/users', {templateUrl: 'views/users_view.html'}).
        otherwise({redirectTo: '/teach/'});
    $locationProvider.html5Mode(true);
}]);

Now everytime i click on the tabs, the route changes and I see the different view, but URL changes to
http://teachme.com/#teach
http://teachme.com/#teach/overview
http://teachme.com/#teach/users

which fails the whole point of keeping the url unique and for bookmark purposes. Is there a way that routes work fine, but the URL stays to http://teachme.com
Thanks

A: The whole point of routes is to use deep linking, per the docs.
The domain & path components of your URL will always remain constant, however the component after the # is what changes, which allows bookmarks to work even though you are creating a single page app.
Short version is No, routing will not work if you don't want the portion of the URL after the # to be changed.  To me it seems like you loose value for bookmarking in the absence of such additions.
Even on a single page app, you can bookmark the teach or overview section etc.  Maybe you provide a bookmark link which always stamps the domain by itself in the bookmark for the user.


text:
Q: range.moveStart() function in IE11 non compatible mode I have a text box(numeric) in which numbers can entered or deleted.
On pressing the backspace key a value from a certain position is be deleted and a javascript function as below is called.

function getCaretPosition(textObject)
{
 var position = 0;
 if(textObject.createTextRange)
 {

  var range="";
  if (window.getSelection)
  {
   range = window.getSelection();
  }
  if (document.getSelection)
  {
  range = document.getSelection();
  }
  if(range=="")
  {
   if (document.selection)
   {
   range = document.selection.createRange().duplicate();
   }
  }

  //range = document.selection.createRange().duplicate();
  range.moveStart('textedit', -1);
  position = range.text.length;
 }
 else if(textObject.setSelectionRange)
  position = textObject.selectionEnd;
 return position;
}

When i run the application in IE11 non compatible mode and use the backspace key on the text field, a javascript error occurs as below:
"Object doesn't support property or method 'moveStart'"
I'm guessing that moveStart method is not supported in IE11.
Can someone please suggest on how to overcome this issue?
This seems to be working fine in IE11 compatible mode though.


text:
Q: Unwanted characters in in nltk3? I am currenlty working in a natural processing language project, and I scrapped several text from the web. I have worked out from some code fragments here from this site.
f = open(new_file, "w")     #arquivo para escrita do texto processado

with open(txt_file,  'rb') as in_file:

    for line in in_file:
        line = line.lower()         # troca tudo para minusculas
        if  re.search('\S', str(line)):
            line2=line
        phrases_list = re.split('[!?.,;:&()]+',  str(line2))         #separa as linhas pelos pontos

        for phrase in phrases_list:
            word_list = []
            # testa para ver se esta na lista de stopwords

            for word in phrase.split():         #separa as linhas em palavras
                if  word in contractions:
                    new_word =contractions[word]
                    if new_word not in stopset:
                        word_list.append(new_word)
                else:
                    if word not in stopset:
                        word_list.append(word)

            new_phrase = ' '.join(word_list)        # converte a lista em uma string

            # limpa o texto e salva cada frase linha por linha
            clean_phrase = re.sub("[^a-zA-Z\s]+", '', new_phrase).strip()
            if clean_phrase !='':
                f.write("%s\n" % clean_phrase)
f.close()

process_text(file_name,  caminho+"textoprocessado3.txt")`

In textoprocessado3.txt there appear things like:

b xexxceuropeanxexxd
  b every real peoples revolution
  b bourgeois revolution  displayed xexxcbrilliantxexxdn

How can I get rid of these unwanted characters, such as "b" at the beginning, "n" at the end or xexxc...xexxd?

A: First of all, the issue has nothing to do with NLTK. The code you posted doesn't even show any use of NLTK.
The main problem is that you are opening the input file in binary mode ('rb') instead of text mode ('rt', 'r', or just skip it, since both 'r' and 't' are the default). Opening a file in binary mode gives you bytes – but you want text, so you need the text mode.
Let's look at an example: A file with a single line of text:

It's

So 4 characters (plus a final newline). Note that the thrid character is not the ASCII apostrophe, but a typographical quote (Unicode character U+2019). The file is encoded in UTF-8.
If you read this in text mode, everything is fine:
>>> with open('example.txt', 'rt', encoding='UTF8') as f:
...     text = f.read()
...
>>> text
'It's\n'

It's crucial to have the right encoding, because the default encoding might not be the right one. It's a good guess to always try UTF-8 first, because if it's not the correct encoding, it will cause a decoding error.
However, if you read in bytes, this is what you get:
>>> with open('example.txt', 'rb') as f:
...     bytes_ = f.read()
...
>>> bytes_
b'It\xe2\x80\x99s\n'

That's how the encoded text was written to the disk, using 3 bytes for the typographical quote character. When you call str() on this, you get a representation string, where everything "special" is escaped, eg. newlines:
>>> str(bytes_)
"b'It\\xe2\\x80\\x99s\\n'"

And then you remove everything but the ASCII letters a through z, and whitespace, which means you remove the backslashes and digits:
>>> re.sub(r'[^a-zA-Z\s]', '', str(bytes_))
'bItxexxsn'

And that's exactly what happened on line 60 of the fragment you posted on ur1.ca.
Long story short: Use text mode when reading text.


text:
Q: pandas - Splitting date ranges on specific day boundary I've got a DataFrame of date ranges (the actual DataFrame has more data attached to it but has the same start and end columns).  The data ultimately needs to be analyzed week-by-week on a Sunday-Saturday basis.  Thus, I'd like to go through the DataFrame, and split any date ranges (start to finish) that cross from a Saturday to Sunday.  For example, given the DataFrame:
import pandas as pd

date_ranges = [
    {'start': '2020-01-16 22:30:00', 'end': '2020-01-17 01:00:00'}, # spans thurs-fri, ok as is
    {'start': '2020-01-17 04:30:00', 'end': '2020-01-17 12:30:00'}, # no span, ok as is
    {'start': '2020-01-18 10:15:00', 'end': '2020-01-18 14:00:00'}, # no span, ok as is
    {'start': '2020-01-18 22:30:00', 'end': '2020-01-19 02:00:00'}  # spans sat-sun, must split
]
data_df = pd.DataFrame(date_ranges)

I want my result to look like:
result_ranges = [
    {'start': '2020-01-16 22:30:00', 'end': '2020-01-17 01:00:00'}, # spans thurs-fri, ok as is
    {'start': '2020-01-17 04:30:00', 'end': '2020-01-17 12:30:00'}, # no span, ok as is
    {'start': '2020-01-18 10:15:00', 'end': '2020-01-18 14:00:00'}, # no span, ok as is
    {'start': '2020-01-18 22:30:00', 'end': '2020-01-19 00:00:00'}, # split out saturday portion
    {'start': '2020-01-19 00:00:00', 'end': '2020-01-19 02:00:00'}  # and the sunday portion
]

result_df = pd.DataFrame(result_ranges)

Any thoughts on how to effectively do this in pandas would be greatly appreciated.  Currently I am doing the bad thing, and iterating over rows, and it is quite slow when the data set gets large.

A: Manipulations like this are always difficult and at some level I think a loop is necessary. In this case, instead of looping over the rows, we can loop over the edges. This should lead to a rather big gain in performance when the number of weeks your data span is much smaller than the number of rows you have.
We define edges and modify the DataFrame endpoints where necessary. In the end the desired DataFrame is whatever is left of the DataFrame we modified, plus all the separate timespans we stored in l. The original Index is preserved, so you can see exactly what rows were split. If a single timespan straddles N edges it gets split into N+1 separate rows.
Setup
import pandas as pd

df[['start', 'end']]= df[['start', 'end']].apply(pd.to_datetime)

edges = pd.date_range(df.start.min().normalize() - pd.Timedelta(days=7),
                      df.end.max().normalize() + pd.Timedelta(days=7), freq='W-Sun')

Code
l = []
for edge in edges:
    m = df.start.lt(edge) & df.end.gt(edge)  # Rows to modify
    l.append(df.loc[m].assign(end=edge))     # Clip end of modified rows
    df.loc[m, 'start'] = edge                # Fix start for next edge

result = pd.concat(l+[df]).sort_values('start')

Output
                start                 end
0 2020-01-16 22:30:00 2020-01-17 01:00:00
1 2020-01-17 04:30:00 2020-01-17 12:30:00
2 2020-01-18 10:15:00 2020-01-18 14:00:00
3 2020-01-18 22:30:00 2020-01-19 00:00:00
3 2020-01-19 00:00:00 2020-01-19 02:00:00

A: My solution is even more general that you defined, namely it creates
a sequence of "week rows" from each source row, even if both dates
contain between them e.g. two Sat/Sun breaks.
To check that it works, I added one such row to your DataFrame, so that
it contains:
                start                 end
0 2020-01-16 22:30:00 2020-01-17 01:00:00
1 2020-01-17 04:30:00 2020-01-17 12:30:00
2 2020-01-18 10:15:00 2020-01-18 14:00:00
3 2020-01-18 22:30:00 2020-01-19 02:00:00
4 2020-01-25 20:30:00 2020-02-02 03:00:00

Note that the last row includes two Sat/Sun break, from 25.01 to 26.01
and from 1.02 to 2.02.
Start from conversion of both columns to datetime:
data_df.start = pd.to_datetime(data_df.start)
data_df.end = pd.to_datetime(data_df.end)

To process your data, define the following function, to be applied to each row:
def weekRows(row):
    row.index = pd.DatetimeIndex(row)
    gr = row.resample('W-SUN', closed='left')
    ngr = gr.ngroups  # Number of groups
    i = 1
    data = []
    for key, grp in gr:
        dt1 = key - pd.Timedelta('7D')
        dt2 = key
        if i == 1:
            dt1 = row.iloc[0]
        if i == ngr:
            dt2 = row.iloc[1]
        data.append([dt1, dt2])
        i += 1
    return pd.DataFrame(data, columns=['start', 'end'])

Let's present "individually", how it operates on 2 last rows:
When you run:
row = data_df.loc[3]
weekRows(row)

(for the last but one row), you will get:
                start                 end
0 2020-01-18 22:30:00 2020-01-19 00:00:00
1 2020-01-19 00:00:00 2020-01-19 02:00:00

And when you run:
row = data_df.loc[4]
weekRows(row)

(for the last), you will get:
                start                 end
0 2020-01-25 20:30:00 2020-01-26 00:00:00
1 2020-01-26 00:00:00 2020-02-02 00:00:00
2 2020-02-02 00:00:00 2020-02-02 03:00:00

And to get your desired result, run:
result = pd.concat(data_df.apply(weekRows, axis=1).values, ignore_index=True)

The result is:
                start                 end
0 2020-01-16 22:30:00 2020-01-17 01:00:00
1 2020-01-17 04:30:00 2020-01-17 12:30:00
2 2020-01-18 10:15:00 2020-01-18 14:00:00
3 2020-01-18 22:30:00 2020-01-19 00:00:00
4 2020-01-19 00:00:00 2020-01-19 02:00:00
5 2020-01-25 20:30:00 2020-01-26 00:00:00
6 2020-01-26 00:00:00 2020-02-02 00:00:00
7 2020-02-02 00:00:00 2020-02-02 03:00:00

First 3 rows result from your first 3 source rows.
Two next rows (index 3 and 4) result from source row with index 3.
And the last 3 row (index 5 thru 7) result from the last source row.

A: Similar to @Valdi_Bo's answer, I looked into breaking down a single interval of (start, end) into a series of intervals, including all the midnights of Sundays in between.
This is accomplished by the following function:
def break_weekly(start, end):
    edges = list(pd.date_range(start, end, freq='W', normalize=True, closed='right'))
    if edges and edges[-1] == end:
        edges.pop()
    return pd.Series(list(zip([start] + edges, edges + [end])))

This code will create a weekly date range from "start" to "end", normalizing to midnight time (so Sunday midnight) and will keep the interval open on the left (so it starts on the Sunday following start.)
There's a corner case for when "end" is exactly midnight on Sunday, since the interval needs to be closed on one side, we're keeping it closed on the right, so we're checking whether those two match and drop it if they're the same.
We then use zip() to create tuples with each pairs of dates, including the "start" at the beginning in the left, and the "end" timestamp at the end of the right.
We finally return a pd.Series of those tuples, since that makes apply() do what we expect.
Example usage:
>>> break_weekly(pd.Timestamp('2020-01-18 22:30:00'), pd.Timestamp('2020-01-19 02:00:00'))
0    (2020-01-18 22:30:00, 2020-01-19 00:00:00)
1    (2020-01-19 00:00:00, 2020-01-19 02:00:00)
dtype: object

At this point, you can apply it to the original data frame to find the complete list of intervals.
First, convert the types of the columns to pd.Timestamp (you have strings in the columns in your example):
data_df = data_df.apply(pd.to_datetime)

Then you can find the whole list of intervals with:
intervals = (data_df
    .apply(lambda r: break_weekly(r.start, r.end), axis=1)
    .unstack().dropna().reset_index(level=0, drop=True)
    .apply(lambda r: pd.Series(r, index=['start', 'end'])))

The first step applies break_weekly() to the "start" and "end" columns, row by row. Since break_weekly() returns a pd.Series, it will end up producing a new DataFrame with one column per date interval (as many as there are weeks in an interval).
Then unstack() will merge those columns back together, and dropna() will drop the NaN that were generated because each row had a different number of columns (different number of intervals for each row.)
At this point we have a multi-index, so reset_index(level=0, drop=True) will drop the index level we don't care about and only keep the one that matches the original DataFrame.
Finally, the last apply() will convert the entries from Python tuples back to a pd.Series and will name the columns "start" and "end" again.
Looking at the result up until this point:
>>> intervals
                start                 end
0 2020-01-16 22:30:00 2020-01-17 01:00:00
1 2020-01-17 04:30:00 2020-01-17 12:30:00
2 2020-01-18 10:15:00 2020-01-18 14:00:00
3 2020-01-18 22:30:00 2020-01-19 00:00:00
3 2020-01-19 00:00:00 2020-01-19 02:00:00

Since the indices match the ones from your original DataFrame, you can now use this DataFrame to connect it back to your original one, if you had more columns with values there and you want to duplicate those here, it's just a matter of joining them together.
For example:
>>> data_df['value'] = ['abc', 'def', 'ghi', 'jkl']
>>> intervals.join(df.drop(['start', 'end'], axis=1))
                start                 end value
0 2020-01-16 22:30:00 2020-01-17 01:00:00   abc
1 2020-01-17 04:30:00 2020-01-17 12:30:00   def
2 2020-01-18 10:15:00 2020-01-18 14:00:00   ghi
3 2020-01-18 22:30:00 2020-01-19 00:00:00   jkl
3 2020-01-19 00:00:00 2020-01-19 02:00:00   jkl

You'll notice that the value in the last row has been copied to both rows in that interval.


text: Q: 2010 Outlook settings Every morning when I open Outlook my mail options are reset, specificially my signnature fonts AND (the most irritating) in Advanced View Settings: Messages under "Group By" the "automatically group according to arrangement" keeps getting checked. How can I "lock" my settings?


text:
Q: why my link url to bad url on my site? link urls is bad in server but correct in my local!
i use :
Url.Action("myaction", "mycontroller", new { id = a.Id, title = a.Title,Name="test", area = "" })

and :
 routes.MapRoute(
            name: "ViewRout",
            url: "{lang}/{Name}/{id}/{title}",
            defaults: new { controller = "mycontroller", action = "myaction", lang = "en", id = UrlParameter.Optional, title = UrlParameter.Optional },
            constraints: new { id = @"\d+",
            namespaces: new[] { string.Format("{0}.Controllers", typeof(RouteConfig).Namespace) }
        );

url in local :
/en/test/6546/title1

but, url in server (not always, often, sometimes just bad!) :
/x1(a)xsyidfjazxdfdsxd/en/test/6546/title1

please help me!

A: It seems that your application is configured to enable cookieless sessions. This strange values in the URL are used to identify the sessions in case it can't use cookies for that. Please check "Enter Cookieless Sessions" section at:
https://msdn.microsoft.com/en-us/library/aa479314.aspx


text:
Q: Removing spaces between anchor tags I am working on a navigation links, there is a some gaps in between the links.
Got some solution for earlier questions from stackoverflow which says to remove the whitespaces between anchor tags as some browser will treat them as newline.  In my case there are no spaces between thee anchor tags.
enter link description here

Link1

Link2

Link3

#nav{
  background-color:#000000;
}

#nav ul {
  height: 50px;
  padding: 0;
  margin: 0;
  text-align:center;
  border:1px solid #fff;
}

#nav ul li {
   display: inline-block;
   height: 50px;
   width: 150px;
   text-align: center;
   border-right:1px solid #fff;
   border-left:1px solid #fff;
   list-style: none;
   font: normal bold 12px/1.2em Arial, Verdana, Helvetica;
   padding: 0;
   margin: 0;
   background-color: #000000;
}

 #nav ul li a{
   padding: 18px 0;
   text-decoration: none;
   color: white;
   display: block;
}

A: A quick solution would be to use float: left instead of display: inline-block for #nav ul li. Here's a complete article on how to remove the white space between inline-block elements using various methods.
By the way, the white space between each menu item which you see now is because of the border-right and the border-left.

#nav{
  background-color:#000000;
}

#nav ul {
  height: 50px;
  padding: 0;
  margin: 0;
  text-align:center;
  border:1px solid #fff;
}

#nav ul li {
   float: left;
   height: 50px;
   width: 150px;
   text-align: center;
   border-right:1px solid #fff;
   border-left:1px solid #fff;
   list-style: none;
   font: normal bold 12px/1.2em Arial, Verdana, Helvetica;
   padding: 0;
   margin: 0;
   background-color: #000000;
}

Link1

Link2

Link3

A: You don't have whitespaces in the anchor tags but you do have in the li tags. The li tags are the ones with inline-block. You should either remove those as well, or use font-size: 0; on the ul tag and then reset to the correct font-size in the li tag.
You should think of inline-block elements as really big characters, that way you can understand them easier.

A: font-size: 0 should be an answer!. In my case I make div including anchor tags.
After putting font-size: 0 on div, the space between anchor tags.


text:
Q: WIndows subsystem for Linux 'Get' button is disabled I am trying to install Ubuntu on windows using Windows subsystem for linux, but on store the button is grey, how can I enable it?

A:
I am trying to install Ubuntu on windows using Windows subsystem for
  linux, but on store the button is grey

You are trying to install the Windows 10 1709+ Ubuntu WSL on a Windows 10 1703 installation.  That will not be possible.

What you actually want to do, if you want to install WSL today on a Windows 10 1511+ to Windows 10 1703 installation simply do the following:

*

*Enable Developer Mode

*Install Windows Subsystem for Linux Beta

*Reboot

how can I enable it?

You cannot enable it.  What you have found can only be installed on a Windows 10 build 16215 or higher installation.  You should simply wait until 1709 is released or use an Insider Preview build of RS3 (aka 1709) if you cannot wait.


text:
Q: Pandas nunique got an expected I'm trying to learn Pandas and I'm running into a small problem with groupby and nunique.
Creating the dataframe below:
import pandas as pd
import numpy as np

chicago_dataset = pd.read_csv("https://raw.githubusercontent.com/gjreda/gregreda.com/master/content/notebooks/data/city-of-chicago-salaries.csv" ,
                                  converters={'Employee Annual Salary': lambda x: float(x.replace('$', ''))})

With the headers:
chicago_dataset.columns
Out[63]: Index(['Name', 'Position Title', 'Department', 'Employee Annual Salary'], dtype='object')

Now I want to group by Department and get a distinct count of Position Title how would I do something like this?
by_dept = chicago_dataset.groupby('Department')

I can do it with Name like below but Position Title is two words.
by_dept.Name.nunique()

A: There two different ways to do it:

*

*df.valid_python_name

*df['any string with spaces and # etc.']
Use the second:
by_dept['Position Title'].nunique()

Example:
>>> by_dept['Position Title'].nunique().head()

Department
ADMIN HEARNG          15
ANIMAL CONTRL         19
AVIATION             125
BOARD OF ELECTION     23
BOARD OF ETHICS        9
Name: Position Title, dtype: int64


text:
Q: Auto Inserting Amazon affiliate links take me to the wrong Amazon I live in the Republic of Ireland which is served by amazon.co.uk. The rads.stackoverflow.com/amzn/click/ redirector sends me to amazon.com.
According to this article, the redirector should use IP geolocation to send you to the most appropriate Amazon site:

Auto-Inserting Stack Overflow affiliate into all Amazon book links
We have a clever affiliate redirect
  that geolocates the IP and redirects
  to the appropriate regional Amazon
  store (amazon.uk, amazon.ca, et
  cetera).

Can the Amazon link redirector be changed to redirect to amazon.co.uk for Irish IP addresses?

A: Got a reply from Jeff explaining why the GeoLocator doesn't work any more:

It's a long story, but unless we
operate a business in the UK,
officially, we can't get affiliate
income from Amazon there anyway .. so
we don't geolocate amazon stuff any
more, and have not for a while.
some details here
https://blog.stackoverflow.com/2009/11/our-amazon-advertising-experiment/
but that bit is quite important and
not covered there.

Which is fair enough.


text:
Q: How can shifted pixels be adjusted to same position after doing cv.filter2D In a video frame, I am trying to sharpen the part where human face is visible, then imposing it on the background.
But after using the sharpening filter i.e. [[-1,-1,-1],[-1,9,-1],[-1,-1,-1]] on the image, the pixels get shifted and on superimposing the face on the background, image gets pixelated.
Here is a sample input and output image
# using canny edge detection to get the face pixels.
edges = cv2.Canny(input_image, 10, 200)
edges = cv2.dilate(edges, None)
edges = cv2.erode(edges, None)
contours,_ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
mask = np.zeros(edges.shape)
cv2.fillConvexPoly(mask, max_contour[0], (255))
mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)
mask_stack = np.dstack([mask]*3)

# sharpening the input_image
kernel = np.ones((3,3),np.float32)*-1
kernel[1][1] = 9
sharp = cv2.filter2D(input_image,-1,kernel)

# using mask_stack to impose filtered pixels.
final_img = (((1-mask_stack) * input_image)+((mask_stack) * sharp) )

How can this issue be

A: You need to use the ddepth argument to cv2.filter2D to choose a signed type for the output image. For example,
sharp = cv2.filter2D(input_image, CV_64F, kernel)

When ddepth = -1 as you do, then the output image will have the same type as the input image, and negative values will roll over and become large values (bright colors). This is what you see. I don't think there's a shift or pixelation occurring.
Next, after computing the final_img, you'll have to properly clamp the values and cast back to uint8:
final_img = (((1-mask_stack) * input_image)+((mask_stack) * sharp) )
final_img = np.clip(final_img, 0, 255).astype(np.uint8)


text:
Q: How to count all Subdocument in a Collection using Mongoose Here i need to count all sub-documents in a collection using mongoose
this is my routes
router.get('/all-booking', function(req, res){
        BookingList.find({}, 'booking', function (err, docs) {
            if(err)
                throw err;
            res.json(docs);
        });
    });

Here In BookingList booking is a  subdocument array, by above query am getting all sub-documents in Collection, But I need to Count all sub-document, How can i do this.
Help will be appreciated

A: Use aggregation to get the count:
router.get('/all-booking', function(req, res){
    var pipeline = [
        {   // Get the length of the booking array
            "$project": {
                "booking_size": { "$size": "$booking" }
            }
        },
        {   // Get the total length of all the booking fields
            "$group": {
                "_id": null,
                "count": { "$sum": "$booking_size" }
            }
        }
    ]
    BookingList.aggregate(pipeline, function (err, result) {
        if(err)
            throw err;
        console.log(result[0].count); // Prints the count of all the booking sub-documents in the collection
        res.json(result);
    });

    // Or using the fluent aggregate pipeline builder API
    BookingList.aggregate()
        .project({ "booking_size": { "$size": "$booking" } })
        .group({ "_id": null, "count": { "$sum": "$booking_size" } })
        .exec(function (err, result) {
            if(err)
                throw err;
            console.log(result[0].count); // Prints the count of all the booking sub-documents in the collection
            res.json(result);
        });
});


text:
Q: sqlalchemy: Updating a database using python I have this Post Model
class Post(Base):
__tablename__ = "posts"

id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default='True')
owner = Column(String, nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False,
                                  server_default=text('now()'))

I tried to modify an existing row with this python code but I'm getting the error:

File ".\app\main.py", line 118, in update_post
post.update()
AttributeError: 'Post' object has no attribute 'update'

@app.put("/posts/{id}", status_code=status.HTTP_202_ACCEPTED)
def update_post(id: int, db: Session = Depends(get_db)):

post = db.query(models.Post).filter(models.Post.id == id).first()

if post == None:
    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No post with
              that Id, {id}")

post.update()
db.commit()

return {"data": post}

I am using python 3.10
What am I doing wrong?

A: It's not the way we update records in sqlalchemy. If you already have an object just replace fields you want to update
post.title = "new title"
post.owner = "new owner"
...
db.commit()

Interesting fact, to fetch single unique record you could just write
post = db.query(models.Post).get(id)

A: Apparently, the post I was pointing to referenced the schema which of course doesn't have the update attribute, I have to differentiate the post I want to update.
This now works for me.
@app.put("/posts/{id}", status_code=status.HTTP_202_ACCEPTED)
def update_post(id: int, ***updated_post: Post***, db: Session = Depends(get_db)):

post = db.query(models.Post).filter(models.Post.id == id).first()

if post == None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No post with
          that Id, {id}")

post.update(updated_post.dict(), synchronize_session=False)
db.commit()

return {"data": ***updated_post***}


text:
Q: The host network interface with the given name could not be found I'm running Windows 10, VirtualBox 5 and Vagrant 1.7.4 and trying to run openedx plateform.
After i run vagrant up i got:
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set network interfaces...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["hostonlyif", "ipconfig", "VirtualBox Host-Only Ethernet Adapter #25", "--ip", "192.168.33.1", "--netmask", "255.255.255.0"]

Stderr: VBoxManage.exe: error: The host network interface with the given name could not be found
VBoxManage.exe: error: Details: code E_INVALIDARG (0x80070057), component HostWrap, interface IHost, callee IUnknown
VBoxManage.exe: error: Context: "FindHostNetworkInterfaceByName(Bstr(pszName).raw(), hif.asOutParam())" at line 204 of file VBoxManageHostonly.cpp

The Vagrant file:
Vagrant.require_version ">= 1.5.3"

VAGRANTFILE_API_VERSION = "2"

MEMORY = 4096
CPU_COUNT = 2

# map the name of the git branch that we use for a release
# to a name and a file path, which are used for retrieving
# a Vagrant box from the internet.
openedx_releases = {
  "openedx/rc/aspen-2014-09-10" => {
    :name => "aspen-fullstack-rc1", :file => "20141010-aspen-fullstack-rc1.box",
  },
  "aspen.1" => {
    :name => "aspen-fullstack-1", :file => "20141028-aspen-fullstack-1.box",
  },
  "named-release/aspen" => {
    :name => "aspen-fullstack-1", :file => "20141028-aspen-fullstack-1.box",
  },
  "named-release/birch.rc1" => {
    :name => "birch-fullstack-rc1", :file => "20150204-birch-fullstack-rc1.box"
  },
  "named-release/birch.rc2" => {
    :name => "birch-fullstack-rc2", :file => "20150211-birch-fullstack-rc2.box"
  },
  "named-release/birch.rc3" => {
    :name => "birch-fullstack-rc3", :file => "20150213-birch-fullstack-rc3.box"
  },
  "named-release/birch" => {
    :name => "birch-fullstack", :file => "20150224-birch-fullstack.box",
  },
  "named-release/birch.1" => {
    :name => "birch-fullstack-1", :file => "birch-1-fullstack.box",
  },
}
openedx_releases.default = {
  :name => "kifli-fullstack", :file => "20140826-kifli-fullstack.box"
}
openedx_releases_vmware = {
  "named-release/birch" => {
    :name => "birch-fullstack-vmware", :file => "20150610-birch-fullstack-vmware.box",
  },
}
openedx_releases_vmware.default = {
  :name => "kifli-fullstack-vmware", :file => "20140829-kifli-fullstack-vmware.box",
}
rel = ENV['OPENEDX_RELEASE']

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # Creates an edX fullstack VM from an official release
  config.vm.box     = openedx_releases[rel][:name]
  config.vm.box_url = "http://files.edx.org/vagrant-images/#{openedx_releases[rel][:file]}"

  config.vm.synced_folder  ".", "/vagrant", disabled: true
  config.ssh.insert_key = true

  config.vm.network :private_network, ip: "192.168.33.10"
  config.hostsupdater.aliases = ["preview.localhost"]

  config.vm.provider :virtualbox do |vb|
    vb.customize ["modifyvm", :id, "--memory", MEMORY.to_s]
    vb.customize ["modifyvm", :id, "--cpus", CPU_COUNT.to_s]

    # Allow DNS to work for Ubuntu 12.10 host
    # http://askubuntu.com/questions/238040/how-do-i-fix-name-service-for-vagrant-client
    vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
  end

  config.vm.provider :virtualbox do |v, override|
  v.gui=true
  end

  ["vmware_fusion", "vmware_workstation"].each do |vmware_provider|
    config.vm.provider vmware_provider do |v, override|
      override.vm.box     = openedx_releases_vmware[rel][:name]
      override.vm.box_url = "http://files.edx.org/vagrant-images/#{openedx_releases_vmware[rel][:file]}"
      v.vmx["memsize"] = MEMORY.to_s
      v.vmx["numvcpus"] = CPU_COUNT.to_s
    end
  end
end

When i comment this line, everything goes well
config.vm.network :private_network, ip: "192.168.33.10"

But i connot access to te LMS and CMS pages (Cuz i comment this line of course)
Any suggestion will be appreciated !

A: Finally ! i solved it ! Here is the solution :
1- I run VBox-Win10-fix-14040.exe as Admin (See this Discussion)
2- Run the VirtualBox.exe as Admin + Compatibility with Windows 7
3- And Vagrant up :)
That's it !

A: Simple solution: Delete the already created (default) Host only Ethernet Adapter from VirtualBox Preferences and run sh launch.sh (if you received error while installing Mirantis Openstack package).
P.S. I don't see a reason why it shouldn't work for Vagrant as well.

A: for windows 7 x86, maybe your virtual box update to latest version. Try to revert back to version 4. can choose release on march or september 2014

A: If you are getting error similar to below while trying to setup Mirantis Openstack package on Virtualbox:
VBoxManage.exe: error: The host network interface name 'VirtualBox Host-Only Et' could not be foundVBoxManage.exe: error: The host network interface named 'VirtualBox Host-Only Et' could not be found
Open the network.sh script and add | sed 's/\r$//' as follows before | egrep:
local found_iface=(execute VBoxManage list hostonlyifs | sed 's/\r$//'| egrep "Name: + $name\$" | awk '/Name/ { $1 = ""; print substr($0, 2) }')
local new_name=(execute VBoxManage list hostonlyifs | sed 's/\r$//' | egrep -A9 "Name: + $name\$" | awk '/Name/ { $1 = ""; print substr($0, 2) }')
local new_ip=(execute VBoxManage list hostonlyifs | sed 's/\r$//'| egrep -A9 "Name: + $name\$" | awk '/IPAddress:/ { print $2 }')
local new_mask=(execute VBoxManage list hostonlyifs | sed 's/\r$//'| egrep -A9 "Name: + $name\$" | awk '/NetworkMask:/ { print $2 }')
local new_dhcp=(execute VBoxManage list hostonlyifs | sed 's/\r$//'| egrep -A9 "Name: + $name\$" | awk '/DHCP:/ { print $2 }')
local id=execute VBoxManage hostonlyif create | sed 's/\r$//'| sed "s/'/_/g" | cut -d "_" -f2 | sed 's/\r$//'| sed "s/^_//" | sed "s/_$//"


text:
Q: Remove image set by Glide and use imageView.setImageBitmap() I have a fragment where at first an Image is set to an imageView using Glide (image url fetched from internet). Then upon click on the imageview a new image can be chose from either gallery or camera intent. the problem is when I try to set the bitmap that I get from OnActivityResult(). The image actually sets but that is overlapped by glide. I need to show image captured from camera/gallery. Any help is appreciated, also if it can be done using Picasso or any other library please suggest that.
  Below is what I have tried so far
the onActivityResult ()
 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK)
    {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            //   onCaptureImageResult((Bitmap) data.getExtras().get("data"));
            onCaptureImageResult(data);
    }
}

private void onCaptureImageResult(Intent data)
{
    if (data != null)
    {
        mImageUri = Uri.parse("file://" + data.getStringExtra(CameraConfiguration.Arguments.FILE_PATH));
    }

    try
    {
        bitmap_image = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), mImageUri);
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap_image.compress(Bitmap.CompressFormat.JPEG, 60, bytes);

        bitmap_image = Bitmap.createScaledBitmap(bitmap_image, (int) (bitmap_image.getWidth() * 0.5), (int) (bitmap_image.getHeight() * 0.5), true);

        ExifInterface ei = new ExifInterface(data.getStringExtra(CameraConfiguration.Arguments.FILE_PATH));
        int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

        switch (orientation)
        {
            case ExifInterface.ORIENTATION_ROTATE_90:
                bitmap_image = (SnappyUtils.rotateImage(bitmap_image, 90));
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                bitmap_image = (SnappyUtils.rotateImage(bitmap_image, 180));
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                bitmap_image = (SnappyUtils.rotateImage(bitmap_image, 270));
                break;

            case ExifInterface.ORIENTATION_NORMAL:

            default:
                break;
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
        Log.d("exception", e.toString());
    }
    ////////////////////// it is showing on iv_logo2 as expected as it does not has anything set by glide//////////////////////////////////////////////////////////////////
    iv_logo.setBackground(null);
    iv_logo.setImageBitmap(bitmap_image);
    iv_logo2.setImageBitmap(bitmap_image);

    ///////////////////////////tried added this by seeing other SO posts //////////////////////////////////////////////////////////////////
    Glide.with(mContext)
            .load(mImageUri)
            .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .skipMemoryCache(true)
            .into(iv_logo);
}

Also please note that this is not the same issue as removing cache of Glide

A: Use:
Glide.with(iv_logo.context)
    .clear(iv_logo);

A: update your code
edit:
iv.logo.setBackground(null);

to:
iv.logo.setImageBitmap(null);

A: After spending lots of time figuring out how to remove image set by Glide, and failing, decided to go old-school and first download the image in phone and set that image as bitmap in my application
asynchtask to download image
private class GetImages extends AsyncTask<Object, Object, Object>
{
    private String requestUrl, imagename_;
    private ImageView view;
    private Bitmap bitmap;
    private FileOutputStream fos;

    private GetImages(String requestUrl, ImageView view, String _imagename_)
    {
        this.requestUrl = requestUrl;
        this.view = view;
        this.imagename_ = _imagename_;
    }

    @Override
    protected Object doInBackground(Object... objects)
    {
        try
        {
            URL url = new URL(requestUrl);
            URLConnection conn = url.openConnection();
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Object o)
    {
        view.setImageBitmap(bitmap);
    }
}


text:
Q: Set QBoxLayout maximum size? I clearly missing something here, please enlighten me.
AttributeError: 'QVBoxLayout' object has no attribute 'setMaximumSize'

I've been reading the Qt Docs for a while but just cant seem to be able to get this to work

A: AFAIK you can't set a maximal size for a layout. Why would you want to - it makes no sense to me (which child widget should the layout limit?)
Regarding setMaximumSize - there's no such method for layouts. There is however, a QLayout::SetMaximumSize constraint which you can set, but this constraint applies to the widget that's laid out with this layout, not to the layout itself. It means that the widget can grow no larger than the maximal size of the layout - so this is quite different from what you need.
I recommend you re-think your real goal - perhaps it can be achieved in some other way. For instance, you can set the maximal size for the individual widgets laid out by your QBoxLayout.

A: You cannot set the maximumSize property directly as it is dynamically determined by the layout. Perhaps you are trying to set the QLayout.SizeConstraint to QLayout.SetMaximumSize? If so, then see the QLayout.setSizeConstraint method. Otherwise, you should call QWidget.setMaximumSize if you want to specify an exact maximum for a given widget.

A: Just as that error tells you, there is no setMaximumSize method on a layout.
QWidgets have that method.


text:
Q: BindingSource not updating when user edits cell in DataGridView (Simple broken example) I'm new to DataGridView and getting frustrated after hours of searching and trying to understand why this simple example is not working.
The code below creates a default editable DataGridView, which is bound to a list of a simple class with DateTime, Double and string members. I'm expecting a user to enter a valid time, and then that time is set to the right public property. It doesn't even work with the string property, let alone the other two.
I've tried to investigate with various events, and the binding source just is never updated.
(For convenience, below is a fully self-contained, functioning source example)
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

public class SimpleDataGridViewBindingForm : Form
{
    private DataGridView dataGridView1 = new DataGridView();
    private BindingSource bs = new BindingSource();

    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new SimpleDataGridViewBindingForm());
    }

    public SimpleDataGridViewBindingForm()
    {
        this.dataGridView1.Dock = DockStyle.Fill;
        this.Width = 400;

        this.Controls.Add(this.dataGridView1);
        this.Load += new EventHandler(Form1_Load);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.bs.DataSource = typeof(WorkLog);
        this.dataGridView1.DataSource = bs;
        this.dataGridView1.CellValidated += dataGridView1_CellValidated;
        this.dataGridView1.CellEndEdit += dataGridView1_CellEndEdit;
        this.dataGridView1.CellValueChanged += dataGridView1_CallValueChanged;

        this.dataGridView1.Columns.Add("Start", "Start");
        this.dataGridView1.Columns.Add("Length", "Length");
        this.dataGridView1.Columns.Add("Description", "Description");
    }

    private void dataGridView1_CallValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        Debug.WriteLine(bs.Current);    // call first, not updated here
    }

    private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
    {
        Debug.WriteLine(bs.Current);    // not updated here also
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        Debug.WriteLine(bs.Current);    // and finally not updated here either
    }
}

public class WorkLog
{
    public DateTime Start;
    public double Length;
    public string Description;

    public WorkLog()
    {
        // Leave fields empty.
    }

    public WorkLog(DateTime start, double seconds, string desc)
    {
        Start = start;
        Length = seconds;
        Description = desc;
    }
}

I'm obviously missing something, even though this code throws no errors. Any ideas?


text:
Q: Kähler metrics for projective space that are not the Fubini-Study metric For projective $N$-space $CP^{N}$, there is a canonical Kähler metric called the Fubini-Study metric. Do there exist other Kähler metrics for $CP^N$. If so, is there any classification of such metrics?
More generally, how does this work for the Grassmanians, or even flag manifolds?

A: This is not  a classification, but you can get a grip on the space of Kahler metrics on $CP^N$ using Bergman metrics and the Segre embeddings.
To explain this conside let $\{s_\alpha\}$ be a basis of homogeneous polynomials of degree k in N+1 variables.  This gives an embedding $CP^N\to CP(H^0(O(k)))$.  Now define a metric on H^0(O(k)) by declaring that the s_i are orthonormal.  This defines a Fubini-Study metric on P(H^0(O(k)) and which pulls back to a metric on $\omega'$ on $CP^N$.
Now it can be proved that any Kahler metric $\omega$ on $CP^N$ is the limit of metrics of the form $k^{-1}\omega'$ for suitable bases $\{s_\alpha\}$ as $k$ tends to infinity (You can take the $\{s_\alpha\}$ to be orthonormal with respect to the $L^2$-metric induced by $\omega$).
In fact there is nothing special about $CP^N$ here.  The above works for any projective manifold $X$ with ample line bundle $L$.

A: Every complex manifold that admits one Kahler metric $w$ admits a lot of them, indeed $w+i\partial \bar \partial f$ is a Kahler metric if the second derivatives of $f$ are not too large. This is why, asking if one can classify Kahler metrics on $\mathbb CP^n$ is more-less equivalent to ask if one can classify functions on $\mathbb CP^n$. Can we classify functions? It depends on what you want to know.
Even if we want to classify Kahler metrics on $\mathbb C^n$, what can this mean? One analogy can be helpful here. Namely this question is somewhat similar to asking if we can classify convex functions on $\mathbb R^n$. Such a function $f$ always define a Hessian metric on $\mathbb R^n$ given by $g_{ij}=\frac{\partial^2 f}{\partial x_i \partial x_j}$. So, can we classify convex functions?


text:
Q: source value 1.5 is obsolete I've just switched to Android Studio from Eclipse and am getting this warning during builds. However, I don't have any idea what it means. V1.5 of what? There's definitely not enough info that I can find to pinpoint a specific point in the code (if that's what it is).
I might mention that this is an old project that goes back to Android 2.x days, but currently targets only V4.x+ and has a min-sdk of 14.

A: Figured it out with help from above comments: had to install the Java 1.7 JDK and then change Project Structure settings to point to that directory.


text:
Q: Programa dá crash após alocação na pilha e chamada em C Estou tentando fazer um simples programa: aloca na pilha um inteiro, chama scanf da biblioteca em C e o imprime na tela. Já fiz disassembly do mesmo em C, e tento reimplementá-lo, sem sucesso. Testei a alocação sem fazer qualquer chamada em C, sem qualquer erro. O problema é a convenção x64 da Microsoft. O que há de errado com o seguinte programa?
bits 64
section .data
local1 db 'Hello. Input a number, please.',10,'> ', 0
local2 db '%u', 0
local3 db 10,'You input: %u', 0

section .text
extern printf
extern scanf
extern exit
extern getch

global WinMain
WinMain:
    push rbp
    mov rbp, rsp
    mov dword[rbp - 4], 0
    ; = push dword 0 em 64 bits
    mov rcx, local1
    call printf ;imprime o "pedido"
    mov rcx, local2
    lea rdx, [rbp - 4] ;endereço da variável alocada
    call scanf
    mov rcx, local3
    call printf
    call getch
    xor rcx, rcx ;coloca o valor de saída como 0
    call exit ;sai
    mov rsp, rbp
    pop rbp ;stack frame de saída
    leave

PS.: (Considere | uma quebra de linha) Já tentei trocar mov dword[rbp - 4], 0 por sub rsp, 4 | mov dword[rsp-4], 0 e push word 0 | push word 0 (push dword é ilegal em 64 bits).

A: Você comparou o código gerado pelo compilador com o código que você escreveu? Se colar aqui o assembly gerado, pode ajudar.
De qualquer forma antes de chamar uma função você deve alocar espaço na pilha para 4 parâmetros, aqueles que são passados em rcx, rdx, r8, r9, mesmo que haja menos parâmetros.
Assim a função chamada terá espaço para "derramar" (spill) na pilha os valores passados e usar esses registradores para outras coisas (para chamar outras funções, obter ponteiros para esses parâmetros, etc.)
Vi que você só falou em sub rsp, 4, que avança a pilha em 4 bytes (para o seu inteiro, e nada para os parâmetros), o que é insuficiente. Além disso, a pilha tem que ficar alinhada em 16 bytes entre chamadas de função. Lembrando que call faz push de 8 bytes, então cada função deve ajustar a pilha com 16n+8 bytes para restaurar o alinhamento, sendo n o número de variáveis de 64 bits que você quer.
Então sugiro começar a função com sub rsp, 88 (16*5 + 8, deixando assim espaço para 5 valores, 4 para as chamadas e 1 para sua variável local) e esquecer todo o resto da manipulação de pilha (usar só mov daí em diante).
Se for fazer push do rbp, ele deve servir como o + 8 da fórmula acima, então só precisaria sub rsp, 80.
Obs.: trechos de código não testados.


text: Q: installing ubuntu on windows and LVM option While installing ubuntu on windows , during installation it is giving me 2 options to work within the advance section either , installation with LVM or none. So, should I go with LVM or normal installation


text:
Q: Setting custom kernel for CNN in pytorch Is there a way to specify our own custom kernel values for a convolution neural network in pytorch? Something like kernel_initialiser in tensorflow? Eg. I want a 3x3 kernel in nn.Conv2d with initialization so that it acts as a identity kernel -
0 0 0
0 1 0
0 0 0
(this will effectively return the same output as my input in the very first iteration)
My non-exhaustive research on the subject -
I could use nn.init but it only has some pre-defined kernel initialisaition values.
I tried to follow the discussion on their official thread but it doesn't suit my needs.
I might have missed something in my research please feel free to point out.

A: I think an easier solution is to :
    deconv = nn.ConvTranspose2d(
        in_channels=channel_dim, out_channels=channel_dim,
        kernel_size=kernel_size, stride=stride,
        bias=False, padding=1, output_padding=1
    )
    deconv.weight.data.copy_(
        get_upsampling_weight(channel_dim, channel_dim, kernel_size)
    )

in other words use copy_

A: Thanks to ptrblck I was able to solve it.
I can define a new convolution layer as conv and as per the example I can set the identity kernel using -
weights = ch.Tensor([[0, 0, 0], [0, 1, 0], [0, 0, 0]]).unsqueeze(0).unsqueeze(0)
weights.requires_grad = True

conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1, bias=False)

with ch.no_grad():
    conv.weight = nn.Parameter(weights)

I can then continue to use conv as my regular nn.Conv2d layer.


text:
Q: Is it possible to access resources in another APK without using content providers? I thought that it is impossible to access resources contained in other APK unless content providers are used. However, I stumbled upon an app called Better Keyboard. It uses skins, so I decided to download an example of a skin.
An example skin really surprised me. It contains almost no code, declares only an activity and no content providers. Nontheless it contains resources and they are apparently somehow accessed from Better Keyboard app if the APK with the skin gets installed. So how is it done?

A: Try this
 PathClassLoader loader =
 new PathClassLoader ("/data/app/com.skin.apk", null,PathClassLoader.getSystemClassLoader());
 InputStream f = loader.getResourceAsStream("res/drawable/icon.png");
 Bitmap bitmap=BitmapFactory.decodeStream(f);
 BitmapDrawable b=new BitmapDrawable(bitmap);
 mButton.setBackgroundDrawable(b);

A: I believe you're looking for
Resources res = mPackageManager.getResourcesForApplication("org.example.foo");
http://developer.android.com/reference/android/content/pm/PackageManager.html#getResourcesForApplication%28java.lang.String%29

A: It is possible by using getresoucesforapplication and you need res.getidentifier to retrieve the resource Id. However, It seem not work when retrieving style resource.


text:
Q: Bootstrap height container with long text I downloaded Bootstrap template from: http://startbootstrap.com/templates/scrolling-nav/

Scrolling Nav

                    Click me!

This demo is the same sort of scrolling navigation menu we use in our Grayscale theme. Whenever you want to use the page scrolling feature, make sure the link points to an ID (#about for example), and that the parent of the link has the class .page-scroll. See how the button above and the menu bar links are formatted for a working example.

About Section

Services Section

If the content of the About Section is too long it's overlap on the Services Section, so I have a part of the About section on the Services Sections.
Services section : contains a form where the client can send me information, but since the About Section Overlap, some of the text of the About are on the Form of Services
I added Important! but it didn't work, any help please

A: Remove css height:100% in the scrolling-nav.css in all three sections.
That will fix the bug

A: Hi there are two ways of doing this
1) Add this class at the at the end in scrolling-nav.css
.about-section {
    background: none repeat scroll 0 0 #EEEEEE;
    height: auto !important;
    padding-bottom: 15px !important;
}

or go to line no 36 in scrolling-nav.css and update height: 100%; with height: auto;
.about-section {
    background: none repeat scroll 0 0 #EEEEEE;
    height: auto;
    padding-bottom: 15px;
    padding-top: 150px;
    text-align: center;
}

you can also update .contact-section and .services-section like this to fix this issue completely.


text:
Q: Which version of Chrome supports ORTC? I heard Google is having plans to support ORTC standards from version 38 or 39, but haven't seen any confirmation on it.

A: https://bloggeek.me/google-roadmap-webrtc/
This was on the roadmap but did not happen.
Programmatically , you can check for the existence of the RTCRtpSender object. It's not there in the canary version (43 as of today) of chrome even.