text:
Q: Expected number of cuts before a stick is halved A stick of unit length is put horizontally from left to right. Cut this stick at a uniformly randomly chosen position at each step and keep the left remaining part. Keep cutting until the length of the remaining part is smaller than 1/2 of the original length. Find the expected number of cuts.

A: The length of the remaining part is the product $Z_n = \prod_{k=1}^n X_k$ of i.i.d. random variables $X_1, X_2, \ldots$, each of which is uniformly distributed on $(0,1)$, and $N=\min\{n \geq 1 : Z_n < 1/2\}$ is a stopping time with respect to the natural filtration.
Then

*

*$Z_N$ is uniformly distributed on $(0,1/2)$

*$\log(X_n)$ is integrable with expected value $-1$

*$N \leq \min\{n \geq 1 : X_n < 1/2\}$ which is a geometric random variable and therefore integrable.

The above justifies the use of Wald's equation for stopping times, so that $$\mathbb{E}[N] = \frac{\mathbb{E}[\log(Z_N)]}{\mathbb{E}[\log(X_1)]} = -2\int_0^{1/2}\log x\,dx = 1 + \log(2)$$

A: Let $E_{r}$ be the expected number of cuts before the remainder is smaller than $r$ times the original length. We have the following recurrence relationship:
$$E_{r} = r  + \int_{r}^{1} (1+ E_{(r/x)}) \;dx= \\=1 + \int_{r}^{1}  E_{(r/x)}  \;dx $$
With $E_{0} = \infty $ and $E_{1} = 1$.
Explanation: Assuming the first cut gives a remainder of length $r$ or less  gives expected number of cuts $1$. Assuming the remainder is of length  $x \in [r,1]$ gives the expected number of cuts $1$ + the number of cuts required to reach $r/x$ times the remaining length.
This gives us: $$E_{r} = 1 - \log(r)\\ E_{\frac{1}{2}} = 1 + \log(2)$$

Proof that the solution $E_{r} = 1-\log(r)$ is uniquely determined by the recurrence and constraints:
Let $F_{r}$ be defined by $F_{\log(r)} = E_{r}$. We have $$F_{\log(r)} = 1 + \int_{r}^{1}  F_{\log(r)-\log(x)} dx $$ By changing variables as: $\log(r)\rightarrow r$, $\log(x)\rightarrow x\;$
(or  $r\rightarrow e^r$, $x\rightarrow e^x$) the equation becomes:
$$F_{r} = 1 + \int_{r}^{0}  e^x F_{(r-x)} dx $$
An additional change of $x \rightarrow (r-x)$ gives:
$$F_{r} = 1 + \int_{0}^{r}  -F_{x} \;e^{r-x} \; dx $$
with our constraints becoming $F_{-\infty} = \infty$ and $F_{0} = 1$. Assume this has more than one solution (as our solution gives $F_{r} = 1 - r$). Then the difference between the two solutions satisfies:
$$D_{r} =  \int_{0}^{r}  -D_{x} \;e^{r-x} \; dx \\
D_0 = 0 $$
Differentiating the equation by $r$ we get:
$$D_{r}' = -D_r \; e^{r-r} +  \int_{0}^{r}  -D_{x} \;e^{r-x} \; dx = \\=-D_{r} + D_{r} = 0 $$
From this we get $D_{r} = c$, which combined with $D_{0} = 0 $ gives $D_{r} = 0$. Therefore, our solution is unique.

A: The simulation results (with R) also support the above results:
set.seed(1)
cuts <- replicate(100000,
               {
                 x <- 1
                 i <- 0
                 while (x >= 1/2) {
                   x <- runif(1, 0, x) # keep the left part
                   i <- i + 1
                 }
                 i
               }
               )
 mean(cuts)
 # [1] 1.69461
 1 + log(2)
 # [1] 1.693147

It's interesting to observe how the distribution of cuts looks like:
hist(cuts)


text:
Q: Python: Adding excel file to an access database I am using pyodbc to access an access (accdb) file. I want to add an excel workbook into the access database programatically, but cannot find an API to do so. Here is my current code:
import pyodbc
DBFile = r'C:\Documents and Settings\IA.accdb'
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBFile)

exFile = r'C:\Documents and Settings\IA_2006.xls'
conn1 = pyodbc.connect('DRIVER={Microsoft Excel Driver \
                       (*.xls)};DBQ='+exFile,autocommit=True)

cursor = conn.cursor()
####IA_1 is a table within IA.accdb
cursor.execute('select * from IA_1')
row = cursor.fetchone()
####For debugging, print a line
if row:
        print row

How should I import the data from the excel file (IA_2006.xls) into the IA.accdb?

A: It seems like you got to a certain point and gave up.
Don't give up! :-)
You've made the connection to the Excel spreadsheet, now you need to read it*.
curs1 = conn1.cursor()
# the following returns list of tuples
excel_results = curs1.execute('select [a_column]
                               from [Sheet1$]').fetchall()

Then you can insert to your MS Access db, e.g.:
curs.executemany('insert into mytable (mycolumn) values (?)', excel_results)
conn.commit()

*If in doubt, Excel sheet names can be found by running the following:
for row in curs1.tables():
    print row.table_name

redpajama_set_name: RedPajamaStackExchange


text:
Q: Average of list of doubles I am having some issues writing a Haskell function. I am trying to get the average of a list of triples of doubles. when I divide by just the ' length xs ' ,  I get an error that the length is an Int, so I tried using fromIntegeral and its not giving me an error but not giving the right answer. For example if I test,
averages [(2.0,1.0,3.0)] it returns [6.0]
averages :: [(Double, Double, Double)] -> [Double]
averages xs = [ (x+y+z) / fromIntegral (length xs) | (x,y,z) <- xs ]

A: You are missunderstanding your own type function, the avarage is always over 3, because you have a list of triplets (or tuples of three?):
averages :: [(Double, Double, Double)] -> [Double]
averages xs = [ (x+y+z) / 3 | (x,y,z) <- xs ]

$> averages [(8,6,7), (4,4,10), (1,1,1)]
=> [7.0,6.0,1.0]

A: Note that length xs will evaluate to 1 when you evaluate averages [(2.0,1.0,3.0)]. The list contains a single element: a tuple. Since you are averaging the elements of a triplet, you can just divide by 3.

A: Others have explained why you're getting the wrong answers, but I would like to urge you to break up your problem into two pieces.
averageTriple :: (Double, Double, Double) -> Double
averageTriple (x,y,z) = ...

averageTriples :: [(Double, Double, Double)] -> [Double]
averageTriples ts = ... -- use averageTriple here


text:
Q: Could not login I can not login with my Stack Exchange account it keep saying no account found.

Is this just my account?

Yeah I double check the email address and password.
So as it turns out that I can login via other oAuth provider Stack Exchange. I think this is a bug.

A: Okay, click the button that says Log in using another OpenId, then click login with StackExchange, login, and you should be good to go. This happend to me, too, and that let me login.

A: This was a server side issue that has been fixed as of the last build-out, thanks for reporting it.


text: Q: how to enable Incremental compilation in C++ in VS code how to enable Incremental compilation in C++ in VS code,now i do not change my code, but when I run ,the code will be recompiled, waste a lot of time, now i want to set Incremental compilation,but i can not.


text:
Q: Pandas groupby(dictionary) not returning intended result I'm trying to group the following data:
>>> a=[{'A': 1, 'B': 2, 'C': 3, 'D':4, 'E':5, 'F':6},{'A': 2, 'B': 3, 'C': 4, 'D':5, 'E':6, 'F':7},{'A': 3, 'B': 4, 'C': 5, 'D':6, 'E':7, 'F':8}]
>>> df = pd.DataFrame(a)
>>> df
   A  B  C  D  E  F
0  1  2  3  4  5  6
1  2  3  4  5  6  7
2  3  4  5  6  7  8

With the Following Dictionary:
dict={'A':1,'B':1,'C':1,'D':2,'E':2,'F':2}

such that
df.groupby(dict).groups

Will output
{1:['A','B','C'],2:['D','E','F']}

A: Needed to add the axis argument to groupby:
>>> grouped = df.groupby(groupDict,axis=1)
>>> grouped.groups
{1: ['A', 'B', 'C'], 2: ['D', 'E', 'F']}


text:
Q: Why does Observable.Generate() throw System.StackOverflowException? I´m writing a C# (.NET 4.5) application that is used to aggregate time based events for reporting purposes. To make my query logic reusable for both realtime and historical data I make use of the Reactive Extensions (2.0) and their IScheduler infrastructure (HistoricalScheduler and friends).
For example, assume we create a list of events (sorted chronologically, but they may coincide!) whose only payload ist their timestamp and want to know their distribution across buffers of a fixed duration:
const int num = 100000;
const int dist = 10;

var events = new List<DateTimeOffset>();
var curr = DateTimeOffset.Now;
var gap = new Random();

var time = new HistoricalScheduler(curr);

for (int i = 0; i < num; i++)
{
    events.Add(curr);
    curr += TimeSpan.FromMilliseconds(gap.Next(dist));
}

var stream = Observable.Generate<int, DateTimeOffset>(
    0,
    s => s < events.Count,
    s => s + 1,
    s => events[s],
    s => events[s],
    time);

stream.Buffer(TimeSpan.FromMilliseconds(num), time)
    .Subscribe(l => Console.WriteLine(time.Now + ": " + l.Count));

time.AdvanceBy(TimeSpan.FromMilliseconds(num * dist));

Running this code results in a System.StackOverflowException with the following stack trace (it´s the last 3 lines all the way down):
mscorlib.dll!System.Threading.Interlocked.Exchange<System.IDisposable>(ref System.IDisposable location1, System.IDisposable value) + 0x3d bytes
System.Reactive.Core.dll!System.Reactive.Disposables.SingleAssignmentDisposable.Dispose() + 0x37 bytes
System.Reactive.Core.dll!System.Reactive.Concurrency.ScheduledItem<System.DateTimeOffset>.Cancel() + 0x23 bytes
...
System.Reactive.Core.dll!System.Reactive.Disposables.AnonymousDisposable.Dispose() + 0x4d bytes
System.Reactive.Core.dll!System.Reactive.Disposables.SingleAssignmentDisposable.Dispose() + 0x4f bytes
System.Reactive.Core.dll!System.Reactive.Concurrency.ScheduledItem<System.DateTimeOffset>.Cancel() + 0x23 bytes
...

Ok, the problem seems to come from my use of Observable.Generate(), depending on the list size (num) and regardless of the choice of scheduler.
What am I doing wrong? Or more generally, what would be the preferred way to create an IObservable from an IEnumerable of events that provide their own timestamps?

A: (update - realized I didn't provide an alternative: see at bottom of answer)
The problem is in how Observable.Generate works - it's used to unfold a corecursive (think recursion turned inside out) generator based on the arguments; if those arguments end up generating a very nested corecursive generator, you'll blow your stack.
From this point on, I'm speculating a lot (don't have the Rx source in front of me) (see below), but I'm willing to bet your definition ends up expanding into something like:
initial_state =>
generate_next(initial_state) =>
generate_next(generate_next(initial_state)) =>
generate_next(generate_next(generate_next(initial_state))) =>
generate_next(generate_next(generate_next(generate_next(initial_state)))) => ...

And on and on until your call stack gets big enough to overflow. At, say, a method signature + your int counter, that'd be something like 8-16 bytes per recursive call (more depending on how the state machine generator is implemented), so 60,000 sounds about right (1M / 16 ~ 62500 maximum depth)
EDIT: Pulled up the source - confirmed: the "Run" method of Generate looks like this - take note of the nested calls to Generate:
protected override IDisposable Run(
    IObserver<TResult> observer,
    IDisposable cancel,
    Action<IDisposable> setSink)
{
    if (this._timeSelectorA != null)
    {
        Generate<TState, TResult>.α α =
                new Generate<TState, TResult>.α(
                     (Generate<TState, TResult>) this,
                     observer,
                     cancel);
        setSink(α);
        return α.Run();
    }
    if (this._timeSelectorR != null)
    {
        Generate<TState, TResult>.δ δ =
               new Generate<TState, TResult>.δ(
                   (Generate<TState, TResult>) this,
                   observer,
                   cancel);
        setSink(δ);
        return δ.Run();
    }
    Generate<TState, TResult>._ _ =
             new Generate<TState, TResult>._(
                  (Generate<TState, TResult>) this,
                  observer,
                  cancel);
    setSink(_);
    return _.Run();
}

EDIT: Derp, didn't offer any alternatives...here's one that might work:
(EDIT: fixed Enumerable.Range, so stream size won´t be multiplied by chunkSize)
const int num = 160000;
const int dist = 10;

var events = new List<DateTimeOffset>();
var curr = DateTimeOffset.Now;
var gap = new Random();
var time = new HistoricalScheduler(curr);

for (int i = 0; i < num; i++)
{
    events.Add(curr);
    curr += TimeSpan.FromMilliseconds(gap.Next(dist));
}

    // Size too big? Fine, we'll chunk it up!
const int chunkSize = 10000;
var numberOfChunks = events.Count / chunkSize;

    // Generate a whole mess of streams based on start/end indices
var streams =
    from chunkIndex in Enumerable.Range(0, (int)Math.Ceiling((double)events.Count / chunkSize) - 1)
    let startIdx = chunkIndex * chunkSize
    let endIdx = Math.Min(events.Count, startIdx + chunkSize)
    select Observable.Generate<int, DateTimeOffset>(
        startIdx,
        s => s < endIdx,
        s => s + 1,
        s => events[s],
        s => events[s],
        time);

    // E pluribus streamum
var stream = Observable.Concat(streams);

stream.Buffer(TimeSpan.FromMilliseconds(num), time)
    .Subscribe(l => Console.WriteLine(time.Now + ": " + l.Count));

time.AdvanceBy(TimeSpan.FromMilliseconds(num * dist));

A: OK, I´ve taken a different factory method that doesn´t require lamdba expressions as state transitions and now I don´t see any stack overflows anymore. I´m not yet sure if this would qualify as a correct answer to my question, but it works and I thought I´d share it here:
var stream = Observable.Create<DateTimeOffset>(o =>
    {
        foreach (var e in events)
        {
            time.Schedule(e, () => o.OnNext(e));
        }

        time.Schedule(events[events.Count - 1], () => o.OnCompleted());

        return Disposable.Empty;
    });

Manually scheduling the events before (!) returning the subscription seems awkward to me, but in this case it can be done inside the lambda expression.
If there is anything wrong about this approach, please correct me. Also, I´d still be happy to hear what implicit assumptions by System.Reactive I have violated with my original code.
(Oh my, I should have checked that earlier: with RX v1.0, the original Observable.Generate() does in fact seem to work!)


text:
Q: how to profile blocking code in java – measure execution time instead of CPU time I am trying to profile that is often blocking in either database and rest calls. The code is not cpu bound. The following sample junit methods should illustrate the issue:
@RepeatedTest(10)
void fast() throws InterruptedException {
    Thread.sleep(100);
}

@RepeatedTest(10)
void slow() throws InterruptedException {
    // imagine a slow database or rest call or any other blocking code
    Thread.sleep(1000);
}

I am using IntelliJ and Java Flight Recorder. I expect that method fast is reported as using about 10% of execution time and method slow is using about 90% of execution time. But they are not reported at all because they don't eat CPU time.
How can I profile the real execution time that includes waiting time in blocking code instead of CPU time only?

A: You need a profiler that understands the semantics of JDBC and HTTP calls. For example, with JProfiler, the profiling agent captures a synthetic Net I/O thread state that is included when the thread status selector is set to "All states".

Disclaimer: My company develops JProfiler

A: Async profiler is an excellent, free, and very lightweight tool for JVM profiling. In typical settings, it indeed measures on-CPU time but it has an option to do "Wall-clock" profiling: https://github.com/jvm-profiling-tools/async-profiler#wall-clock-profiling
You can experiment with that and see if that gives you better results.


text:
Q: Reading txt file, then count unique words and put them into arraylist I got this assignment for school and all my other methods are working just fine, but reading unique words just doesn't work for me.
My method for reading txtfile:
public void lesBok(String filnavn) throws Exception {
    File file = new File(filnavn);
    Scanner innlestfil = new Scanner(file);
    while (innlestfil.hasNextLine()) {
        String s = innlestfil.nextLine();
        if((ord.contains(s))){
              for(i = 0; i < ord.size(); i++){
                if(ord.get(i).toString().equalsIgnoreCase(s)){
                  ord.get(i).oekAntall();
                }
              }
            }else{
                Ord nyttOrd = new Ord(s);
                ord.add(nyttOrd);
              }
        }
    }

It reads the txt file, but the problem is that it doesn't difference from unique words.
So if a txt file is for example
hey
My
name
is
hey
It reads 5 words instead of 4.
When the same word pops up, I want it to run this method:
public void oekAntall(){
    antall ++;

A: If you are not specifically required to read it in one word at a time, why not read the entire line and then parse it? I would recommend the StringTokenizer class to accomplish this. I'll write out some pseudo code to show what I mean.
String inputLine = sc.readLine();
StringTokenizer st = new StringTokenizer(inputLine, " "); //parse on spaces
while(st.hasMoreTokens()) {
    //Parse tokens
    array[x] = st.nextToken();
}


text:
Q: For every $n$ there exists $m$ such that $m/n$ is an upper bound but $(m-1)/n$ is not This is a problem discussed in Analysis 1 by Terence Tao.

$E$ is a non-empty set of Real numbers. $ n\geq 1$, $L,K$ are two integers such that $L<K$. Let $\frac{L}{n}$ is not an upper bound of $E$ but $\frac{K}{n}$ is an upper bound. It is required to prove that:
There exists an integer $m$ where $L<m \leq K$ such that $\frac{m}{n}$ is an upper bound for $E$ but  $\frac{m-1}{n}$ is not.

Suppose $E=(0,1)$ and $n=2$. Let $L=1 ,K=3$ then $L,K$ satisfies the required properties and we can find $m$ as 2. Then we can verify the result.
It is given as a hint to prove by contradiction.
So we can assume that There exist integers $ L,M$ satisfying the conditions but for every integer $m$ with $L<m \leq K$, $ \frac{m}{n}$ cannot be an upper bound for $E$ .That means  there exists $  x \in E $ such that $x >\frac{m}{n}$ .
I can't proceed from this step. It is also given that we have to use induction.

A: Define the set $ NE = \{n x  \ | \ x \in E\} $. Now clearly $ x \le  \frac {K}{n}$ for every $x \in E$ and hence $ nx \le K  $ whence it follows that $K$ is an upper bound for $ NE $. Then $l =  \sup NE$ exists.
Now consider the set $A = \{ n \in \Bbb N \ | n \ge l \ \} $. This set is non-empty since it contains $K$. By the Well-Ordering principle this set has a least element and call this, $m$.
Firstly,
$$\forall x\in E \;\; m \ge l \ge nx \implies x \le \frac m n \;\; \forall x\in E  $$
Secondly, suppose $ \dfrac{m - 1}{n} $ is an upper bound for $E$. Then,
$$ \forall x \in E \;\; x \le \dfrac{m - 1}{n} \implies nx \le m - 1  $$
Then $m - 1$ is an upper bound for  $NE$ and hence $l \le m - 1$. But then $m - 1 \in A$ and $m - 1 \lt m$ contradicting the choice of $m$. So there you have it.
I have not used induction but I have used the equivalent condition the Well-Ordering Principle.

Note all we have done here is to divide the real line into segments of size $\frac 1 n$. You can obviously do this. This gives an "index" if you will of the real line. Now the supremum of the set $E$ exists and is on the real line. But this must lie between two indices. That is $ \dfrac{m - 1}{n} \lt l \le \dfrac{m }{n}$.


text:
Q: How to get datacontext of an event emitting item control? I have a bunch of buttons being render inside an items control. I want to get access to the data context of the clicked button. How can I achieve that?
Model:
public class RunYear
{
    public RunYear(int year)
    {
        Year = year;
        Months = new Month[3];
    }
    public int Year { get; set; }
    public Month[] Months { get; set; }
}

public class Month
{
    public int ColumnIndex { get; set; }
    public string MonthName { get; set; }
    // some other props
}

Code behind:
public partial class MainWindow : Window
{
    private ObservableCollection<RunYear> _years = new ObservableCollection<RunYear>();
    public ObservableCollection<RunYear> Years { get{return _years; } }
    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
        GenerateData();
    }

    private void GenerateData()
    {
        for (int i = 2010; i < 2015; i++)
        {
            var runYear = new RunYear(i);
            runYear.Months[0] = new Month() { ColumnIndex = 0, MonthName = $"Jan {i}" };
            runYear.Months[1] = new Month() { ColumnIndex = 1, MonthName = $"Feb {i}" };
            runYear.Months[2] = new Month() { ColumnIndex = 2, MonthName = $"Mar {i}" };
            Years.Add(runYear);
        }
    }

    public void OnClick(object sender, RoutedEventArgs args)
    {
        // how do I get the databound item?
        var cp = sender as ContentPresenter; //doesn't work
        var vm = cp?.Content as Month;
    }
}

XAML:
    <Grid>
    <ItemsControl Name="icYears" ItemsSource="{Binding Years}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="70" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="75"/>
                    </Grid.RowDefinitions>
                    <DockPanel Grid.Column="0" Grid.Row="0" >
                        <TextBox IsReadOnly="True" TextAlignment="Center" Text="{Binding Year}" />
                    </DockPanel>

                    <ItemsControl Grid.Column="1" Name="icMonths" ItemsSource="{Binding Months}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <Grid >
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="75"></RowDefinition>
                                    </Grid.RowDefinitions>
                                </Grid>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                        <ItemsControl.ItemContainerStyle>
                            <Style>
                                <Setter Property="Grid.Column" Value="{Binding ColumnIndex}" />
                            </Style>
                        </ItemsControl.ItemContainerStyle>
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <Button Click="OnClick"  Content="{Binding MonthName}"  Padding="2" Margin="2"/>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

A: Do you mean like this?
private void Button_Click(object sender, RoutedEventArgs e)
{
    var vm = (sender as FrameworkElement).DataContext;


text:
Q: Spring Boot Project cannot run by IntelliJ IDE Edit:
Here's the WebApplication file:
@SpringBootApplication
@EnableAsync
@EnableAutoConfiguration
public class WebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplication.class);
    }
}

I am using IntelliJ(15.0.2) to run a spring boot project,
It is working properly when I execute java -jar spring-boot-sample.war
Unfortunately it failed to run by IDE and complained Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
The error details are as follows:
[2016-07-25 12:32:46.979] boot - 5719 ERROR [restartedMain] --- SpringApplication: Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
    at com.rentacoder.WebApplication.main(WebApplication.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:185)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 13 more
[2016-07-25 12:32:47.014] boot - 5719  INFO [restartedMain] --- ClasspathLoggingApplicationListener: Application failed to start with classpath: [file:/Users/hzhang/work/workplace/IdeaProjects/RHS/target/classes/]

Below is the dependencies settings in the POM file:
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

Did I miss something in POM settings?

A: As a quick workaround, you can add a jar configuration that uses the resulting jar from target folder.
In this way you can start the application normally or in debug mode.
As a drawback for this approach: you won't have the hotswap available and you will see the changes only after a maven build. But in this case I usually add in the add jar run configuration window in before section a maven goal with "clean package -DskipTests" so each time I press run I will have the latest changes available.
This is a quickfix; the problem can be solved in other ways - I done it some times ago but I can't remember exactly what was the problematic dependency - you need to dig a little in Spring source code with some debugging around the methods from which the exception jumps.

A: How did you set the Configuration on IntelliJ? Since it's a WAR file, you'd need to have a web server container. Your pom has spring-boot-starter-tomcat, so you'll need to create a Tomcat Server configuration. This is a paid feature in IntelliJ, so you probably can't do it with the community edition.
A work-around is to create a Remote Debugging on your war file:
http://blog.trifork.com/2014/07/14/how-to-remotely-debug-application-running-on-tomcat-from-within-intellij-idea/


text:
Q: Overlap in the data - Spark Scala
I want to find the overlap between each brand like when I compare HORLICKS VS BOOST, I will have to find whats HORLICKS only percentage , BOOST ONLY and their intersection.Its basically a venn diagram problem.I have computed for one combination. But I want to compute for all combination , like HORLICKS vs BOOST,HORLICKS VS nESTLE , HORLICKS vs BOURNVITA etc.
Can somebody help me ? I am new to spark
Below is my code:
  val A_storeList = sourceDf.where(col("CATEGORY").equalTo(item1(0)) and col("SUBCATEGORY").equalTo(item1(1)) and col("product_char_name").equalTo(item1(2)) and col("product_charval_dsc").equalTo(item1(3))).select("store_id").collect().map(_(0)).distinct
  val B_storeList = sourceDf.where(col("CATEGORY").equalTo(item2(0)) and col("SUBCATEGORY").equalTo(item2(1)) and col("product_char_name").equalTo(item2(2)) and col("product_charval_dsc").equalTo(item2(3))).select("store_id").collect().map(_(0)).distinct
  val aAndBstoreList = A_storeList.intersect(B_storeList)
  val AunionB_storeList = A_storeList.union(B_storeList).distinct
  val AOnly_storeList = A_storeList.diff(B_storeList)
  val Bonly_storeList = B_storeList.diff(A_storeList)
  val subSetOfSourceDf = sourceDf.withColumn("Versus",lit(item1(3)+"Vs"+item2(3)))
  val A = subSetOfSourceDf.where(col("store_id").isin(A_storeList:_*)).withColumn("Venn",lit("A"))
  val B = subSetOfSourceDf.where(col("store_id").isin(B_storeList:_*)).withColumn("Venn",lit("B"))
  val AandB = subSetOfSourceDf.where(col("store_id").isin(aAndBstoreList:_*)).withColumn("product_charval_dsc",when(col("product_charval_dsc").equalTo(item1(3)),item1(3)+" and "+item2(3)).when(col("product_charval_dsc").equalTo(item2(3)),item1(3)+" and "+item2(3)).otherwise(col("product_charval_dsc"))).withColumn("Venn",lit("AintersectB"))
  val AunionB = subSetOfSourceDf.where(col("store_id").isin(AunionB_storeList:_*)).withColumn("product_charval_dsc",when(col("product_charval_dsc").equalTo(item2(3)),item1(3)+" and "+item2(3)).when(col("product_charval_dsc").equalTo(item1(3)),item1(3)+" and "+item2(3)).otherwise(col("product_charval_dsc"))).withColumn("Venn",lit("AunionB"))
  val AOnly = subSetOfSourceDf.where(col("store_id").isin(AOnly_storeList:_*)).withColumn("Venn",lit("AOnly"))
  val BOnly = subSetOfSourceDf.where(col("store_id").isin(Bonly_storeList:_*)).withColumn("Venn",lit("BOnly"))
  val allInOne = A.union(B.union(AandB.union(AunionB).union(AOnly.union(BOnly))))

  val divisor = allInOne.where((col("Venn").equalTo("A").and(col("product_charval_dsc").equalTo(item1(3)))) or (col("Venn").equalTo("B").and(col("product_charval_dsc").equalTo(item2(3)))) )
    .groupBy("CATEGORY","SUBCATEGORY","product_char_name").agg(sum("SALVAL") as "TOTAL")

  val finalDf1 = allInOne.groupBy("CATEGORY","SUBCATEGORY","product_char_name","product_charval_dsc","Venn")
    .agg(sum("SALVAL") as "SALVAL")
    .where(col("product_charval_dsc").equalTo(item1(3)) or col("product_charval_dsc").equalTo(item2(3)) or col("product_charval_dsc").equalTo(item1(3)+" and "+item2(3)))

  val outputDf =finalDf1.join(divisor,Seq("CATEGORY","SUBCATEGORY","product_char_name"))
    .withColumn("SALE_PERCENT",col("SALVAL")/col("TOTAL") multiply(100)).withColumn("Versus",lit(item1(3)+" Vs "+item2(3)))

With this Code I have generated output. But I want to how to do this for all combination.
Generated Result:


text:
Q: reactjs - get a subset of an nested array objects I have a variable like this, which I am passing as an input into the react app.
const options = [{"label": "Gryffindor", "value": "Gryffindor", "description": "Daring, strong nerve and chivalry.", "color": "#00ffa2"},
      {"label": "Slytherin", "value": "Slytherin", "description": "Cunning and ambitious. Possibly dark wizard.", "color": "#84d2ff"}]

From the above array i want to achieve the following output:
const TAG_COLORS:any = {
  Gryffindor: '#00ffa2',
  Slytherin: '#84d2ff',
}

can some one suggest how to achieve this?

A: Think this is what you are after:
edit. my bad misread the question.

  const options = [{"label": "Gryffindor", "value": "Gryffindor", "description": "Daring, strong nerve and chivalry.", "color": "#00ffa2"}, {"label": "Slytherin", "value": "Slytherin", "description": "Cunning and ambitious. Possibly dark wizard.", "color": "#84d2ff"}];

var TAG_COLOURS = {};
for (var i = 0; i < options.length; i++) {
  TAG_COLOURS[options[i].label] = options[i].color;
}

console.log(TAG_COLOURS);

A: You may use the map function to create a JavaScript object and then use the JavaScript object method on it.
This is how you may go about it:

var options = [
{
 "label":
     "Gryffindor", "value": "Gryffindor", "description": "Daring, strong nerve and chivalry.", "color": "#00ffa2"},
{
 "label":
     "Slytherin", "value": "Slytherin", "description": "Cunning and ambitious. Possibly dark wizard.", "color": "#84d2ff"}
]

options.map((data)=>{console.log(Object.values(data))})

Hope this answers your question


text:
Q: Sorting List in C# How to sort a List based on the item's integer value
The list is like
"1"
"5"
"3"
"6"
"11"
"9"
"NUM1"
"NUM0"

The result should be like
"1"
"3"
"5"
"6"
"9"
"11"
"NUM0"
"NUM1"

is there any idea to do this using LINQ or Lambda expression?
Thanks in advance

A: Jeff Atwood has a blog post about natural sorting where he links to some available implementations of the desired algorithm.
One of Jeffs links points to Dave Koelle how has a C# implementation:
/*
 * The Alphanum Algorithm is an improved sorting algorithm for strings
 * containing numbers.  Instead of sorting numbers in ASCII order like
 * a standard sort, this algorithm sorts numbers in numeric order.
 *
 * The Alphanum Algorithm is discussed at http://www.DaveKoelle.com
 *
 * Based on the Java implementation of Dave Koelle's Alphanum algorithm.
 * Contributed by Jonathan Ruckwood <jonathan.ruckwood@gmail.com>
 *
 * Adapted by Dominik Hurnaus <dominik.hurnaus@gmail.com> to
 *   - correctly sort words where one word starts with another word
 *   - have slightly better performance
 *
 * Released under the MIT License - https://opensource.org/licenses/MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
using System;
using System.Collections;
using System.Text;

/*
 * Please compare against the latest Java version at http://www.DaveKoelle.com
 * to see the most recent modifications
 */
namespace AlphanumComparator
{
    public class AlphanumComparator : IComparer
    {
        private enum ChunkType {Alphanumeric, Numeric};
        private bool InChunk(char ch, char otherCh)
        {
            ChunkType type = ChunkType.Alphanumeric;

            if (char.IsDigit(otherCh))
            {
                type = ChunkType.Numeric;
            }

            if ((type == ChunkType.Alphanumeric && char.IsDigit(ch))
                || (type == ChunkType.Numeric && !char.IsDigit(ch)))
            {
                return false;
            }

            return true;
        }

        public int Compare(object x, object y)
        {
            String s1 = x as string;
            String s2 = y as string;
            if (s1 == null || s2 == null)
            {
                return 0;
            }

            int thisMarker = 0, thisNumericChunk = 0;
            int thatMarker = 0, thatNumericChunk = 0;

            while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
            {
                if (thisMarker >= s1.Length)
                {
                    return -1;
                }
                else if (thatMarker >= s2.Length)
                {
                    return 1;
                }
                char thisCh = s1[thisMarker];
                char thatCh = s2[thatMarker];

                StringBuilder thisChunk = new StringBuilder();
                StringBuilder thatChunk = new StringBuilder();

                while ((thisMarker < s1.Length) && (thisChunk.Length==0 ||InChunk(thisCh, thisChunk[0])))
                {
                    thisChunk.Append(thisCh);
                    thisMarker++;

                    if (thisMarker < s1.Length)
                    {
                        thisCh = s1[thisMarker];
                    }
                }

                while ((thatMarker < s2.Length) && (thatChunk.Length==0 ||InChunk(thatCh, thatChunk[0])))
                {
                    thatChunk.Append(thatCh);
                    thatMarker++;

                    if (thatMarker < s2.Length)
                    {
                        thatCh = s2[thatMarker];
                    }
                }

                int result = 0;
                // If both chunks contain numeric characters, sort them numerically
                if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
                {
                    thisNumericChunk = Convert.ToInt32(thisChunk.ToString());
                    thatNumericChunk = Convert.ToInt32(thatChunk.ToString());

                    if (thisNumericChunk < thatNumericChunk)
                    {
                        result = -1;
                    }

                    if (thisNumericChunk > thatNumericChunk)
                    {
                        result = 1;
                    }
                }
                else
                {
                    result = thisChunk.ToString().CompareTo(thatChunk.ToString());
                }

                if (result != 0)
                {
                    return result;
                }
            }

            return 0;
        }
    }
}

A: Try writing a small helper class to parse and represent your tokens. For example, without too many checks:
public class NameAndNumber
{
    public NameAndNumber(string s)
    {
        OriginalString = s;
        Match match = Regex.Match(s,@"^(.*?)(\d*)$");
        Name = match.Groups[1].Value;
        int number;
        int.TryParse(match.Groups[2].Value, out number);
        Number = number; //will get default value when blank
    }

    public string OriginalString { get; private set; }
    public string Name { get; private set; }
    public int Number { get; private set; }
}

Now it becomes easy to write a comparer, or sort it manually:
var list = new List<string> { "ABC", "1", "5", "NUM44", "3",
                              "6", "11", "9", "NUM1", "NUM0" };

var sorted = list.Select(str => new NameAndNumber(str))
    .OrderBy(n => n.Name)
    .ThenBy(n => n.Number);

Gives the result:

1, 3, 5, 6, 9, 11, ABC, NUM0, NUM1, NUM44

A: This is called a "natural sort order", and is usually employed to sort items like those you have, like filenames and such.
Here's a naive (in the sense that there are probably plenty of unicode-problems with it) implementation that seems to do the trick:
You can copy the code below into LINQPad to execute it and test it.
Basically the comparison algorithm will identify numbers inside the strings, and handle those by padding the shortest one with leading zeroes, so for instance the two strings "Test123Abc" and "Test7X" should be compared as though they were "Test123Abc" and "Test007X", which should produce what you want.
However, when I said "naive", I mean that I probably have tons of real unicode problems in here, like handling diacritics and multi-codepoint characters. If anyone can give a better implementation I would love to see it.
Notes:

*

*The implementation does not actually parse the numbers, so arbitrarily long numbers should work just fine

*Since it doesn't actually parse the numbers as "numbers", floating point numbers will not be handled properly, "123.45" vs. "123.789" will be compared as "123.045" vs. "123.789", which is wrong.

Code:
void Main()
{
    List<string> input = new List<string>
    {
        "1", "5", "3", "6", "11", "9", "A1", "A0"
    };
    var output = input.NaturalSort();
    output.Dump();
}

public static class Extensions
{
    public static IEnumerable<string> NaturalSort(
        this IEnumerable<string> collection)
    {
        return NaturalSort(collection, CultureInfo.CurrentCulture);
    }

    public static IEnumerable<string> NaturalSort(
        this IEnumerable<string> collection, CultureInfo cultureInfo)
    {
        return collection.OrderBy(s => s, new NaturalComparer(cultureInfo));
    }

    private class NaturalComparer : IComparer<string>
    {
        private readonly CultureInfo _CultureInfo;

        public NaturalComparer(CultureInfo cultureInfo)
        {
            _CultureInfo = cultureInfo;
        }

        public int Compare(string x, string y)
        {
            // simple cases
            if (x == y) // also handles null
                return 0;
            if (x == null)
                return -1;
            if (y == null)
                return +1;

            int ix = 0;
            int iy = 0;
            while (ix < x.Length && iy < y.Length)
            {
                if (Char.IsDigit(x[ix]) && Char.IsDigit(y[iy]))
                {
                    // We found numbers, so grab both numbers
                    int ix1 = ix++;
                    int iy1 = iy++;
                    while (ix < x.Length && Char.IsDigit(x[ix]))
                        ix++;
                    while (iy < y.Length && Char.IsDigit(y[iy]))
                        iy++;
                    string numberFromX = x.Substring(ix1, ix - ix1);
                    string numberFromY = y.Substring(iy1, iy - iy1);

                    // Pad them with 0's to have the same length
                    int maxLength = Math.Max(
                        numberFromX.Length,
                        numberFromY.Length);
                    numberFromX = numberFromX.PadLeft(maxLength, '0');
                    numberFromY = numberFromY.PadLeft(maxLength, '0');

                    int comparison = _CultureInfo
                        .CompareInfo.Compare(numberFromX, numberFromY);
                    if (comparison != 0)
                        return comparison;
                }
                else
                {
                    int comparison = _CultureInfo
                        .CompareInfo.Compare(x, ix, 1, y, iy, 1);
                    if (comparison != 0)
                        return comparison;
                    ix++;
                    iy++;
                }
            }

            // we should not be here with no parts left, they're equal
            Debug.Assert(ix < x.Length || iy < y.Length);

            // we still got parts of x left, y comes first
            if (ix < x.Length)
                return +1;

            // we still got parts of y left, x comes first
            return -1;
        }
    }
}

A: How about:
    list.Sort((x, y) =>
    {
        int ix, iy;
        return int.TryParse(x, out ix) && int.TryParse(y, out iy)
              ? ix.CompareTo(iy) : string.Compare(x, y);
    });

A: This is the Fastest Algorithm - took me 2 mili to sort 50 items
~
static void Sort()
{
    string[] partNumbers = new string[] {"A1", "A2", "A10", "A111"};
    string[] result = partNumbers.OrderBy(x => PadNumbers(x)).ToArray();
}

public static string PadNumbers(string input)
{
        const int MAX_NUMBER_LEN = 10;

        string newInput = "";
        string currentNumber = "";
        foreach (char a in input)
        {
            if (!char.IsNumber(a))
            {
                if (currentNumber == "")
                {
                    newInput += a;
                    continue;
                }
                newInput += "0000000000000".Substring(0, MAX_NUMBER_LEN - currentNumber.Length) + currentNumber;
                currentNumber = "";
            }
            currentNumber += a;
        }
        if (currentNumber != "")
        {
            newInput += "0000000000000".Substring(0, MAX_NUMBER_LEN - currentNumber.Length) + currentNumber;
        }

        return newInput;
    }

~

A: I don't think you need anything besides listName.Sort() because sort() method uses default comparer to quick sort nodes. Default comparer does exactly what you are interested in.

A: Here is a C# 7 solution (assuming the list has the name a):
    var numericList = a.Where(i => int.TryParse(i, out _)).OrderBy(j => int.Parse(j)).ToList();
    var nonNumericList = a.Where(i => !int.TryParse(i, out _)).OrderBy(j => j).ToList();
    a.Clear();
    a.AddRange(numericList);
    a.AddRange(nonNumericList);


text:
Q: Near or Nearly, when used with 10% of If we consider the two sentences:

*

*On Mondays, near 10% of the workforce report sick;

*On Mondays, nearly 10% of the workforce report sick;

I am inclined to think that the latter is correct. But '10% of the workforce' is a noun-phrase, so the adverb 'nearly' should not logically be there.
I saw a few sentences similar to the first, but I am not very convinced they are correct.
Couldn't find this in the Wren & Martin.
Please correct me if I am wrong.

A: I think nearly would be a better choice here - as you are describing how close percentage of sick workforce is to 10% and not describing the 10% as noun itself -
Source :

Near or Nearly? Near can function as a verb, adverb, adjective, or
preposition. Nearly is used as an adverb to mean "in a close manner"
or "almost but not quite." Here are some examples that demonstrate the
differences between various uses of near and nearly.
"I'll be seeing you in the near future." Here, near describes the noun
"future." "The cat crept near." Near is an adverb that describes where
the cat crept. "Don't worry; we're nearly there." Here, nearly
describes how close we are. Near can also be used as a verb and a
preposition.
"My graduation neared." Here, neared is the verb of the sentence. "I
want the couch near the window." Near is a preposition at the head of
the phrase "near the window."

Owl English


text:
Q: SAXNotRecognizedException when adding project to weblogic through eclipse We have a maven project which successfully builds when we do it from CLI.
Unfortunately when we try to add the project on weblogic through eclipse the following exception is thrown:

18-05-23 10:27:35 ERROR digester.Digester - Digester.getParser:
  org.xml.sax.SAXNotRecognizedException:
  http://apache.org/xml/features/validation/dynamic     at
  oracle.xml.jaxp.JXSAXParserFactory.setFeature(JXSAXParserFactory.java:128)
    at
  org.apache.commons.digester.parser.XercesParser.configureXerces(XercesParser.java:185)
    at
  org.apache.commons.digester.parser.XercesParser.newSAXParser(XercesParser.java:138)
    at
  org.apache.commons.digester.ParserFeatureSetterFactory.newSAXParser(ParserFeatureSetterFactory.java:71)

We have the following as a dependency:
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.9.1</version>
        </dependency>

Any suggestion on how to overcome this problem?

A: If it successfully builds from Maven, but does not work in Eclipse, it must be a difference in the JDK being used or the classpath.
My guess is that you have more than one XML library on your classpath and, due to the ordering of the classpath, a different one is taking precedence in each case.
To list the classpath in Maven:
mvn dependency:build-classpath -Dmdep.outputFile=cp.txt

Manually compare the ordering with the Eclipse one (in the .classpath file), paying particular attention to any JARs that may contain XML libraries. If any JARs are missing or in a different order, adjust them to match the Maven classpath.


text:
Q: Which amongst the following is a better way to write Unit Test and go ahead with TDD in ASP.NET MVC After reading about MVC and Test Driven Development for quite a bit, I am just getting started on converting my webforms app to MVC. I am using this book as one of the references to learn TDD in ASP.NET MVC.
A Unit Test from that book is as below:
[TestMethod()]
public void Register_Can_Get_To_View()
{
    var target = new AccountController();
    var results = target.Register();
    Assert.IsNotNull(results);
    Assert.IsInstanceOfType(results, typeof(ViewResult));
    Assert.AreEqual("Register", target.ViewData["Title"]);
}

I am also having a look at the nerddinner source code from codeplex and there a similar Unit Test is written as follows
[TestMethod]
public void Index()
{
    // Arrange
    HomeController controller = new HomeController();

    // Act
    ViewResult result = controller.Index() as ViewResult;

    // Assert
    Assert.IsNotNull(result);
}

In the first case, the author is comparing the type of results with ViewResult. However in the second case, the result is being casted as a ViewResult and that is not being tested.
Which is better and do I need to really test in detail as shown in the first case?

A: Ideally you test the result for all the things it could get wrong, where being null might only be the first.
You should assert all of the values of the result, and in fact would test them from different angles (i.e. with different inputs) so that you're testing that those results change correctly relevant to the input. (i.e. to prove you've not hard-coded the values required by one single test just to get it to pass).
The idea being:

*

*Write a test that doesn't compile.

*Write just enough to get it to compile, but still fail (i.e. NotImplementedException).

*Write just enough to get the test to pass (you can hard-code the unit under test to get the test to pass).

*Write another test that fails (which forces you to put a better implementation in than the hard-coding to account for the different input).

*Make the changes so the test passes again.

*Repeat until the unit is fully tested (i.e. all possible/suitable inputs are accounted for, and unsuitable ones are checked and refused appropriately).

Sometimes you can short-circuit step 3 and write what Kent Beck refers to as the Obvious Implementation for things that you know from experience are going to be very simple. You wouldn't do this for complex units, but for a method that reverses a string or adds two numbers together you can go ahead and just write the implementation properly.
In this case, I'd consider asserting the following:

*

*That the controller action result was not null.

*That the Model property was of the correct type (assuming strongly-typed views).

*That each property on the Model or each value in the ViewData was the correct value for the given input.

A: The first test looks as if the controller action is using ViewData instead of view models. For me this is bad. It uses magic strings and it is extremely brittle. So no longer need to comment on it.
The second test doesn't do anything useful other than verifying that the controller action returned a view.
But a more real world controller action will pass a view model to this view. So you need to test this. Personally I prefer MVCContrib TestHelper as it makes my unit tests very fluent and readable:
[TestMethod]
public void Index()
{
    // Arrange
    var controller = new HomeController();

    // Act
    var actual = controller.Index();

    // Assert
    actual
        .AssertViewRendered()
        .WithViewData<MyViewModel>()
        .ShouldNotBeNull("the view model was null");
}

Here we assert that the controller action rendered a view and that the view model which was passed to it wasn't null and it was of the expected type because the corresponding view will be strongly typed to this view model.


text:
Q: Get sum of Recycler view Edittext and update the parent layout (Custom Adapter) How can i get access to parent layout from Recycler view adapter. my objective is get the sum of qty in Recycler view and  update the subtotal in parent.
here is my code.
here is the Main Activity
public class project_bid extends AppCompatActivity {

DatabaseReference mRef;
RecyclerView ItemRecyclerView;
EditText subtotal, tax, grandTotal;
String key;
LinearLayout bid_total_layout;
projectItemAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    key = getIntent().getStringExtra("key");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_project_bid);

    mRef = FirebaseDatabase.getInstance().getReference().child("projects/1/project_line");

    subtotal = (EditText) findViewById(R.id.project_bid_subtotal);
    tax = (EditText) findViewById(R.id.project_bid_tax);
    grandTotal = (EditText) findViewById(R.id.project_bid_grandTotal);
    bid_total_layout = (LinearLayout) findViewById(R.id.project_bid_total_layout);

    ItemRecyclerView = (RecyclerView) findViewById(R.id.projectRecycler);
    ItemRecyclerView.setHasFixedSize(false);
    ItemRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<ProjectDetailsLineBuilder> list = new ArrayList<ProjectDetailsLineBuilder>();
            for (DataSnapshot snapshot: dataSnapshot.getChildren()){
                ProjectDetailsLineBuilder item = snapshot.getValue(ProjectDetailsLineBuilder.class);
                list.add(item);
            }
            adapter = new projectItemAdapter(list, project_bid.this);
            ItemRecyclerView.setAdapter(adapter);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

@Override
protected void onStart() {
    super.onStart();

}

In addition i used the above method to get and pass the value to adapter. the for loop will create performance issue, is there any better solution?
Here is my adapter and view holder class.
public class projectItemAdapter  extends RecyclerView.Adapter<projectItemAdapter.projectBidItems>{
ArrayList<ProjectDetailsLineBuilder> data;
Context context;
LinearLayout totalLayout;

public projectItemAdapter(ArrayList<ProjectDetailsLineBuilder> data, Context context) {
    this.data = data;
    this.context = context;
}

@Override
public projectBidItems onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(context).inflate(R.layout.project_bid_line, parent, false);
    View main = LayoutInflater.from(context).inflate(R.layout.activity_project_bid, parent, false);
    return new projectBidItems(v);

}

@Override
public void onBindViewHolder(projectBidItems holder, int position) {
    ProjectDetailsLineBuilder item = data.get(position);
    holder.qty.setText(String.valueOf(item.getQuantity()));
    holder.quantity.setText("Quantity: 20 " + item.getUnit());
    holder.title.setText(item.getTitle());
    holder.desc.setText(item.getDescription());
    holder.unitprice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if(b){

            }
        }
    });
}

@Override
public int getItemCount() {
    return data.size();
}

public static class projectBidItems extends RecyclerView.ViewHolder {
    View mView;
    EditText qty;
    EditText total, unitprice;
    TextView quantity, desc, title;

    public projectBidItems(View item) {
        super(item);
        mView = item;

        unitprice = (EditText) mView.findViewById(R.id.project_line_unit_price);
        total = (EditText) mView.findViewById(R.id.project_line_total);
        quantity = (TextView) mView.findViewById(R.id.project_line_qty);
        qty = (EditText) mView.findViewById(R.id.project_line_cal_qty);
        title = (TextView) mView.findViewById(R.id.project_line_title);
        desc = (TextView) mView.findViewById(R.id.project_lined_description);

    }

}

}


text:
Q: Customize QMenu added to a QMenuBar So I try, with Qt, to bold the fourth Menu Title "Test" in a QMenuBar (see picture below).

    QMenuBar* pQMenubar = new QMenuBar();
    pQMenubar->addMenu(new QMenu("Fichier")); //Some QMenu, not important
    pQMenubar->addMenu(new QMenu("Windows")); //Some QMenu, not important
    pQMenubar->addMenu(new QMenu("Tools"));   //Some QMenu, not important

    QMenu* pQMenuTest = new QMenu("Test");    // The Menu I wanna bold
    pQMenubar->addMenu(pQMenuTest);

    //There is some action added to each QMenu, but I do not want them bold

To achieve that, I've tried by setting StyleSheet or font to the QMenuBar or QMenu("test")
Set the font (setBold(true)) or StyleSheet(font-weighted: bold) to the QMenu do not work, it only set actions contains in the QMenu in bold.
But when I change styleSheet or Font of the QMenuBar, all QMenu and QAction are bold, so I've tried this way.
I've tried to "filter" the object affected by the style sheet :
    //Try 1
    pQMenuBar.setStyleSheet(QMenu {font-weight: bold}); //Nothing is bold

    //Try 2
    pQMenuTest.setObjectName("Test");
    pQMenuBar.setStyleSheet(QMenu#Test {font-weight: bold}); //Nothing is bold

    //Try 3
    pQMenuTest.setObjectName("Test");
    pQMenuBar.setStyleSheet(#Test {font-weight: bold}); //Nothing is bold

    //Try 4, just to check if it's works
    pQMenuTest.setObjectName("Test");
    pQMenuBar.setStyleSheet(QWidget {font-weight: bold}); //Evrything is bold

I've started to suspect the QMenuBar.addMenu(QMenu) do not really use the QMenu for the "display" and so filter by QMenu or the objectname do not work. (I've tried to filter with QAction, but nothing is bold too).


text:
Q: Installation of TFS 2018 I am going to install TFS 2018 in a machine.
Do you think that I may face any kind of issues if Install it on Drive D instead of the default drive C?
It should be the same but I am just wondering if afterwards I may face any issue or something.

A: The fact that you can specify a different installation drive during the install should tell you that it will work fine.


text:
Q: Difference between decimal and decimal.value? I often have to call the Value property when accessing my Linq to SQL objects to check for null values or I get an exception.  Can someone please expain these data types (i.e. decimal?, bool?, etc...) that appear to wrap the primitive types?

A: decimal? is shorthand (and equivalent to) nullable<decimal>, which means it can have a value of null set to it. The same thing applies to bool?, int?, etc.
These values are chosen by Linq 2 SQL when your database fields allow null values. Otherwise, you would not have a way to indicate that those values should be null.

A: They are Generics of type Nullable<T>, and they do wrap primitive types.
Why they invented the short form int? is Nullable seems to be down to the standard confusion between succinct and terse C based language developers struggle with.
decimal? total = null;

total.HasValue will return false, it won't blow up with a null reference
but total.Value.ToString(); will throw an exception, because the Value property of total is null.
The Value and HasValue properties are read only.
total = 10;

means total.Value will return 10.0 and total.HasValue will return true.
It's a really nice generic, especially for database types, still don't get the short form though...


text:
Q: Как задать высоту в TextBox? Как задать нужную высоту в TextBox?

A: Вам нужно свойство AutoSize у TextBox установить в false. Можно наследоваться от класса TextBox.
 public class TextBoxWithHeight : TextBox
    {
        public bool Auto_Size
        {
            get { return this.AutoSize; }
            set { this.AutoSize = value; }
        }
    }

Или же в дизайнере добавить код
textBox.AutoSize = false;
textBox.Size = new System.Drawing.Size(100, 50);

Так же можете попробовать изменить размер после того, как выставив свойство Multiline = true

A: Из резметки
<TextBox Height="45" />

или из кода
var textBox = new TextBox { Height = 45 };

A: Насколько я помню у элемента TextBox высота зависит от того, сколько в него строк умещается, иными словами, есть у него свойство Multiline, его Вам нужно выставить в true, чтобы Ваш TextBox был высотой в несколько строк. Из кода это делается не сложно.
Первый вариант:
textBox1.Multiline = true;
textBox1.Height = 32;

И после этого Вы сможете менять уже высоту.

Однако, если Вы хотите оставить одну строку, при этом чтобы текст был больше - Вам нужно менять размер шрифта Font в текстовом поле у Вашего TextBox.
Второй вариант:
textBox1.Font = new Font(textBox1.Font.FontFamily, 32);

То есть все зависит от того, что Вы хотите увидеть, если несколько строк того же размера, что и раньше - Вам по первому пути, если бОльший текст - меняйте размер шрифта.
Можно менять как программным кодом, так и через свойства компонента в визуальном интерфейсе среды разработки.

A: Высота у однострочного TextBox зависит от размеров шрифта и вычисляется автоматически. В исходниках есть комментарий на тему того, что можно отключить AutoSize и менять высоту, однако согласно исходникам это скрытое публичное свойство, унаследованное от TextBoxBase, которое не отображается ни в автокомплите, ни в редакторе свойств. Если его принудительно выставить в *.Designer.cs (), то это cработает только на время редактирования формы, после запуска дизайнер удалит вашу запись из своего файла все вернется в исходное состояние, хотя в режиме редактирования формы TextBox все еще будет делать вид "послушного мальчика" менять свои размеры, но только во время редактирования.
Обходные пути:
В визуальном редакторе:

*

*Можете попытаться подобрать шрифт нужного размера, но выставить размер с точностью до пикселя не выйдет.

*Если хочется быстро и наглядно - можно положить TextBox на Panel. Выставить Border = None у TextBox и Border = Fixed3d у Panel. А также заменить цвет фона Panel с дефолтного Control на Window. Получится такой составной контрол, который выглядит как TextBox. Этот вариант также поможет, если нужно выставить позицию ввода текста в положение, отличное от левого верхнего угла.
В коде:

*Можете настроить параметры TextBox, включая скрытое свойство AutoSize полностью в коде, разумеется такой вариант исключает возможность предварительного просмотра в редакторе форм.

*Можете создать класс унаследованный от TextBox и либо переопределить свойство AutoSize и сделать его видимым (оно виртуальное и скрыто атрибутами см. тут), либо определить конструктор по умолчанию (без параметров) и просто выставить его в конструкторе в false и менять размер как нравится даже в редакторе форм.
PS: В формах еще много  таких не очевидных сюрпризов, некоторые решаются, некоторые нет.


text:
Q: Apt-get does not find package `git` on Ubuntu 12.04 I am trying to install git on ubuntu 12.04. But when enter the command
sudo apt-get install git

I get the following message. I have run sudo apt-get update already.
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package git is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  git-el

E: Package 'git' has no installation candidate

A: You have to install git-core instead
sudo apt-get -y install git-core


text:
Q: Generic reference for object I've a code where a Object implementing a certain interface (ChallengeTransactionInfo) should be deserialized from a JSON String in order to be processed. The processos also implements a certain interface(ChallengeTransactionAction), which is bound to the first interface:
public interface ChallengeTransactionInfo {
}

public interface ChallengeTransactionAction<T extends ChallengeTransactionInfo> {
    public Class<T> getTransactionInfoClass();
    public void setTrxInfo(T trxInfo);
}

Then I have two classes that implement those interfaces
public class TestAVO implements ChallengeTransactionInfo {
}

public class TestAAction implements ChallengeTransactionAction<TestAVO>{

    public Class<TestAVO> getTransactionInfoClass() {
        return TestAVO.class;
    }

    public void setTrxInfo(TestAVO trxInfo) {
        // TODO Auto-generated method stub
    }
}

And now I have a code that receives the action, the JSON string, and should deserialize the Info object and pass it to the Action object
public class TestMain {
    public static void main(String[] args) {
        ChallengeTransactionAction<? extends ChallengeTransactionInfo> action = (ChallengeTransactionAction<? extends ChallengeTransactionInfo>) null;

        ChallengeTransactionInfo rsaTrxInfo = null;

        Class<? extends ChallengeTransactionInfo> rsaTrxClazz = null;

        rsaTrxClazz = action.getTransactionInfoClass();

        Gson gson = new GsonBuilder().create();

        String objectJSON = "{one:1}";

        // And we retrieve it
        rsaTrxInfo = gson.fromJson(objectJSON, rsaTrxClazz);

        //setTransactionInfoClass
        action.setTrxInfo(rsaTrxInfo);
    }
}

This code does not compile, as the call to setTrxInfo gives an error:
The method setTrxInfo(capture#5-of ? extends ChallengeTransactionInfo) in the type ChallengeTransactionAction is not applicable for the arguments (ChallengeTransactionInfo)
So the problem is that rsaTrxInfo should be defined somehow as
? extends ChallengeTransactionInfo rsaTrxInfo
But it does not work. How can I create a generic reference in order for this to work?


text:
Q: Adding UUID for each row being imported from a CSV file We want to import 100 thousand rows from a .csv file into a Cassandra table.
There is no unique value for each row, for this reason we want to add UUID to each imported row, how do we do this automatically while importing data from CSV file.
Sample row (first row is column names) from .CSV file
DateTime,Latitude,Longitude,Depth,Magnitude,MagType,NbStations,Gap,Distance,RMS,Source,EventID,Version
2014-09-11T12:36:11.000+00:00,67.689,-162.763,14.6,3.9,ml,,,,0.79,ak,ak11387003,1410441826879

Want to add UUID to each row like below
UID, DateTime,Latitude,Longitude,Depth,Magnitude,MagType,NbStations,Gap,Distance,RMS,Source,EventID,Version
c37d661d-7e61-49ea-96a5-68c34e83db3a,2014-09-11T12:36:11.000+00:00,67.689,-162.763,14.6,3.9,ml,,,,0.79,ak,ak11387003,1410441826879

A: There's no way to do that directly from CQL's COPY command, but instead you could process the CSV file outside of Cassandra first.
For example, here's a Python script that will read in from file in.csv, append a UUID column to each row, and write out to out.csv:
#!/usr/bin/python
# read in.csv adding one column for UUID

import csv
import uuid

fin = open('in.csv', 'rb')
fout = open('out.csv', 'w')

reader = csv.reader(fin, delimiter=',', quotechar='"')
writer = csv.writer(fout, delimiter=',', quotechar='"')

firstrow = True
for row in reader:
    if firstrow:
        row.append('UUID')
        firstrow = False
    else:
        row.append(uuid.uuid4())
    writer.writerow(row)

The resulting file could be imported using CQL COPY (after you've created your schema accordingly). If you use this example, make sure to read up on Python's uuid functions to choose the one you need (probably uuid1 or uuid4).


text:
Q: PHP Include Is Giving Me Errors When I Use Direct Link I am trying to include a php file using php include, and the catch is that I need to use variables in the URL...  I know that I cannot do this with a relative link, so I am using the direct link but getting this error:
I was wondering if anybody could tell me what I am doing wrong...
Here is the include code:
<?php

include 'http://www.procapturemarketing.net/Scripts/PCMSSystemsOwned.php?ref=NMVT';

?>

And Here is PCMSSYSTEMSOWNED.php:
<?php

$systems = explode(', ',$row_rsUsers['Systems']);

if (in_array("Empower", $systems) and $_GET['ref'] != "Empower") { ?>

Empower System

<?php } if (in_array("MCA", $systems) and $_GET['ref'] != "MCA") { ?>

MCA System

<?php } if (in_array("Neucopia", $systems) and $_GET['ref'] != "Neucopia") { ?>

Neucopia System

<?php } if (in_array("NMVT", $systems) and $_GET['ref'] != "NMVT") { ?>

NMVT System

<?php } ?>

Also if you need it here is the recordset rsUsers:
$colname_rsUsers = "-1";
if (isset($_GET['MM_Username'])) {
  $colname_rsUsers = $_GET['MM_Username'];
}
mysql_select_db($database_myBackOfficeConn, $myBackOfficeConn);
$query_rsUsers = sprintf("SELECT * FROM Users WHERE Username = %s", GetSQLValueString($colname_rsUsers, "text"));
$rsUsers = mysql_query($query_rsUsers, $myBackOfficeConn) or die(mysql_error());
$row_rsUsers = mysql_fetch_assoc($rsUsers);


text:
Q: How to convert a formatted string into plain text User copy paste and send data in following format: " "
I need to convert it into plain txt (we can say ascii chars) like 'jovy debbie'
It comes in different font and format:
ex:
' '
'  '
Any Help will be Appreciated, I already refer other stack overflow question but no luck :(

A: Those letters are from the Mathematical Alphanumeric Symbols block.
Since they have a fixed offset to their ASCII counterparts, you could use tr to map them, e.g.:
" ".tr("-", "a-z")
#=> "jovy debbie"

The same approach can be used for the other styles, e.g.
" ".tr("--", "a-zA-Z")
#=> "Jenica Dugos"

This gives you full control over the character mapping.
Alternatively, you could try Unicode normalization. The NFKC / NFKD forms should remove most formatting and seem to work for your examples:
" ".unicode_normalize(:nfkc)
#=> "jovy debbie"

" ".unicode_normalize(:nfkc)
#=> "Jenica Dugos"


text:
Q: Why is overflow != visible required for any div to be resizabel with resize css property? I have been reading this post about how to make a div resizable. What I don'
t understand is why does the overflow property have to be different from visible? Both the w3c docs and csstricks blog mention this.  Is there any specific reason behind this? If yes then what?

A: If you look at the overflow options, setting this value to visible will prevent the box to wrap the content, instead the content will go out of the box. Therefore, if the user is dynamically modifying the box, you would get the context overlapping your element's box.
reference: mdn overflow


text:
Q: Pass value of JavaScript variable to Rails view with hidden_field_tag helper I set up a JavaScript program using jQuery to change the user input values at various form field.
$(document).ready(function(){
    $("#billAmt").keyup(function(){
        var a = $("#billAmt").val();
        var b = a*3/100;
        var d = "<%= current_user.balance %>";
        var c = d - b;
        $("#cashBack").val(b);
        $("#total").val(c);
    });
});

This JavaScript code is inside the form_tag and I would like to pass #cashBack to hidden field.
I did like:
<%= hidden_field_tag :cashBack, nil, :id => "cashBack", :value => ''%>

When I submit the form, params[:cashBack] is empty. So, how do I pass the value and change every time I change the value.

A: In order to set hidden textfield, You must use pure javascript instead of JQuery.
$("#cashBack").get(0).value = b;


text:
Q: Hash based routing in react-router-component I want to use hash-based routing in react-router-component, so I added the hash attribute to the <Locations> component like this:

  <Locations hash>
    <Location path="/" handler={HomePage} />
    <Location path="/movies/" handler={MoviesPage} />
    <Location path="/movies/:id" handler={MoviePage} />
  </Locations>

I'm linking to this locations like this:

<Link href="/">Home</Link>

<Link href="/movies/">Movies</Link>

I also tried including the hashtags manually in the Link component (I can't find it documented anyware how to link to a hash-based route).

<Link href="/#/">Home</Link>

<Link href="/#/movies/">Movies</Link>

The problem is that either way, react-router-component is not responding to clicks on the links. It is updating the url in the browser, but it is not switching to render the component defined as handler in the Location.
When I visit the url manually, e.g. http://localhost:8082/#/movies/, the correct component is being rendered, but again, I can still not navigate.
Also, if I remove the hash attribute from the <Locations>, linking to routes is working as expected again.


text:
Q: How to make EC2 user-data work on freshly built AMI, made with Packer I can build AMI images just fine.  But they've stopped working with EC2 User Data:
There is user data:
$ cat /tmp/user_data.sh
#!/bin/bash

touch /tmp/i_have_user_data /root/i_have_user_data

And I can launch a plain Ubuntu image:
aws ec2 run-instances --instance-type m3.medium --image-id ami-eed10e86 --user-data file:///tmp/user_data.sh

And it works:
ubuntu@ip-10-165-90-180:~$ ls /tmp/i_have_user_data

/tmp/i_have_user_data
But if I build an AMI based on that one, with Packer:
"builders": [
    {
        "type": "amazon-ebs",
        "region": "us-east-1",
        "source_ami": "ami-eed10e86",
        "instance_type": "m3.large",
        "ssh_username": "ubuntu",
        "tags": {
            "OS_Version": "Ubuntu",
            "Release": "LTS"
        }
    }
],

... and run that the very same way as before, there's nothing in /tmp.  However, it's clear that there is user data if you run ec2metadata:
ramdisk-id: unavailable
reserveration-id: unavailable
security-groups: default
user-data: #!/bin/bash

touch /tmp/i_have_user_data /root/i_have_user_data

I'm pretty sure it's a state issue and that removing a statefile is going to make it all magically work.  Or, there's a trick to make the cloud-final upstart script work, which might be what's broken.  Anyway, I haven't found that yet.
Update:
I made it work by turning the user-data script into a boothook:
#cloud-boothook
#!/bin/sh
echo "RUNNING USER DATA SCRIPT"

Still looking for an explanation for why they stopped working.  Cloud Init's docs are getting better, but there's still a way to go.

A: Packer creates your image then takes a snapshot before making the AMI. This is your first boot. At this point you would need to boot the instance, which according to Ubuntu, would clean the /tmp directory.
I would try putting the file elsewhere and see if it persists.
The #cloud-boothook runs every time, given the docs that state you responsible for disabling it.


text:
Q: The Peter-Weyl Theorem and extensions of finite-dimensional representations In L-groups, projective representations, and the Langlands classification, by Adams and Vogan, it is stated that a standard consequence of the Peter-Weyl Theorem is the following.
If $G$ is a compact group and $H$ is a closed subgroup of $G$, then every finite-dimensional representation of $H$ has an extension to a finite-dimensional representation of $G$. (See Scholium 3.20.)
I have not seen this mentioned in any other texts and do not see how it follows from the Peter-Weyl Theorem. Any help would be appreciated.


text:
Q: MNIST Neural Network not learning - Micheal Nielsen Example I have been trying to code up the neural network for recognizing MNIST that was given by Michael Nielsen here http://neuralnetworksanddeeplearning.com/chap1.html
The original was written using Python 2.7 I believe, I'm using v3. The network does go through the test examples and updates the weights and biases, but it doesn't learn, and gets around 10% of the test examples right (so as good as random guessing).
I have also tried simply copying the code from the site and running it in Python 2.7, and it works as it should (getting up to 95% accuracy). The only significant difference in the nets are the data set (I'm using the one downloaded directly from MINST two days ago) and the two locations where i switched np.dot into np.outer, just to make it easier to keep track of the array shapes (I tried sticking to (N,) instead of (N,1)). But that part seems to be fine, since the layer sizes are different and the multiplications are going through. I am also using the same learning rate and layer sizes as given in the example.
I cannot see what could be throwing the net off. If anyone has tried doing the same, or has some insight into this I would greatly appreciate it.
Thanks !
The code :
import matplotlib.pyplot as plt
import numpy as np
import idx2numpy

import random

### LOAD DATASET ###

train = idx2numpy.convert_from_file("mnist/train-images.idx3-ubyte")

train_labels = idx2numpy.convert_from_file("mnist/train-labels.idx1-ubyte")

test = idx2numpy.convert_from_file("mnist/t10k-images.idx3-ubyte")

test_labels = idx2numpy.convert_from_file("mnist/t10k-labels.idx1-ubyte")

def vectorize(x):
    e = np.zeros(10)
    e[x] = 1.0
    return e

training_images = [np.reshape(i, (784))/255 for i in train]
training_labels = [vectorize(i) for i in train_labels]
training_set = list(zip(training_images,training_labels))

test_images = [np.reshape(i, (784))/255 for i in test]
test_set = list(zip(training_images,test_labels))

### NETWORK CLASS ###

class myNet():

    def __init__ (self , sizes ):

        self.sizes = sizes

        self.N = len(sizes)

        self.w = [np.random.randn(y, x) for x, y in zip( sizes [: -1] , sizes [1:]) ]

        self.b = [np.random.randn(i) for i in sizes[1:]]

    def sigmoid (self,z):

        return 1.0/(1.0+ np.exp(-z))

    def sigmoid_prime (self,z):

        return self.sigmoid (z)*(1 - self.sigmoid (z))

    def cost_derivative (self,output_activations , y):

        return ( output_activations - y)

    def feedforward (self , a):

        for bb, ww in zip(self.b , self.w ):
            a = self.sigmoid (np.dot(ww, a)+bb)

        return a

    def backprop (self , x, y):

        nabla_b = [np. zeros (bb. shape ) for bb in self.b ]
        nabla_w = [np. zeros (ww. shape ) for ww in self.w ]

        activation = x

        activations = [x] # list to store all the activations , layer by layer
        zs = [] # list to store all the z vectors , layer by layer

        for bb, ww in zip(self.b , self. w ):
            z = np.dot(ww, activation )+bb

            zs. append (z)
            activation = self.sigmoid (z)
            activations . append ( activation )
        # backward pass

        delta = self. cost_derivative ( activations [-1], y) * self.sigmoid_prime (zs [ -1])

        nabla_b [-1] = delta
        nabla_w [-1] = np.outer(delta , activations [ -2])
        # Note that the variable l in the loop below is used a little

        for l in range (2, self.N ):

            z = zs[-l]
            sp = self.sigmoid_prime (z)
            delta = np.dot(self.w [-l+1]. transpose () , delta ) * sp
            nabla_b [-l] = delta
            nabla_w [-l] = np.outer(delta , activations [-l -1])

        return (nabla_b , nabla_w )

    def update(self,mini_batch,eta):

        nabla_b = [np.zeros (bb.shape ) for bb in self.b ]
        nabla_w = [np.zeros (ww.shape ) for ww in self.w ]

        for x, y in mini_batch :

            delta_nabla_b , delta_nabla_w = self. backprop (x, y)

            nabla_b = [nb+dnb for nb , dnb in zip(nabla_b , delta_nabla_b )]
            nabla_w = [nw+dnw for nw , dnw in zip(nabla_w , delta_nabla_w )]

        self.w = [ww -( eta/len( mini_batch ))*nw
                         for ww, nw in zip(self.w , nabla_w )]
        self.b = [bb -( eta/len( mini_batch ))*nb
                        for bb, nb in zip(self.b, nabla_b )]

        return

    def gradient_descent(self,training_data,epochs,mini_batch_size,eta,test_data):

        i = 0

        n = len( training_data )

        for j in range (epochs):

            random.shuffle (training_data)

            mini_batches = [
                training_data [k:k+ mini_batch_size ]
                for k in range (0, n, mini_batch_size )]

            for mini_batch in mini_batches :
                self.update( mini_batch , eta)

            print("Epoch {0}: {1}". format (
                j, self.evaluate(test_data)))

        return

    def evaluate (self, test_data):

        test_results = [( np.argmax (self.feedforward (x)), y)
                        for (x, y) in test_data ]

        return sum(int(x == y) for (x, y) in test_results )

sizes =[28*28, 30, 10]

net = myNet(sizes)

net.gradient_descent(training_set,30,10,3.0,test_set)

A: I found the mistake... By mistake I zipped up the training images with the test labels to form the test set, which is clearly not what it should be. Now that I formed the test set properly, everything works and gets up to around 95% accuracy. Here is the full corrected code for completeness (usable in Python3)
import matplotlib.pyplot as plt
import numpy as np
import idx2numpy

import random

def vectorize(x):
    e = np.zeros(10)
    e[x] = 1.0
    return e

### LOAD DATASET ###

train_images = idx2numpy.convert_from_file("mnist/train-images.idx3-ubyte")/255
train_labels = idx2numpy.convert_from_file("mnist/train-labels.idx1-ubyte")

train_images = [np.reshape(x,(784)).astype('float32') for x in train_images]
train_labels = [vectorize(i) for i in train_labels]

test_images = idx2numpy.convert_from_file("mnist/t10k-images.idx3-ubyte")/255
test_labels = idx2numpy.convert_from_file("mnist/t10k-labels.idx1-ubyte")

test_images = [np.reshape(x,(784)).astype('float32') for x in test_images]

training_set = list(zip(train_images,train_labels))

test_set = list(zip(test_images,test_labels)) ## THIS IS WHERE I MESSED UP

### NETWORK CLASS ###

class myNet():

    def __init__ (self , sizes ):

        self.sizes = sizes

        self.N = len(sizes)

        self.w = [np.random.randn(y, x) for x, y in zip( sizes [: -1] , sizes [1:]) ]

        self.b = [np.random.randn(i) for i in sizes[1:]]

    def sigmoid (self,z):

        return 1.0/(1.0+ np.exp(-z))

    def sigmoid_prime (self,z):

        return self.sigmoid (z)*(1 - self.sigmoid (z))

    def cost_derivative (self,output_activations , y):

        return ( output_activations - y)

    def feedforward (self , a):

        for bb, ww in zip(self.b , self.w ):
            a = self.sigmoid (np.dot(ww, a)+bb)

        return a

    def backprop (self , x, y):

        nabla_b = [np. zeros (bb. shape ) for bb in self.b ]
        nabla_w = [np. zeros (ww. shape ) for ww in self.w ]

        activation = x

        activations = [x] # list to store all the activations , layer by layer
        zs = [] # list to store all the z vectors , layer by layer

        for bb, ww in zip(self.b , self. w ):
            z = np.dot(ww, activation )+bb

            zs. append (z)
            activation = self.sigmoid (z)
            activations . append ( activation )
        # backward pass

        delta = self. cost_derivative ( activations [-1], y) * self.sigmoid_prime (zs [ -1])

        nabla_b [-1] = delta
        nabla_w [-1] = np.outer(delta , activations [ -2])
        # Note that the variable l in the loop below is used a little

        for l in range (2, self.N ):

            z = zs[-l]
            sp = self.sigmoid_prime (z)
            delta = np.dot(self.w [-l+1]. transpose () , delta ) * sp
            nabla_b [-l] = delta
            nabla_w [-l] = np.outer(delta , activations [-l -1])

        return (nabla_b , nabla_w )

    def update(self,mini_batch,eta):

        nabla_b = [np.zeros (bb.shape ) for bb in self.b ]
        nabla_w = [np.zeros (ww.shape ) for ww in self.w ]

        for x, y in mini_batch :

            delta_nabla_b , delta_nabla_w = self. backprop (x, y)

            nabla_b = [nb+dnb for nb , dnb in zip(nabla_b , delta_nabla_b )]
            nabla_w = [nw+dnw for nw , dnw in zip(nabla_w , delta_nabla_w )]

        self.w = [ww -( eta/len( mini_batch ))*nw
                         for ww, nw in zip(self.w , nabla_w )]
        self.b = [bb -( eta/len( mini_batch ))*nb
                        for bb, nb in zip(self.b, nabla_b )]

        return

    def gradient_descent(self,training_data,epochs,mini_batch_size,eta,test_data):

        i = 0

        n = len( training_data )

        for j in range (epochs):

            random.shuffle (training_data)

            mini_batches = [
                training_data [k:k+ mini_batch_size ]
                for k in range (0, n, mini_batch_size )]

            for mini_batch in mini_batches :
                self.update( mini_batch , eta)

            print("Epoch {0}: {1}". format (
                j, self.evaluate(test_data)))

        return

    def evaluate (self, test_data):

        test_results = [( np.argmax (self.feedforward (x)), y)
                        for (x, y) in test_data ]

        return sum(int(x == y) for (x, y) in test_results )

sizes =[28*28, 30, 10]

net = myNet(sizes)

net.gradient_descent(training_set,30,10,3.0,test_set)


text:
Q: Laravel (Sail): Vite Dev Server not found (404) I am currently switching from webpack to vite.
Current status is, that build commands (yarn production) works for js and css using vite.
However, using the dev server, I receive an 404 message telling me, that the files weren't found - what did I miss?

Below is my code:
vite.config.js
export default ({ command }) => ({
    base: command === 'serve' ? '' : '/build/',
    publicDir: 'fake_dir_so_nothing_gets_copied',
    build: {
        manifest: true,
        outDir: 'public/build',
        rollupOptions: {
            input: 'resources/js/app.js',
        },
    },
    server: {
        strictPort: true,
        port: 3000
    },

    resolve: {
        alias: {
            '@': '/js',
        }
    }
});

helpers.php
<?php

use Illuminate\Support\Facades\Http;
use Illuminate\Support\HtmlString;

function vite_assets(): HtmlString
{
    $devServerIsRunning = false;

    if (app()->environment('local')) {
        try {
            Http::get("http://localhost:3000");
            $devServerIsRunning = true;
        } catch (Exception) {
        }
    }

    if ($devServerIsRunning) {
        return new HtmlString(<<<HTML
            <script type="module" src="http://localhost:3000/@vite/client"></script>
            <script type="module" src="http://localhost:3000/resources/js/app.js"></script>
        HTML);
    }

    $manifest = json_decode(file_get_contents(
        public_path('build/manifest.json')
    ), true);

    return new HtmlString(<<<HTML
        <script type="module" src="/build/{$manifest['resources/js/app.js']['file']}"></script>
        <link rel="stylesheet" href="/build/{$manifest['resources/js/app.js']['css'][0]}">
    HTML);
}

so I can finally embed {{ vite_assets() }} inside my blade layout

A: I recommend you to use: https://laravel-vite.dev/ when passing from webpack to vite, it worked perfect for me and took me like less than an hour.


text:
Q: Safari ITP 2.3: Capped Lifetime For All Script-Writeable Website Data I am a little confused about Safari's ITP 2.3 policy which caps the lifetime of script-writable storage in the browser to 7 days.
The official article states that:

After seven days of Safari use without the user interacting with a web page on website.example, all of website.example's non-cookie website data is deleted.

This definitely includes localStorage. Does someone know for sure whether

*

*IndexedDB

*CacheStorage

*Service Worker

are cleared as well?

A: Looking at the relevant Webkit commit, it clearly includes IndexedDB - it does not seem to  include CacheStorage or ServiceWorker.

A: This post of March 24th lists what is affected.
On that list, I can see IndexDB and something that they call "Service Worker Registrations".
https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/


text:
Q: Azure search fetch multiple records I want to fetch multiple records from Azure index using one of the fields, but I am unsure that how many number of filters can I use in a single query. Suppose if I want to fetch 1000 records, can I add 1000 filters to the search query?
for example : I have a field called field_document_id and I want to fetch multiple documents given that I have the ids of the document. For this I am querying like : *&$filter=field_document_id eq '1', this will fetch me the document with field_document_id value 1, suppose I want to fetch multiple documents in a single request like this, I there any other way ? If I use multiple filters is there any limit to it?

A: I believe there are limits in the number of filter clauses you can define however I am not able to find the exact number. This is what is mentioned here:

There are limits to the size and complexity of filter expressions that
you can send to Azure Cognitive Search. The limits are based roughly
on the number of clauses in your filter expression. A good guideline
is that if you have hundreds of clauses, you are at risk of exceeding
the limit. We recommend designing your application in such a way that
it doesn't generate filters of unbounded size.

Microsoft recommends that you use search.in function when you have a large number of filter clauses on a single field. According to the documentation, it not only overcomes the filter size limitation but is also better in terms of performance.


text:
Q: Browsing Windows Phone 8 file system in the emulator Is there a way to browse the file system of Windows Phone 8 running in the emulator, preferably while the emulator is running?
It would make debugging much easier if I could access the application local storage and its other private folders while the application is running: check the files that are present, modify them, add new ones etc. On more than one occasion this proved useful to me with Windows Store apps for Windows 8.

A: Also, you can use built-in tool ISETool.exe (only command line):
How to use the Isolated Storage Explorer tool for Windows Phone
Best regards

A: Just use the Windows Phone Power Tools integrated file browser.


text:
Q: list table using hostname and port number I need to list the table from known database 'dbname' from the host name and port number.

mysql_connect(): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

I tried with code
$dbname = 'inh_db';
$port = '3386';
if (!mysql_connect('182.35.5.00', 'name', 'dbname')) {
echo 'Could not connect to mysql';
exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
  echo "Table: {$row[0]}\n";
}
mysql_free_result($result);

A: mysql_connect('182.35.5.0:3386', 'name', 'password', 'dbname')
details:
http://php.net/manual/zh/function.mysql-connect.php


text:
Q: Divisor of rational function I need to find divisor of function:
$f(w_0,w_1,w_2)=(w_{0}^{2},w_1w_2)$
on  $S=\left \{ w_0w_1-w_2w_3=0  \right \}\subseteq P^3$.
And the question is do I need to take into account this surface?
 There is my solution:
Firstly we will find zeros and poles of f:

*

*$f=0: D=\left \{ w_0=0 \right \}.$

*$f= \infty  :$ $L_1= \left \{w_1=0  \right \}   ; L_2=\left \{ w_2=0 \right \} $
$(f)=mD-n_1L_1-n_2L_2$
Let us take Affine set $A=\left \{ w_3\neq 0 \right \}$ where $x=\frac{w_0}{w_3}, y=\frac{w_1}{w_3}, z=\frac{w_2}{w_3}$. After the intersection of A with 3 curves, we get:
$A\cap D=\left \{ x=0 \right \}; A\cap L_1=\left \{ y=0 \right \};A\cap L_2=\left \{ z=0 \right \}$
hence: $f(x,y,z)=\frac{x^2}{yz}$, so $m=2, n_1=n_2=1$, and $(f)=2D-L_1-L_2$
Is it right? Thanks!


text:
Q: Getting locked out of Google Compute Engine Instance So I've read through quite a few posts related to my similar issue. I've followed the explanations with no success. No matter what user I log in as, I receive "Permission denied (publickey).".
I've even attempted to create a new Google RSA key pair on my workstation. When I created that, I receive the standard message:
"INFO: Updated project with new ssh key. It can take some time for the instance to pick up the key.
INFO: Waiting 10 seconds before attempting to connect."
Any thoughts how I can get back into my server?

A: Check if your instance has instance-specific sshKeys metadata using "gcutil getinstance " and looking for an sshKeys entry under the metadata section.  If the instance has an sshKeys entry, you can try adding your new key to it using the custom instance metadata command of "gcutil setinstancemetadata  --metadata=sshKeys: --fingerprint=", using the ssh key syntax for mapping a key to a user in GCE.
Alternatively, given that gcutil added your new ssh key to the project-level metadata, you could try deleting the instance-level sshKeys metadata altogether and see if it reverts to using the project-level sshKeys metadata.

A: We have created a startup script to self-manage and troubleshoot ssh connectivity issues https://github.com/GoogleCloudPlatform/compute-ssh-diagnostic-sh/
what you describe is easiest to resolve by destroying the instance with deleteinstance --nodelete_boot_pd bring up a brand new instance from a stock image, attach your original disk as a second disk to the new instance, inspect and fix any issues with your configuration on the disk, destroy the new instance and disk, recreate your original instance with the original disk


text:
Q: Hiding source in flash player I have to develop an application to play video online using flash player. All the video files have some cost to play/download and should not to be downloaded.
So now the problem is that when a user play a video he/she can view the source of flash player and then can download.
Please tell me how it is possible to hide or some other stuffs?

A: How can the user view the source of the Flash video if you use a front end video player? You typically have a video file, then an Flash player application that can browse videos and play them but not reveal the source.
Alternative, is a using a streaming server, like Flash media server, where the video is fed to the front end and not available as a single file.


text:
Q: nasm segfault in simple programm This code is supposed to output length of key in 1 digit but it outputs segfault.
I can't understand what I've done wrong, the problem must be in the first part of listing, because I took the flen function straight from from book:
    section .text
    global _start   ;must be declared for linker (ld)
_start:

    mov edi,key
        call flen
        mov ebx,1
        add ecx,38
        mov edx,1
        int 0x80

    flen:           ;length of string on es:edi
    xor eax,eax
    xor ecx,ecx
    dec ecx
    cld
    repne scasb
    neg ecx
    ret

    xor eax,eax
    inc eax
    int 0x80

section .data
key db '123456',0x0
keylen equ $ - key     ;length of our dear string
plaintext times 256 db 1

A: You should move the exit code to before flen. As it is your control flow falls through into flen again after the system call returns. Also you should put a system call number into eax. Furhermore, the value to be printed must be in memory, and a pointer must be passed. The ascii code of 0 is 48 not 38, or you could just use '0'. Something like this:
    section .text
    global _start   ;must be declared for linker (ld)
_start:

    mov edi,key
        call flen
        add ecx, '0' ; convert to ascii
        push ecx     ; put text onto stack
        mov ecx, esp ; put address into ecx
        mov eax, 4   ; sys_write
        mov ebx,1
        mov edx,1
        int 0x80

    xor eax,eax
    inc eax
    int 0x80

    flen:           ;length of string on es:edi
    xor eax,eax
    xor ecx,ecx
    dec ecx
    cld
    repne scasb
    neg ecx
    ret

section .data
key db '123456',0x0
keylen equ $ - key     ;length of our dear string
plaintext times 256 db 1

Note that flen returns 8.
PS: Learn to use a debugger.