问:
How to clear previous lines from StreamWriter?
```<code>void BuildProjects()
{
    String outputPath = @"D:\PIT\ProcessImprovementTool\DLL";
    console = new Process();
    console.StartInfo.FileName = "cmd.exe";
    console.StartInfo.UseShellExecute = false;
    console.StartInfo.CreateNoWindow = true;
    console.StartInfo.RedirectStandardInput = true;
    console.StartInfo.RedirectStandardOutput = true;
    console.StartInfo.RedirectStandardError = true;
    console.Exited += new EventHandler((sender, e) =>
    {
        Console.WriteLine("if (console.Exited) --> ExitCode: " + console.ExitCode);
        BuildProjects();
    });
    console.OutputDataReceived += new DataReceivedEventHandler(ConsoleOutputHandler);
    console.ErrorDataReceived += new DataReceivedEventHandler(ConsoleOutputHandler);
    console.Start();
    using (StreamWriter sw = console.StandardInput)
    {
        sw.AutoFlush = true;
        console.StandardInput.AutoFlush = true;
        if (sw.BaseStream.CanWrite)
        {
            sw.WriteLine("D:\\PIT\\ProcessImprovementTool\\callVcvars32.bat");
            sw.WriteLine("cls");
            for (int ctr = 0; ctr < 5; ctr++)
            {
                sw.WriteLine("msbuild /property:OutputPath=" + outputPath + @";OutputType=Library " + lines[ctr]);
                //console.BeginOutputReadLine();
                sw.Flush();
            }
        }
        if (tryout)
        {
            Console.WriteLine("working");
        }
        sw.Close();
        //sw.Flush();
    }
    console.BeginOutputReadLine();
    console.BeginErrorReadLine();
    //console.WaitForExit();
    counter++;
}
</code>```

in the

```<code>for (int ctr = 0; ctr < 5; ctr++)
{
    sw.WriteLine("msbuild /property:OutputPath=" + outputPath + @";OutputType=Library " + lines[ctr]);
    //console.BeginOutputReadLine();
    sw.Flush();
}
</code>```

if i set the limit for ctr to 40 (ctr < 40) my application hangs, and I get that the stream is already at its limit.

Based on my research, .Flush() should do the trick. or setting AutoFlush to True, but doesn't seem to work.

so how do I clear previous stream records, or anything that would let me input more than 40 lines? (i got 100+ but not more than 150 lines to write in streamWriter).

lines variable stores the value of "build.txt".

```<code>void readFromBuild()
{
    doneReading = true;
    lines = System.IO.File.ReadAllLines(@"D:\PIT\ProcessImprovementTool\Build\build.txt");
    //System.Console.WriteLine("Contents of WriteLines2.txt = ");
    foreach (string line in lines)
    {
        lineCount++;
    }
    Console.WriteLine(lineCount);
    lineCount = lineCount - limit;
}
</code>```

"build.txt" contains all files to be compiled to produce DLL files.

答:
For me, this is as good as answered. I just did it in another way, though it may not be that good.</p>

```<code>buildProgress.Enabled = true;
buildProgress.Maximum = lineCount;
for (int ctr = 0; ctr < lineCount; ctr++)
{
    String outputPath = @"Q:\";
    StreamReader reader;
    String outputLine;
    console = new Process();
    console.StartInfo.FileName = "cmd.exe";
    console.StartInfo.UseShellExecute = false;
    console.StartInfo.CreateNoWindow = true;
    console.StartInfo.RedirectStandardInput = true;
    console.StartInfo.RedirectStandardOutput = true;
    console.StartInfo.RedirectStandardError = true;
    console.Start();
    using (StreamWriter sw = console.StandardInput)
    {
        sw.AutoFlush = true;
        console.StandardInput.AutoFlush = true;
        if (sw.BaseStream.CanWrite)
        {
            sw.WriteLine(@"Q:\");
            sw.WriteLine("msbuild /property:OutputPath=" + outputPath + @";OutputType=Library " + lines[ctr]);
            sw.Flush();
        }
        sw.Close();
    }
    reader = console.StandardOutput;
    outputLine = reader.ReadToEnd();
    console.WaitForExit();
    //if (console.HasExited)
    //{
        Console.Write(outputLine);
        //outputTextBox.Text += outputLine;
        pathToLog = @"Q:\" + fileList[ctr];
        File.Create(pathToLog).Dispose();
        File.WriteAllText(pathToLog, outputLine);
        buildProgress.Value = ctr;
        string[] readThatLog = File.ReadAllLines(pathToLog);
        foreach(string line in readThatLog)
        {
            if (line == "Build succeeded.")
            {
                outputTextBox.AppendText(lines[ctr]);
                outputTextBox.AppendText(Environment.NewLine + line);
                outputTextBox.AppendText(Environment.NewLine + Environment.NewLine);
            }
            else if (line == "Build FAILED.")
            {
                outputTextBox.AppendText(lines[ctr]);
                outputTextBox.AppendText(Environment.NewLine + line);
                outputTextBox.AppendText(Environment.NewLine + Environment.NewLine);
            }
        }
    //}
}
buildProgress.Value = 0;
buildProgress.Enabled = false;
Console.WriteLine("\n\n\n\nDONE!!!");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
void BuildProjects()
{
    String outputPath = @"D:\PIT\ProcessImprovementTool\DLL";
    console = new Process();
    console.StartInfo.FileName = "cmd.exe";
    console.StartInfo.UseShellExecute = false;
    console.StartInfo.CreateNoWindow = true;
    console.StartInfo.RedirectStandardInput = true;
    console.StartInfo.RedirectStandardOutput = true;
    console.StartInfo.RedirectStandardError = true;
    console.Exited += new EventHandler((sender, e) =>
    {
        Console.WriteLine("if (console.Exited) --> ExitCode: " + console.ExitCode);
        BuildProjects();
    });
    console.OutputDataReceived += new DataReceivedEventHandler(ConsoleOutputHandler);
    console.ErrorDataReceived += new DataReceivedEventHandler(ConsoleOutputHandler);
    console.Start();
    using (StreamWriter sw = console.StandardInput)
    {
        sw.AutoFlush = true;
        console.StandardInput.AutoFlush = true;
        if (sw.BaseStream.CanWrite)
        {
            sw.WriteLine("D:\\PIT\\ProcessImprovementTool\\callVcvars32.bat");
            sw.WriteLine("cls");
            for (int ctr = 0; ctr < 5; ctr++)
            {
                sw.WriteLine("msbuild /property:OutputPath=" + outputPath + @";OutputType=Library " + lines[ctr]);
                //console.BeginOutputReadLine();
                sw.Flush();
            }
        }
        if (tryout)
        {
            Console.WriteLine("working");
        }
        sw.Close();
        //sw.Flush();
    }
    console.BeginOutputReadLine();
    console.BeginErrorReadLine();
    //console.WaitForExit();
    counter++;
}

in the

for (int ctr = 0; ctr < 5; ctr++)
{
    sw.WriteLine("msbuild /property:OutputPath=" + outputPath + @";OutputType=Library " + lines[ctr]);
    //console.BeginOutputReadLine();
    sw.Flush();
}

if i set the limit for ctr to 40 (ctr < 40) my application hangs, and I get that the stream is already at its limit.

Based on my research, .Flush() should do the trick. or setting AutoFlush to True, but doesn't seem to work.

so how do I clear previous stream records, or anything that would let me input more than 40 lines? (i got 100+ but not more than 150 lines to write in streamWriter).

lines variable stores the value of "build.txt".

void readFromBuild()
{
    doneReading = true;
    lines = System.IO.File.ReadAllLines(@"D:\PIT\ProcessImprovementTool\Build\build.txt");
    //System.Console.WriteLine("Contents of WriteLines2.txt = ");
    foreach (string line in lines)
    {
        lineCount++;
    }
    Console.WriteLine(lineCount);
    lineCount = lineCount - limit;
}

"build.txt" contains all files to be compiled to produce DLL files.

Body:
For me, this is as good as answered. I just did it in another way, though it may not be that good.

buildProgress.Enabled = true;
buildProgress.Maximum = lineCount;
for (int ctr = 0; ctr < lineCount; ctr++)
{
    String outputPath = @"Q:\";
    StreamReader reader;
    String outputLine;
    console = new Process();
    console.StartInfo.FileName = "cmd.exe";
    console.StartInfo.UseShellExecute = false;
    console.StartInfo.CreateNoWindow = true;
    console.StartInfo.RedirectStandardInput = true;
    console.StartInfo.RedirectStandardOutput = true;
    console.StartInfo.RedirectStandardError = true;
    console.Start();
    using (StreamWriter sw = console.StandardInput)
    {
        sw.AutoFlush = true;
        console.StandardInput.AutoFlush = true;
        if (sw.BaseStream.CanWrite)
        {
            sw.WriteLine(@"Q:\");
            sw.WriteLine("msbuild /property:OutputPath=" + outputPath + @";OutputType=Library " + lines[ctr]);
            sw.Flush();
        }
        sw.Close();
    }
    reader = console.StandardOutput;
    outputLine = reader.ReadToEnd();
    console.WaitForExit();
    //if (console.HasExited)
    //{
        Console.Write(outputLine);
        //outputTextBox.Text += outputLine;
        pathToLog = @"Q:\" + fileList[ctr];
        File.Create(pathToLog).Dispose();
        File.WriteAllText(pathToLog, outputLine);
        buildProgress.Value = ctr;
        string[] readThatLog = File.ReadAllLines(pathToLog);
        foreach(string line in readThatLog)
        {
            if (line == "Build succeeded.")
            {
                outputTextBox.AppendText(lines[ctr]);
                outputTextBox.AppendText(Environment.NewLine + line);
                outputTextBox.AppendText(Environment.NewLine + Environment.NewLine);
            }
            else if (line == "Build FAILED.")
            {
                outputTextBox.AppendText(lines[ctr]);
                outputTextBox.AppendText(Environment.NewLine + line);
                outputTextBox.AppendText(Environment.NewLine + Environment.NewLine);
            }
        }
    //}
}
buildProgress.Value = 0;
buildProgress.Enabled = false;
Console.WriteLine("\n\n\n\nDONE!!!");


来源: stackexchange

问:
Insert Data into middle of range
I have the following model

```<code>public class DailyRoutine
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public string Description { get; set; }
}
</code>```

Scenario:
When is created at initial time with 5 records which means 5 entries are entered for each day. Take an example May 1 to May 5 of 2017. Description have any string.

User can add a new record in the middle so that the following records should be moved and changed to next days.

Expected Output:
Example, user can give a date and description in input and submit. If the input date is '5/3/2017' (May 3), the entry should be added after May 2 record and the existing May 3 record changed to May 4, May 4 to May 5 etc. So the out is like May 1 to May 6 and the given input is updated on May 3.

Please help me to this with out degrading performance

答:
This approach will work:</p>

```<code>List<DailyRoutine> d = new List<DailyRoutine>()
{
    new DailyRoutine() { Date = new DateTime(2017, 7, 1)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 2)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 3)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 4)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 5)}
};

DailyRoutine newDr = new DailyRoutine() { Date = new DateTime(2017, 7, 2) };
DailyRoutine oldDr = d.Where(dr => dr.Date == newDr.Date).FirstOrDefault();

if (oldDr != null)
{
    int idx = d.IndexOf(oldDr);
    List<DailyRoutine> changeList = d.Where((dr, i) => i >= idx).ToList();

    foreach (DailyRoutine i in changeList)
    {
        i.Date = i.Date.AddDays(1);
    }

    d.Insert((int)idx, newDr);
}
else
{
    d.Add(newDr);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Insert Data into middle of range

Body:
I have the following model

public class DailyRoutine
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public string Description { get; set; }
}

Scenario:
When is created at initial time with 5 records which means 5 entries are entered for each day. Take an example May 1 to May 5 of 2017. Description have any string.

User can add a new record in the middle so that the following records should be moved and changed to next days.

Expected Output:
Example, user can give a date and description in input and submit. If the input date is '5/3/2017' (May 3), the entry should be added after May 2 record and the existing May 3 record changed to May 4, May 4 to May 5 etc. So the out is like May 1 to May 6 and the given input is updated on May 3.

Please help me to this with out degrading performance

Body:
This approach will work:

List<DailyRoutine> d = new List<DailyRoutine>()
{
    new DailyRoutine() { Date = new DateTime(2017, 7, 1)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 2)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 3)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 4)},
    new DailyRoutine() { Date = new DateTime(2017, 7, 5)}
};

DailyRoutine newDr = new DailyRoutine() { Date = new DateTime(2017, 7, 2) };
DailyRoutine oldDr = d.Where(dr => dr.Date == newDr.Date).FirstOrDefault();

if (oldDr != null)
{
    int idx = d.IndexOf(oldDr);
    List<DailyRoutine> changeList = d.Where((dr, i) => i >= idx).ToList();

    foreach (DailyRoutine i in changeList)
    {
        i.Date = i.Date.AddDays(1);
    }

    d.Insert((int)idx, newDr);
}
else
{
    d.Add(newDr);
}


问:
How to write a service which consumes 2 different types of objects but have a single endpoint?
How to write a service which consumes 2 different types of objects but have a single endpoint ?

/hello is the endpoint I should be able to handle Class Hello1 and Class Hello2 in that...both having different parameters.

```<code>@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello1 request) {}

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello2 request) {}
</code>```

Above is what I need actually...but it needs to be a single endpoint.

答:
I don't think that it is possible to have two methods which respond to the same request (By same request I mean the same routing path and the same method).

What you can do is to create a single entry for the "hello" POST request, and make a DTO object which contains all the members of Hello1 plus all the members of Hell2. Inside the entry method you write the code to determine the type of the request, and do the replies respectively.

Body:
How to write a service which consumes 2 different types of objects but have a single endpoint ?

/hello is the endpoint I should be able to handle Class Hello1 and Class Hello2 in that...both having different parameters.

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello1 request) {}

@CrossOrigin
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public BaseResponseDTO geteula(@RequestBody Hello2 request) {}

Above is what I need actually...but it needs to be a single endpoint.


问:
Can't use CKEDITOR in django template
I am using a form without a model class.

```<code>class ClubWallForm(forms.Form):

    title = forms.CharField(label='Post title', max_length=100)
    description = RichTextField()
    imgURL = forms.CharField(label='Post image url', max_length=100)
    filefield = forms.FileField( label='Select a file',validators=[validate_file_extension] )
</code>```

In my template I used

```<code>`        {% for field in form %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }}: {{ field }}
            </div>
        {% endfor %}`
</code>```

CKEDITOR is not geting displayed in my template.
This is what I am getting.

Inside my views it tried to use ipdb and found that the form has only fields title imgurl and filefield .

答:
Finally I got an answer from my friend.
it was to replace

```<code>description = RichTextField()
</code>```

with

```<code>description = forms.CharField(label='Description',
                   widget=forms.Textarea(attrs={'class': 'ckeditor'}))
</code>```

inside forms.py
and it is working

Title: Can't use CKEDITOR in django template

Body:
I am using a form without a model class.

class ClubWallForm(forms.Form):

    title = forms.CharField(label='Post title', max_length=100)
    description = RichTextField()
    imgURL = forms.CharField(label='Post image url', max_length=100)
    filefield = forms.FileField( label='Select a file',validators=[validate_file_extension] )

In my template I used

`        {% for field in form %}

                {{ field.errors }}
                {{ field.label_tag }}: {{ field }}

        {% endfor %}`

CKEDITOR is not geting displayed in my template.
This is what I am getting.

Inside my views it tried to use ipdb and found that the form has only fields title imgurl and filefield .

Body:
Finally I got an answer from my friend.
it was to replace

description = RichTextField()

with

description = forms.CharField(label='Description',
                   widget=forms.Textarea(attrs={'class': 'ckeditor'}))

inside forms.py
and it is working


问:
NinjectDependencyResolver fails binding ModelValidatorProvider
I'm developing an ASP.NET Web Api 2.2 with C#, .NET Framework 4.5.1.

After updating my Web.Api to Ninject 3.2.0 I get this error:

```<code>Error activating ModelValidatorProvider using binding from ModelValidatorProvider to NinjectDefaultModelValidatorProvider
A cyclical dependency was detected between the constructors of two services.

Activation path:
  3) Injection of dependency ModelValidatorProvider into parameter defaultModelValidatorProviders of constructor of type DefaultModelValidatorProviders
  2) Injection of dependency DefaultModelValidatorProviders into parameter defaultModelValidatorProviders of constructor of type NinjectDefaultModelValidatorProvider
  1) Request for ModelValidatorProvider

Suggestions:
  1) Ensure that you have not declared a dependency for ModelValidatorProvider on any implementations of the service.
  2) Consider combining the services into a single one to remove the cycle.
  3) Use property injection instead of constructor injection, and implement IInitializable
     if you need initialization logic to be run after property values have been injected.
</code>```

I get the exception in NinjectWebCommon:

```<code>public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        var containerConfigurator = new NinjectConfigurator();
        containerConfigurator.Configure(kernel);
    }
}
</code>```

NinjectDependencyResolver class:

```<code>using Ninject;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

namespace Matt.SocialNetwork.Web.Common
{
    public class NinjectDependencyResolver : IDependencyResolver
    {
        private readonly IKernel _container;

        public IKernel Container
        {
            get { return _container; }
        }

        public NinjectDependencyResolver(IKernel container)
        {
            _container = container;
        }

        public object GetService(Type serviceType)
        {
            return _container.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _container.GetAll(serviceType);
        }

        public IDependencyScope BeginScope()
        {
            return this;
        }

        public void Dispose()
        {
            // noop
        }
    }
}
</code>```

NinjectConfigurator class:

```<code>public class NinjectConfigurator
{
    public void Configure(IKernel container)
    {
        // Add all bindings/dependencies
        AddBindings(container);

        // Use the container and our NinjectDependencyResolver as
        // application's resolver
        var resolver = new NinjectDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }

    // Omitted for brevity.
}
</code>```

The strange thing is it compiles and works perfectly, but after update it doesn't work.

I have changed this public class NinjectDependencyResolver : IDependencyResolver, System.Web.Mvc.IDependencyResolver but it still doesn't work.

Any idea?

UPDATE

Debugging I see that the exception is thrown in NinjectDependencyResolver here:

```<code>public IEnumerable<object> GetServices(Type serviceType)
{
    return _container.GetAll(serviceType);
}
</code>```

It runs twice. First serviceType is IFilterProvider and second time serviceType is ModelValidatorProvider, and after that I get the exception.

These are the Ninject packages that I'm using:

```<code><package id="Ninject" version="3.2.2.0" targetFramework="net451" />
<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net451" />
<package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net451" />
<package id="Ninject.Web.WebApi" version="3.2.2.0" targetFramework="net451" />
</code>```

The previous version for these assemblies were:

```<code><package id="Ninject" version="3.2.2.0" targetFramework="net45" />
<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.2.0" targetFramework="net451" />
<package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net45" />
<package id="Ninject.Web.WebApi" version="3.2.0.0" targetFramework="net451" />
</code>```

SECOND UPDATE

I have found that the problem is in this class:

```<code>public static class WebContainerManager
{
    public static IKernel GetContainer()
    {
        var resolver = GlobalConfiguration.Configuration.DependencyResolver as NinjectDependencyResolver;
        if (resolver != null)
        {
            return resolver.Container;
        }

        throw new InvalidOperationException("NinjectDependencyResolver not being used as the MVC dependency resolver");
    }

    public static T Get<T>()
    {
        return GetContainer().Get<T>();
    }
}
</code>```

I set Dependency Resolver here:

```<code>public class NinjectConfigurator
{
    /// <summary>
    /// Entry method used by caller to configure the given
    /// container with all of this application's
    /// dependencies. Also configures the container as this
    /// application's dependency resolver.
    /// </summary>
    public void Configure(IKernel container)
    {
        // Add all bindings/dependencies
        AddBindings(container);

        // Use the container and our NinjectDependencyResolver as
        // application's resolver
        var resolver = new NinjectDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }
</code>```

And I use WebContainerManager in a class that inherits from ExceptionFilterAttribute:

```<code>public class UnhandledExceptionFilter : ExceptionFilterAttribute
{
    private readonly IExceptionLogHelper excepLogHelper;

    public UnhandledExceptionFilter()
        : this(WebContainerManager.Get<IExceptionLogHelper>()) {}

    public UnhandledExceptionFilter(IExceptionLogHelper exceptionLogHelper)
    {
        this.excepLogHelper = exceptionLogHelper;
    }

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        this.excepLogHelper.LogException(actionExecutedContext);
    }
}
</code>```

So, if I remove WebContainerManager I don't get that cycle.

答:
This is what worked for me.

uninstall-package Ninject.Web.WebApi.WebHost

The above command uninstalled the version 'Ninject.Web.WebApi.WebHost 3.2.4.0' and the error is gone!!

Just reconfirm, I have installed the same package using the command

install-package Ninject.Web.WebApi.WebHost

and the command installed the package 'Ninject.Web.WebApi.WebHost 3.2.4.0' and the error reappeared.

Body:
I'm developing an ASP.NET Web Api 2.2 with C#, .NET Framework 4.5.1.

After updating my Web.Api to Ninject 3.2.0 I get this error:

Error activating ModelValidatorProvider using binding from ModelValidatorProvider to NinjectDefaultModelValidatorProvider
A cyclical dependency was detected between the constructors of two services.

Activation path:
  3) Injection of dependency ModelValidatorProvider into parameter defaultModelValidatorProviders of constructor of type DefaultModelValidatorProviders
  2) Injection of dependency DefaultModelValidatorProviders into parameter defaultModelValidatorProviders of constructor of type NinjectDefaultModelValidatorProvider
  1) Request for ModelValidatorProvider

Suggestions:
  1) Ensure that you have not declared a dependency for ModelValidatorProvider on any implementations of the service.
  2) Consider combining the services into a single one to remove the cycle.
  3) Use property injection instead of constructor injection, and implement IInitializable
     if you need initialization logic to be run after property values have been injected.

I get the exception in NinjectWebCommon:

public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    ///
    /// Starts the application
    ///
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    ///
    /// Stops the application.
    ///
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    ///
    /// Creates the kernel that will manage your application.
    ///
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    ///
    /// Load your modules or register your services here!
    ///
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        var containerConfigurator = new NinjectConfigurator();
        containerConfigurator.Configure(kernel);
    }
}

NinjectDependencyResolver class:

using Ninject;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

namespace Matt.SocialNetwork.Web.Common
{
    public class NinjectDependencyResolver : IDependencyResolver
    {
        private readonly IKernel _container;

        public IKernel Container
        {
            get { return _container; }
        }

        public NinjectDependencyResolver(IKernel container)
        {
            _container = container;
        }

        public object GetService(Type serviceType)
        {
            return _container.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _container.GetAll(serviceType);
        }

        public IDependencyScope BeginScope()
        {
            return this;
        }

        public void Dispose()
        {
            // noop
        }
    }
}

NinjectConfigurator class:

public class NinjectConfigurator
{
    public void Configure(IKernel container)
    {
        // Add all bindings/dependencies
        AddBindings(container);

        // Use the container and our NinjectDependencyResolver as
        // application's resolver
        var resolver = new NinjectDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }

    // Omitted for brevity.
}

The strange thing is it compiles and works perfectly, but after update it doesn't work.

I have changed this public class NinjectDependencyResolver : IDependencyResolver, System.Web.Mvc.IDependencyResolver but it still doesn't work.

Any idea?

UPDATE

Debugging I see that the exception is thrown in NinjectDependencyResolver here:

public IEnumerable<object> GetServices(Type serviceType)
{
    return _container.GetAll(serviceType);
}

It runs twice. First serviceType is IFilterProvider and second time serviceType is ModelValidatorProvider, and after that I get the exception.

These are the Ninject packages that I'm using:

<package id="Ninject" version="3.2.2.0" targetFramework="net451" />
<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net451" />
<package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net451" />
<package id="Ninject.Web.WebApi" version="3.2.2.0" targetFramework="net451" />

The previous version for these assemblies were:

<package id="Ninject" version="3.2.2.0" targetFramework="net45" />
<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.2.0" targetFramework="net451" />
<package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net45" />
<package id="Ninject.Web.WebApi" version="3.2.0.0" targetFramework="net451" />

SECOND UPDATE

I have found that the problem is in this class:

public static class WebContainerManager
{
    public static IKernel GetContainer()
    {
        var resolver = GlobalConfiguration.Configuration.DependencyResolver as NinjectDependencyResolver;
        if (resolver != null)
        {
            return resolver.Container;
        }

        throw new InvalidOperationException("NinjectDependencyResolver not being used as the MVC dependency resolver");
    }

    public static T Get<T>()
    {
        return GetContainer().Get<T>();
    }
}

I set Dependency Resolver here:

public class NinjectConfigurator
{
    ///
    /// Entry method used by caller to configure the given
    /// container with all of this application's
    /// dependencies. Also configures the container as this
    /// application's dependency resolver.
    ///
    public void Configure(IKernel container)
    {
        // Add all bindings/dependencies
        AddBindings(container);

        // Use the container and our NinjectDependencyResolver as
        // application's resolver
        var resolver = new NinjectDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }

And I use WebContainerManager in a class that inherits from ExceptionFilterAttribute:

public class UnhandledExceptionFilter : ExceptionFilterAttribute
{
    private readonly IExceptionLogHelper excepLogHelper;

    public UnhandledExceptionFilter()
        : this(WebContainerManager.Get<IExceptionLogHelper>()) {}

    public UnhandledExceptionFilter(IExceptionLogHelper exceptionLogHelper)
    {
        this.excepLogHelper = exceptionLogHelper;
    }

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        this.excepLogHelper.LogException(actionExecutedContext);
    }
}

So, if I remove WebContainerManager I don't get that cycle.


问:
Question about C++0x reference collapse
I don't know why these code can't be compiled.  I'v tested in Visual c++ 2010 and gcc with -std=c++0x. anyone give some suggestion?
thanks!

```<code>template<typename T>
class Foo
{
public:
 void test(const T&){cout<<"const";}
 void test(      T&){cout<<"non const";}
};

int main()
{
 int a;
 Foo<int&> f;
}
</code>```

compile error:  'void Foo::test(T)' : member function already defined or declared

but why this can be compiled?

```<code>template<typename T> void foo(const T&){cout<<"const"; }
template<typename T> void foo( T&){cout<<"non const"; }
int main()
 {
    int a;
    foo<int&>(a);
 }
</code>```

i'v read c++0x article said: T& & ==T& , so  const T& & == const T& ?

答:
i'v read c++0x article said: T& & ==T& , so const T& & == const T& ?

Actually, that doesn't make a lot of sense. IMHO, it's better to put this into a table:

```<code>T       T&      const T      const T&
---------------------------------------
int     int&    const int    const int&
int&    int&    int&         int&
        (1)     (2)          (1+2)

1: Reference collapsing in action
2: const applies to the reference and is therefore ignored
</code>```

If T is already a reference (2nd row) the const in const T applies to the reference and not to the referee. But a reference is inherently constant in the sense that you cannot make it refer to another object after initialization, so a const is just ignored here. You can think of it as "const collapsing". ;-)

ContentLicense: CC BY-SA 2.5

Title: Question about C++0x reference collapse

Body:
I don't know why these code can't be compiled.  I'v tested in Visual c++ 2010 and gcc with -std=c++0x. anyone give some suggestion?
thanks!

template<typename T>
class Foo
{
public:
 void test(const T&){cout<<"const";}
 void test(      T&){cout<<"non const";}
};

int main()
{
 int a;
 Foo<int&> f;
}

compile error:  'void Foo::test(T)' : member function already defined or declared

but why this can be compiled?

template<typename T> void foo(const T&){cout<<"const"; }
template<typename T> void foo( T&){cout<<"non const"; }
int main()
 {
    int a;
    foo<int&>(a);
 }

i'v read c++0x article said: T& & ==T& , so  const T& & == const T& ?

Body:
i'v read c++0x article said: T& & ==T& , so const T& & == const T& ?

Actually, that doesn't make a lot of sense. IMHO, it's better to put this into a table:

T       T&      const T      const T&
---------------------------------------
int     int&    const int    const int&
int&    int&    int&         int&
        (1)     (2)          (1+2)

1: Reference collapsing in action
2: const applies to the reference and is therefore ignored

If T is already a reference (2nd row) the const in const T applies to the reference and not to the referee. But a reference is inherently constant in the sense that you cannot make it refer to another object after initialization, so a const is just ignored here. You can think of it as "const collapsing". ;-)


问:
Smooth scroll to top not working
I am using the to top arrow in website to move to the top section with smooth scroll.. Now its moving to top but not moving in smooth..

The js that i used to get smooth scroll was

```<code>$(function() {
  $('a.page-scroll').bind('click', function(event) {
    console.log("scroll");
    var $anchor = $(this);
  $('html, body').stop().animate({
      scrollTop: $($anchor.attr('href')).offset().top
  }, 1500, 'easeInOutExpo');
  event.preventDefault();
  });
});
</code>```

BUt its not working..
The jsfiddle was https://jsfiddle.net/36m5kp00/

The jquery's that i have used was,

```<code><script src="scripts/controllers/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</code>```

答:
Actually you need to add the jquery easing plugin if you want to use custom easing methods like easeInOutExpo.

Note: jQuery comes with 2 easing methods linear & swing. Reference here: https://api.jqueryui.com/easings/

Here you can get it from: https://cdnjs.com/libraries/jquery-easing

It works well, Check it here: https://jsfiddle.net/ashishanexpert/36m5kp00/4/

Your working code should be like:

```<code>$(window).scroll(function() {
  if ($(this).scrollTop()) {
    $('#letTop:hidden').stop(true, true).fadeIn();
  } else {
    $('#letTop').stop(true, true).fadeOut();
  }
});
$(function() {
  $('a.page-scroll').bind('click', function(event) {
    console.log("scroll");
    var $anchor = $(this);
  $('html, body').stop().animate({
      scrollTop: $($anchor.attr('href')).offset().top
  }, 1500, 'easeInOutExpo');
  event.preventDefault();
  });
});
</code>```

Title: Smooth scroll to top not working

Body:
I am using the to top arrow in website to move to the top section with smooth scroll.. Now its moving to top but not moving in smooth..

The js that i used to get smooth scroll was

$(function() {
  $('a.page-scroll').bind('click', function(event) {
    console.log("scroll");
    var $anchor = $(this);
  $('html, body').stop().animate({
      scrollTop: $($anchor.attr('href')).offset().top
  }, 1500, 'easeInOutExpo');
  event.preventDefault();
  });
});

BUt its not working..
The jsfiddle was https://jsfiddle.net/36m5kp00/

The jquery's that i have used was,

Body:
Actually you need to add the jquery easing plugin if you want to use custom easing methods like easeInOutExpo.

Note: jQuery comes with 2 easing methods linear & swing. Reference here: https://api.jqueryui.com/easings/

Here you can get it from: https://cdnjs.com/libraries/jquery-easing

It works well, Check it here: https://jsfiddle.net/ashishanexpert/36m5kp00/4/

Your working code should be like:

$(window).scroll(function() {
  if ($(this).scrollTop()) {
    $('#letTop:hidden').stop(true, true).fadeIn();
  } else {
    $('#letTop').stop(true, true).fadeOut();
  }
});
$(function() {
  $('a.page-scroll').bind('click', function(event) {
    console.log("scroll");
    var $anchor = $(this);
  $('html, body').stop().animate({
      scrollTop: $($anchor.attr('href')).offset().top
  }, 1500, 'easeInOutExpo');
  event.preventDefault();
  });
});


问:
SQL Server - Convert date field to UTC
I have recently updated my system to record date/times as UTC as previously they were storing as local time.

I now need to convert all the local stored date/times to UTC. I was wondering if there is any built in function, similar to .NET's ConvertTime method?

I am trying to avoid having to write a utility app to do this for me.

Any suggestions?

答:
We can convert ServerZone DateTime to UTC and UTC to ServerZone DateTime

Simply run the following scripts to understand the conversion then modify as what you need

```<code>--Get Server's TimeZone
DECLARE @ServerTimeZone VARCHAR(50)
EXEC MASTER.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
'TimeZoneKeyName',@ServerTimeZone OUT

-- ServerZone to UTC DATETIME
DECLARE @CurrentServerZoneDateTime DATETIME = GETDATE()
DECLARE @UTCDateTime  DATETIME =  @CurrentServerZoneDateTime AT TIME ZONE @ServerTimeZone AT TIME ZONE 'UTC'
--(OR)
--DECLARE @UTCDateTime  DATETIME = GETUTCDATE()
SELECT @CurrentServerZoneDateTime AS CURRENTZONEDATE,@UTCDateTime AS UTCDATE

-- UTC to ServerZone DATETIME
SET @CurrentServerZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE @ServerTimeZone
SELECT @UTCDateTime AS UTCDATE,@CurrentServerZoneDateTime AS CURRENTZONEDATE
</code>```

Note: This(AT TIME ZONE) working on only SQL Server 2016+ and this advantage is automatically considering Daylight while converting to particular Time zone

Title: SQL Server - Convert date field to UTC

Body:
We can convert ServerZone DateTime to UTC and UTC to ServerZone DateTime

Simply run the following scripts to understand the conversion then modify as what you need

--Get Server's TimeZone
DECLARE @ServerTimeZone VARCHAR(50)
EXEC MASTER.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
'TimeZoneKeyName',@ServerTimeZone OUT

-- ServerZone to UTC DATETIME
DECLARE @CurrentServerZoneDateTime DATETIME = GETDATE()
DECLARE @UTCDateTime  DATETIME =  @CurrentServerZoneDateTime AT TIME ZONE @ServerTimeZone AT TIME ZONE 'UTC'
--(OR)
--DECLARE @UTCDateTime  DATETIME = GETUTCDATE()
SELECT @CurrentServerZoneDateTime AS CURRENTZONEDATE,@UTCDateTime AS UTCDATE

-- UTC to ServerZone DATETIME
SET @CurrentServerZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE @ServerTimeZone
SELECT @UTCDateTime AS UTCDATE,@CurrentServerZoneDateTime AS CURRENTZONEDATE

Note: This(AT TIME ZONE) working on only SQL Server 2016+ and this advantage is automatically considering Daylight while converting to particular Time zone


问:
How can i open IE without Back Forward buttons
I want to open IE without Back Forward buttons using C# Code.Just like this:

But it shows like this:

The C# code is:

```<code>using (WebBrowser wb = new WebBrowser())
{
    wb.Url = new System.Uri("about:blank");
    wb.Document.Window.OpenNew(URLStr.ToString(), "location=yes,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=yes");
}
</code>```

I wonder where did i go wrong?

答:
Create a custom form to hold your browser and do not show the browser itself. Please check my sample code which does the same:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        WebBrowser webbrowser = new WebBrowser();
        webbrowser.Parent = this;
        webbrowser.Dock = DockStyle.Fill;
        webbrowser.Navigate("www.google.com");
    }
}
</code>```

Body:
I want to open IE without Back Forward buttons using C# Code.Just like this:

But it shows like this:

The C# code is:

using (WebBrowser wb = new WebBrowser())
{
    wb.Url = new System.Uri("about:blank");
    wb.Document.Window.OpenNew(URLStr.ToString(), "location=yes,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=yes");
}

I wonder where did i go wrong?

Body:
Create a custom form to hold your browser and do not show the browser itself. Please check my sample code which does the same:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        WebBrowser webbrowser = new WebBrowser();
        webbrowser.Parent = this;
        webbrowser.Dock = DockStyle.Fill;
        webbrowser.Navigate("www.google.com");
    }
}


问:
.htaccess blacklist from text file and redirect
I have a site where I want to redirect incoming requests only if they don't appear in a blacklist file. I'd like to store the file outside the public html directory so it would be something like var/www/blacklists/example.com.blacklist and the content would look like

```<code>hello
about
contact
portfolio
</code>```

If my site is example.com and the user visits https://example.com/goodbye, as long as "goodbye" isn't on the blacklist, it will redirect to https://somethingelse.com/goodbye.

If the user visits https://example.com/hello and "hello" is on the blacklist, it would resolve normally.

Also, all requests that resolve normally need to force ssl. example.com/hello or http://example.com/hello should be rewritten as https://example.com/hello

Thanks,
Howie

答:
Create a text file in any path outside your DocumentRoot. Each line should contain 2 columns separated by a single space. 1st column should have your blacklisted path vale and 2nd column should have value 1. Example below:

```<code>cat /tmp/blacklist.txt

hello 1
about 1
contact 1
portfolio 1
</code>```

Then inside the httpd.conf insert a new RewriteMap line as this:

```<code># First, we configure the "default" to be a very restrictive set of
# features.
<Directory />
     # Existing directives here
     # followed by this RewriteMap
     RewriteMap blacklist "txt:/tmp/blacklist.txt"
</Directory>
</code>```

Restart apache server

Finally, inside your site root .htaccess have these rules:

```<code>RewriteEngine On

RewriteCond ${blacklist:$0} !=1
RewriteRule .+ https://somethingelse.com%{REQUEST_URI} [L,NE,R=302]

RewriteCond %{HTTPS} off
RewriteCond ${blacklist:$0} =1
RewriteRule .+ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=302]
</code>```

Body:
I have a site where I want to redirect incoming requests only if they don't appear in a blacklist file. I'd like to store the file outside the public html directory so it would be something like var/www/blacklists/example.com.blacklist and the content would look like

hello
about
contact
portfolio

If my site is example.com and the user visits https://example.com/goodbye, as long as "goodbye" isn't on the blacklist, it will redirect to https://somethingelse.com/goodbye.

If the user visits https://example.com/hello and "hello" is on the blacklist, it would resolve normally.

Also, all requests that resolve normally need to force ssl. example.com/hello or http://example.com/hello should be rewritten as https://example.com/hello

Thanks,
Howie

Body:
Create a text file in any path outside your DocumentRoot. Each line should contain 2 columns separated by a single space. 1st column should have your blacklisted path vale and 2nd column should have value 1. Example below:

cat /tmp/blacklist.txt

hello 1
about 1
contact 1
portfolio 1

Then inside the httpd.conf insert a new RewriteMap line as this:

# First, we configure the "default" to be a very restrictive set of
# features.
<Directory />
     # Existing directives here
     # followed by this RewriteMap
     RewriteMap blacklist "txt:/tmp/blacklist.txt"
</Directory>

Restart apache server

Finally, inside your site root .htaccess have these rules:

RewriteEngine On

RewriteCond ${blacklist:$0} !=1
RewriteRule .+ https://somethingelse.com%{REQUEST_URI} [L,NE,R=302]

RewriteCond %{HTTPS} off
RewriteCond ${blacklist:$0} =1
RewriteRule .+ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=302]


问:
How to remove key from an array in php
I need to remove keys from my arrays, and array be like

```<code>Array ( [0] => 23/2 [1] => KG Halli [2] => D' Souza Layout [3] => Sampangi Rama Nagar [4] => Bengaluru [5] => Bangalore Urban [6] => Karnataka [7] => India [8] => 560001 )
</code>```

and i need it as

23/2, KG Halli, D' Souza Layout, Sampangi Rama Nagar, Bengaluru, Banglore Urban

答:
php implode() function is the answer to your question

You can use implode to make your array values as a string and attach each value with any separator i.e. ',' or a space.

```<code>implode(', ', ARRAY);
</code>```

Title: How to remove key from an array in php

Body:
I need to remove keys from my arrays, and array be like

Array ( [0] => 23/2 [1] => KG Halli [2] => D' Souza Layout [3] => Sampangi Rama Nagar [4] => Bengaluru [5] => Bangalore Urban [6] => Karnataka [7] => India [8] => 560001 )

and i need it as

23/2, KG Halli, D' Souza Layout, Sampangi Rama Nagar, Bengaluru, Banglore Urban

Body:
php implode() function is the answer to your question

You can use implode to make your array values as a string and attach each value with any separator i.e. ',' or a space.

implode(', ', ARRAY);


答:
use string function implode()

```<code>$arr = array('23/2','KG Halli',"D' Souza Layout",'Sampangi Rama Nagar' ,'Bengaluru','Bangalore Urban','Karnataka', 'India',560001);
echo implode(",",$arr);
</code>```

Title: How to remove key from an array in php

Body:
use string function implode()

$arr = array('23/2','KG Halli',"D' Souza Layout",'Sampangi Rama Nagar' ,'Bengaluru','Bangalore Urban','Karnataka', 'India',560001);
echo implode(",",$arr);


问:
How to calculate consecutiveness in Dataset?
I have data set where I need to calculate Consecutiveness of data if it is meeting certain status. The example dataset is as below. The use case is that, if the exchange id is consecutively having Risky and Unstable status then increment the count by 1 for that week and merge with the dataset. I am trying this using Spark.

```<code>Date    Exchange Id Status  Consecutiveness
5/05/2017   a   RISKY   0
5/05/2017   b   Stable  0
5/05/2017   c   Stable  0
5/05/2017   d   UNSTABLE    0
5/05/2017   e   UNKNOWN 0
5/05/2017   f   UNKNOWN 0
6/05/2017   a   RISKY   1
6/05/2017   b   Stable  0
6/05/2017   c   Stable  0
6/05/2017   d   UNSTABLE    1
6/05/2017   e   UNSTABLE    1
6/05/2017   f   UNKNOWN 0
</code>```

My approach was as follows.

Create dataframe for current date exchange having risky and unstable
condition

Create another dataframe for the previous date for exchanges having
risky and unstable

Join 2 dataframes and obtain exchanges not meeting criteria

Update the consecutiveness for current date

Merge with original dataset.

I am trying following commands. But, having issues and not able to proceed with 3,4,5

```<code>case class Telecom(Date: String, Exchange: String, Stability: String, Cosecutive: Int)

val emp1  = sc.textFile("file:/// Filename").map(_.split(",")).map(emp1=>Telecom(emp1(0),emp1(1),emp1(2),emp1(4).trim.toInt)).toDF()

val PreviousWeek = sqlContext.sql("select * from T1 limit 10")

emp1.registerTempTable("T1")

val FailPreviousWeek = sqlContext.sql("Select Exchange, Count  from T1 where Date = '5/05/2017' and Stability in ('RISKY','UNSTABLE')")

val FailCurrentWeek = sqlContext.sql("Select Exchange, Count  from T1 where Date = '6/05/2017' and Stability in ('RISKY','UNSTABLE')")

FailCurrentWeek.join(FailPreviousWeek, FailCurrentWeek("Exchange") === FailPreviousWeek("Exchange"))

val UpdateCurrentWeek = FailCurrentWeek.select($"Exchange",$"Count" +1)

Val UpdateDataSet = emp1.join(UpdateCurrentWeek)

  val UpdateCurrentWeek = FailCurrentWeek.select($"Exchange".alias("Exchangeid"),$"Count" +1)
</code>```

答:
I finally used Hive Window partitioning function with multiple loops.

First step converting the flags to boolean

Calculating the Consecutiveness with flag value in one loop

Then again having one more window partitioning with considering
consecutiveness in the loop.

This can be done same as using Spark SQL.

Body:
I have data set where I need to calculate Consecutiveness of data if it is meeting certain status. The example dataset is as below. The use case is that, if the exchange id is consecutively having Risky and Unstable status then increment the count by 1 for that week and merge with the dataset. I am trying this using Spark.

Date    Exchange Id Status  Consecutiveness
5/05/2017   a   RISKY   0
5/05/2017   b   Stable  0
5/05/2017   c   Stable  0
5/05/2017   d   UNSTABLE    0
5/05/2017   e   UNKNOWN 0
5/05/2017   f   UNKNOWN 0
6/05/2017   a   RISKY   1
6/05/2017   b   Stable  0
6/05/2017   c   Stable  0
6/05/2017   d   UNSTABLE    1
6/05/2017   e   UNSTABLE    1
6/05/2017   f   UNKNOWN 0

My approach was as follows.

Create dataframe for current date exchange having risky and unstable
condition

Create another dataframe for the previous date for exchanges having
risky and unstable

Join 2 dataframes and obtain exchanges not meeting criteria

Update the consecutiveness for current date

Merge with original dataset.

I am trying following commands. But, having issues and not able to proceed with 3,4,5

case class Telecom(Date: String, Exchange: String, Stability: String, Cosecutive: Int)

val emp1  = sc.textFile("file:/// Filename").map(_.split(",")).map(emp1=>Telecom(emp1(0),emp1(1),emp1(2),emp1(4).trim.toInt)).toDF()

val PreviousWeek = sqlContext.sql("select * from T1 limit 10")

emp1.registerTempTable("T1")

val FailPreviousWeek = sqlContext.sql("Select Exchange, Count  from T1 where Date = '5/05/2017' and Stability in ('RISKY','UNSTABLE')")

val FailCurrentWeek = sqlContext.sql("Select Exchange, Count  from T1 where Date = '6/05/2017' and Stability in ('RISKY','UNSTABLE')")

FailCurrentWeek.join(FailPreviousWeek, FailCurrentWeek("Exchange") === FailPreviousWeek("Exchange"))

val UpdateCurrentWeek = FailCurrentWeek.select($"Exchange",$"Count" +1)

Val UpdateDataSet = emp1.join(UpdateCurrentWeek)

  val UpdateCurrentWeek = FailCurrentWeek.select($"Exchange".alias("Exchangeid"),$"Count" +1)


问:
UITableView Content doesn't get deleted after deletion? [Swift 3.0 - Xcode 8]
Im trying to delete cells in my UITableView, but when I delete them, they reappear after I reload the app. I delete from the same array that I stored the values in with core data. Do I have to directly delete from coreData as well? how do I do that?

Heres my code:

```<code>///Function to remove TableView Cells

public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete
{
    SetTIME.remove(at: indexPath.row)
    if SaveData.count == 4 {
        SaveData.remove(at: myIndex*4)
        SaveData.remove(at: (myIndex*4)+1)
        SaveData.remove(at: (myIndex*4)+2)
        SaveData.remove(at: (myIndex*4)+3)}
        tableView.reloadData()
    }

}

 ///CoreData

override func viewDidLoad() {
    super.viewDidLoad()

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newTrip = NSEntityDescription.insertNewObject(forEntityName: "Sets", into: context)
    if DataGrab.count == 4{ // need to change after storing data in VC2 before sending
    newTrip.setValue(DataGrab[0], forKey: "set1")
    newTrip.setValue(DataGrab[1], forKey: "set4")
    newTrip.setValue(DataGrab[2], forKey: "set3")
    newTrip.setValue(DataGrab[3], forKey: "set2")}

    do {
        try context.save()
        print("Saved")
    }
    catch{
        //ProcessError
    }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Sets")
    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)
        if results.count > 0 {
            for result in results {
                if let set1 = (result as AnyObject).value(forKey: "set1") as? String
                {
                    if SaveData.contains(set1){

                    } else {
                    SaveData.append(set1)
                        SetTIME.append(set1)

                if let set2 = (result as AnyObject).value(forKey: "set2") as? String
                {
                    SaveData.append(set2)
                }
                if let set3 = (result as AnyObject).value(forKey: "set3") as? String
                {
                    SaveData.append(set3)
                }
                if let set4 = (result as AnyObject).value(forKey: "set4") as? String
                {
                    SaveData.append(set4)
                        }
                    }
                }
            }
        }
    }
    catch{
        //ProcessErrors
    }
</code>```

答:
```<code>    @IBOutlet weak var btnremove: UIButton!
        @IBOutlet weak var managetable: UITableView!
        var arrayStudent:[StudentData] = []
        var streno:String!
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        var managedContext:NSManagedObjectContext!
        var entity:NSEntityDescription!

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
        {
            let obj = arrayStudent[indexPath.row]
            streno = obj.strEnrollment
            print(streno)
           deleteFeed(eno:streno )
        }
func deleteFeed(eno:String)
    {
        managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Student")
        fetchRequest.predicate = NSPredicate(format: "eno = %@", "\(eno)")
        do
        {
            let fetchedResults =  try managedContext!.fetch(fetchRequest) as? [NSManagedObject]

            for entity in fetchedResults! {

                managedContext?.delete(entity)
                do
                {
                    try managedContext.save()
                    _ = self.navigationController?.popViewController(animated: true)

                }
                catch let error as Error!
                {
                    print(error.localizedDescription)
                }
                managetable.reloadData()

            }
        }
        catch _ {
            print("Could not delete")

        }
    }
</code>```

Body:
Im trying to delete cells in my UITableView, but when I delete them, they reappear after I reload the app. I delete from the same array that I stored the values in with core data. Do I have to directly delete from coreData as well? how do I do that?

Heres my code:

///Function to remove TableView Cells

public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete
{
    SetTIME.remove(at: indexPath.row)
    if SaveData.count == 4 {
        SaveData.remove(at: myIndex*4)
        SaveData.remove(at: (myIndex*4)+1)
        SaveData.remove(at: (myIndex*4)+2)
        SaveData.remove(at: (myIndex*4)+3)}
        tableView.reloadData()
    }

}

 ///CoreData

override func viewDidLoad() {
    super.viewDidLoad()

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newTrip = NSEntityDescription.insertNewObject(forEntityName: "Sets", into: context)
    if DataGrab.count == 4{ // need to change after storing data in VC2 before sending
    newTrip.setValue(DataGrab[0], forKey: "set1")
    newTrip.setValue(DataGrab[1], forKey: "set4")
    newTrip.setValue(DataGrab[2], forKey: "set3")
    newTrip.setValue(DataGrab[3], forKey: "set2")}

    do {
        try context.save()
        print("Saved")
    }
    catch{
        //ProcessError
    }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Sets")
    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)
        if results.count > 0 {
            for result in results {
                if let set1 = (result as AnyObject).value(forKey: "set1") as? String
                {
                    if SaveData.contains(set1){

                    } else {
                    SaveData.append(set1)
                        SetTIME.append(set1)

                if let set2 = (result as AnyObject).value(forKey: "set2") as? String
                {
                    SaveData.append(set2)
                }
                if let set3 = (result as AnyObject).value(forKey: "set3") as? String
                {
                    SaveData.append(set3)
                }
                if let set4 = (result as AnyObject).value(forKey: "set4") as? String
                {
                    SaveData.append(set4)
                        }
                    }
                }
            }
        }
    }
    catch{
        //ProcessErrors
    }


问:
CSS Help to see stars
I have looked around and have been unable to write a CSS code that is based on a 5 star rating system that will change based upon customer feedback. Any help is appreciated.</p>

答:
As peterthegreat mentioned, you might want to look into a javascript solution.

Example of a jquery plugin

Title: CSS Help to see stars


问:
Kotlin: For-loop range must have an 'iterator()' method
If I use var charSet = 1..10 it works, but when I am using the below code, I'm getting this error.

```<code>var charSet = "A".."Z"
for (value in charSet) {
  println("$value")
}
</code>```

For-loop range must have an 'iterator()' method.

Please let me know how to resolve this.

答: To declare a string, we use double quotes and to declare a character, we use single quotes. You can iterate through characters and not strings. When you change your quotes to single, your code will run perfectly. </p>

Body:
If I use var charSet = 1..10 it works, but when I am using the below code, I'm getting this error.

var charSet = "A".."Z"
for (value in charSet) {
  println("$value")
}

For-loop range must have an 'iterator()' method.

Please let me know how to resolve this.


问:
Mongodb cluster and reading from secondary when primary is down
This is not a basic question on just asking about mongo cluster. It is not a duplicate in my opinion
I have a mongodb 3 node cluster and my url is something along the following lines in a PlayFramework conf file

```<code>mongodb.uri = "mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj"
</code>```

By default when the replica is configured, all reads and writes are happening only on Primary and that is what I want. I however, want the reads to go to secondary when no primary is left, that is when 2 nodes go down, there will not be a primary left and only one secondary.

I do not want to modify my code to achieve this for each read query. I tried the following on the secondary node but it does not help

```<code>db.getMongo().setReadPref('primaryPreferred')
</code>```

What exactly do I need to do to make this work?

答:
I do not want to modify my code to achieve this for each read query. I tried the following on the secondary node but it does not help:

```<code>db.getMongo().setReadPref('primaryPreferred')
</code>```

You are on the right track with read preferences, but need to set this in your connection string or driver. Setting a read preference in the mongo shell only affects the current shell session, and has no effect on remote connections.

mongodb.uri = "mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj"

You need to add some additional parameters as per MongoDB's Connecting String URI Format:

(required) The replicaSet=... option indicates that the driver should use "replica set" connection mode as opposed to the default direct connection mode. This parameter enables replica set monitoring, read preferences, and discovery of topology changes. The provided replica set name must match the replica set name configured for your deployment. For full details on the connection behaviour expected for officially supported MongoDB Drivers, see the Server Discovery and Monitoring (SDAM) specification. The rationale section of the spec includes answers to common questions about the chosen approach.

(required) The readPreference=primaryPreferred option indicates the preference to read from a primary but use a secondary if there is no primary available.

(optional) In MongoDB 3.4+ you can specify a maxStalenessSeconds=... option which limits the maximum replication lag (or staleness) when using a secondary read preference. By default there is no max staleness so the driver will not consider replication lag when selecting a secondary based on read preference. If your intent is to use primaryPreferred as a failover option for reads I would set max staleness with caution: you need to ensure that you have at least one secondary which has acceptable staleness.

So, assuming a replica set name of mongocluster and database of myproj the suggested connection string would be:

```<code>mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj?replicaSet=mongocluster&readPreference=primaryPreferred
</code>```

Body:
This is not a basic question on just asking about mongo cluster. It is not a duplicate in my opinion
I have a mongodb 3 node cluster and my url is something along the following lines in a PlayFramework conf file

mongodb.uri = "mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj"

By default when the replica is configured, all reads and writes are happening only on Primary and that is what I want. I however, want the reads to go to secondary when no primary is left, that is when 2 nodes go down, there will not be a primary left and only one secondary.

I do not want to modify my code to achieve this for each read query. I tried the following on the secondary node but it does not help

db.getMongo().setReadPref('primaryPreferred')

What exactly do I need to do to make this work?

Body:
I do not want to modify my code to achieve this for each read query. I tried the following on the secondary node but it does not help:

db.getMongo().setReadPref('primaryPreferred')

You are on the right track with read preferences, but need to set this in your connection string or driver. Setting a read preference in the mongo shell only affects the current shell session, and has no effect on remote connections.

mongodb.uri = "mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj"

You need to add some additional parameters as per MongoDB's Connecting String URI Format:

(required) The replicaSet=... option indicates that the driver should use "replica set" connection mode as opposed to the default direct connection mode. This parameter enables replica set monitoring, read preferences, and discovery of topology changes. The provided replica set name must match the replica set name configured for your deployment. For full details on the connection behaviour expected for officially supported MongoDB Drivers, see the Server Discovery and Monitoring (SDAM) specification. The rationale section of the spec includes answers to common questions about the chosen approach.

(required) The readPreference=primaryPreferred option indicates the preference to read from a primary but use a secondary if there is no primary available.

(optional) In MongoDB 3.4+ you can specify a maxStalenessSeconds=... option which limits the maximum replication lag (or staleness) when using a secondary read preference. By default there is no max staleness so the driver will not consider replication lag when selecting a secondary based on read preference. If your intent is to use primaryPreferred as a failover option for reads I would set max staleness with caution: you need to ensure that you have at least one secondary which has acceptable staleness.

So, assuming a replica set name of mongocluster and database of myproj the suggested connection string would be:

mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj?replicaSet=mongocluster&readPreference=primaryPreferred


问:
How to use new geckodriver endpoints?
The new geckodriver v0.17.0 has a new way to install addons as mentioned here:

```<code>POST /session/{session id}/window/fullscreen to invoke the window manager-specific full screen operation
POST /session/{session id}/moz/addon/install to install an extension [Gecko only]
POST /session/{session id}/moz/addon/uninstall to uninstall an extension [Gecko only]
</code>```

How can I use these endpoints to install my addon to firefox for my selenium tests?

答:
You have to know the ip and port in which geckodriver starts. And Once the geckodriver started you can get the Session Id from the driver Instance.

You can get the Ip Address and Port as mentioned here

For ex: if the ip and port is

localhost:15874

and session id is 1e53412a-05eb-40a9-8a7b-bb8dd6fd75ab

Then you can post a json message to

```<code>http://localhost:15874/session/1e53412a-05eb-40a9-8a7b-bb8dd6fd75ab/moz/addon/install
</code>```

The body of post message should be

```<code>{
    "path":"xxyy.xpi",
    "temporary":true
}
</code>```

Title: How to use new geckodriver endpoints?

Body:
The new geckodriver v0.17.0 has a new way to install addons as mentioned here:

POST /session/{session id}/window/fullscreen to invoke the window manager-specific full screen operation
POST /session/{session id}/moz/addon/install to install an extension [Gecko only]
POST /session/{session id}/moz/addon/uninstall to uninstall an extension [Gecko only]

How can I use these endpoints to install my addon to firefox for my selenium tests?

Body:
You have to know the ip and port in which geckodriver starts. And Once the geckodriver started you can get the Session Id from the driver Instance.

You can get the Ip Address and Port as mentioned here

For ex: if the ip and port is

localhost:15874

and session id is 1e53412a-05eb-40a9-8a7b-bb8dd6fd75ab

Then you can post a json message to

http://localhost:15874/session/1e53412a-05eb-40a9-8a7b-bb8dd6fd75ab/moz/addon/install

The body of post message should be

{
    "path":"xxyy.xpi",
    "temporary":true
}


问:
Textbox compulsory when radio button is selected
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button. When yes radiobutton is clicked. the quantity textbox should not be empty. But it can be empty if no radiobutton is clicked.
This functionality should work when submit button is clicked with yes radiobutton is selected.

```<code> <HTML>
    <head>
    radio
    </head>
    <body>
    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>
</body>
<div>
<script src="~/Scripts/radiobuttonvalidation.js"></script>
</div>
</html>
</code>```

I'm new to mvc and javascript. Please help me with javascript code too, and the way i should link it with my view. Javascript:

```<code>function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}
</code>```

答:
you need to add validation for text box is empty or not

function validate(_this) {
  if ($(_this).attr('id') == "yes") {
    if (!$('#dir').val().trim()) {
      $('#dir').attr('required');
      console.log("Text Box  required");
    }
  } else {
    $('#dir').removeAttr('required');
    console.log("Text Box not required");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=radio>
  Add to electronic <input type="radio" name="yes" onclick="validate(this)" id="yes" />Yes<input type="radio" name="yes" id="no" />No<br />
  <label>Quantity</label><input type="text" size="25" name="dir" id="dir" required/>
  <button type=submit name=insert>insert</button>
</form></code>```

Body:
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button. When yes radiobutton is clicked. the quantity textbox should not be empty. But it can be empty if no radiobutton is clicked.
This functionality should work when submit button is clicked with yes radiobutton is selected.

    radio

    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No

    Quantity<input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>

I'm new to mvc and javascript. Please help me with javascript code too, and the way i should link it with my view. Javascript:

function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}

Body:
you need to add validation for text box is empty or not

function validate(_this) {
  if ($(_this).attr('id') == "yes") {
    if (!$('#dir').val().trim()) {
      $('#dir').attr('required');
      console.log("Text Box  required");
    }
  } else {
    $('#dir').removeAttr('required');
    console.log("Text Box not required");
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=radio>
  Add to electronic <input type="radio" name="yes" onclick="validate(this)" id="yes" />Yes<input type="radio" name="yes" id="no" />No<br />
  <label>Quantity</label><input type="text" size="25" name="dir" id="dir" required/>
  <button type=submit name=insert>insert</button>
</form>


答:
Typo: onclick="validate(_this)  this should be onclick="validate(this)"

function validate(_this) {

    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir"/>
<button type=submit name=insert>insert</button>
</body></code>```

Title: Textbox compulsory when radio button is selected

Body:
Typo: onclick="validate(_this)  this should be onclick="validate(this)"

function validate(_this) {

    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir"/>
<button type=submit name=insert>insert</button>
</body>


答:
You can use  implode() php function to make an array to string

Just like this

```<code>$array=['id'=>12,'no'=>1234]
$String = implode(", ", $array);//it give o/p as "12,1234"
</code>```

Or if you want array with no key value then you can use array_values()
Just like this

```<code>$array=array_values($array);//it give o/p as [12,1234]
</code>```

Title: How to remove key from an array in php

Body:
You can use  implode() php function to make an array to string

Just like this

$array=['id'=>12,'no'=>1234]
$String = implode(", ", $array);//it give o/p as "12,1234"

Or if you want array with no key value then you can use array_values()
Just like this

$array=array_values($array);//it give o/p as [12,1234]


问:
change bgcolor in html table depending on client input
I have seen a number of similar questions but none that appear to answer what I am trying to do.

In a form on page 1 the following three pieces of information will be entered for a measurement, (1)upper limit, (2)lower limit and (3)measured value.

The user will then click on a button taking them to page 2 where the entered information will be uploaded to a mysql data base, this all works well. On page 2 the entered information will be displayed confirming what has been uploaded to the data base. This information is displayed in a html table.

I wish to change the bgcolor of the cell where the measured value is displayed to RED if not a value that is between (1) upper limit or (2) lower limit .

The three pieces of information entered by the user can and will change every time.

Can this be done simply ?

答:
You are already displaying the information on 2nd page in HTML table . Assuming the variables are $upper_limit, $lower_limit and $measured, you can add a check and use bgcolor as a variable as below:

```<code><?php
$bg = ($measured<$lower_limit || $measured>$upper_limit) ? 'bgcolor="red"' : '';
?>

<table>
    <tr>
        <td <?php echo $bg;?>>
             <?php echo $measured; ?>
        </td>
    </tr>
</table>
</code>```

Body:
You are already displaying the information on 2nd page in HTML table . Assuming the variables are $upper_limit, $lower_limit and $measured, you can add a check and use bgcolor as a variable as below:

<?php
$bg = ($measured<$lower_limit || $measured>$upper_limit) ? 'bgcolor="red"' : '';
?>

<table>
    <tr>
        <td <?php echo $bg;?>>
             <?php echo $measured; ?>
        </td>
    </tr>
</table>


问:
About ![CDATA[, what is it?

Possible Duplicate:

  what is the meaning of CDATA

What is, and when is used the ![CDATA[ string/variable/constant? (I don't know what is it)

答:
It is a way to escape large sections of text in XML documents.

From wikipedia:

In an XML document or external parsed entity, a CDATA section is a section of element content that is marked for the parser to interpret as only character data, not markup.

By the way, it is <![CDATA[]]>, not ![CDATA[]].

Title: About ![CDATA[, what is it?


问:
Error while installing ClickHouse DB Ubuntu 16.04 (64 bit)
I followed this link to install ClickHouse DB: https://clickhouse.yandex/#quick-start

I got an error while running this command: sudo apt-get install clickhouse-server-common clickhouse-client -y

Error:

Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
clickhouse-client : Depends: clickhouse-server-base (= 1.1.54236) but it is not going to be installed clickhouse-server-common : Depends: clickhouse-server-base (= 1.1.54236) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

答:
try use following commands</p>

```<code>apt-get purge -y clickhouse*
apt-get install -y clickhouse-server-common
apt-get install -y clickhouse-client
</code>```

Body:
try use following commands

apt-get purge -y clickhouse*
apt-get install -y clickhouse-server-common
apt-get install -y clickhouse-client


问:
How to make sure the QApplication and its QThreads are all closed
The code below creates a single QDialog which starts a QThread that gets a function that is long to calculate. QDialog's closeEvent() method was modified to terminate the thread that was started.

How to make sure the thread is terminated only if it completed a task it was working on? What is the difference between stopping a thread with its quit() and its terminate() method? Should the thread always be terminated before the main application window is closed? Why on Mac OS X the Python process remains to be listed in Activity Monitor even after the main dialog is closed and the thread is terminated?

```<code>import threading
import Queue as Queue
import datetime

global queue
queue = Queue.Queue()

class Thread(QThread):
    def __init__(self, queue, parent):
        QThread.__init__(self, parent)
        self.queue = queue

    def run(self):
        while True:
            task = queue.get()
            output = task()
            queue.task_done()

def longToCalculate():
    for i in range(30000000):
        i += i
        if not i % 100000:
            print '%s ...still calculating ' % datetime.datetime.now()
    print 'calculation completed'
    return i

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

    def closeEvent(self, event):
        # self.thread.quit()
        self.thread.terminate()
        event.accept()

class Dialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.queue = Queue.Queue()
        self.thread = Thread(queue=self.queue, parent=self)
        self.thread.start()
        queue.put(longToCalculate)

if __name__ == '__main__':
    app = QApplication([])
    dialog = Dialog()
    dialog.show()
    qApp.exec_()
</code>```

答:
Here is a sample code which does not include Queue.</p>

```<code>import os, sys
import datetime

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Thread( QThread ):
    def __init__( self, parent ):

        QThread.__init__( self, parent )

    def run( self ):
        self.longToCalculate()

    def longToCalculate( self ):
        for i in range( 30000000 ):
            i += i

            if ( i % 1000000 == 0 ):
                print( '%s ...still calculating' % QDateTime.currentDateTime().toString() )

        print( 'calculation completed' )
        return i

class Dialog(QDialog):
    def __init__( self, parent = None ):

        QDialog.__init__( self, parent )

        self.thread = Thread( parent = self )
        self.thread.start()

        self.thread.finished.connect( self.threadComplete )

    def threadComplete( self ) :
        QMessageBox.information( self, "Thread complete", "The thread has finished running. This program wil automatically close now." )
        self.close()

    def closeEvent( self, cEvent ) :

        if self.thread.isRunning() :
            QMessageBox.information( self, "Thread running", "The thread is running. You cannot close this program." )
            cEvent.ignore()

        else :
            cEvent.accept()

if __name__ == '__main__':

    app = QApplication( sys.argv )

    dialog = Dialog()
    dialog.show()

    qApp.exec_()
</code>```

Body:
The code below creates a single QDialog which starts a QThread that gets a function that is long to calculate. QDialog's closeEvent() method was modified to terminate the thread that was started.

How to make sure the thread is terminated only if it completed a task it was working on? What is the difference between stopping a thread with its quit() and its terminate() method? Should the thread always be terminated before the main application window is closed? Why on Mac OS X the Python process remains to be listed in Activity Monitor even after the main dialog is closed and the thread is terminated?

import threading
import Queue as Queue
import datetime

global queue
queue = Queue.Queue()

class Thread(QThread):
    def __init__(self, queue, parent):
        QThread.__init__(self, parent)
        self.queue = queue

    def run(self):
        while True:
            task = queue.get()
            output = task()
            queue.task_done()

def longToCalculate():
    for i in range(30000000):
        i += i
        if not i % 100000:
            print '%s ...still calculating ' % datetime.datetime.now()
    print 'calculation completed'
    return i

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

    def closeEvent(self, event):
        # self.thread.quit()
        self.thread.terminate()
        event.accept()

class Dialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.queue = Queue.Queue()
        self.thread = Thread(queue=self.queue, parent=self)
        self.thread.start()
        queue.put(longToCalculate)

if __name__ == '__main__':
    app = QApplication([])
    dialog = Dialog()
    dialog.show()
    qApp.exec_()

Body:
Here is a sample code which does not include Queue.

import os, sys
import datetime

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Thread( QThread ):
    def __init__( self, parent ):

        QThread.__init__( self, parent )

    def run( self ):
        self.longToCalculate()

    def longToCalculate( self ):
        for i in range( 30000000 ):
            i += i

            if ( i % 1000000 == 0 ):
                print( '%s ...still calculating' % QDateTime.currentDateTime().toString() )

        print( 'calculation completed' )
        return i

class Dialog(QDialog):
    def __init__( self, parent = None ):

        QDialog.__init__( self, parent )

        self.thread = Thread( parent = self )
        self.thread.start()

        self.thread.finished.connect( self.threadComplete )

    def threadComplete( self ) :
        QMessageBox.information( self, "Thread complete", "The thread has finished running. This program wil automatically close now." )
        self.close()

    def closeEvent( self, cEvent ) :

        if self.thread.isRunning() :
            QMessageBox.information( self, "Thread running", "The thread is running. You cannot close this program." )
            cEvent.ignore()

        else :
            cEvent.accept()

if __name__ == '__main__':

    app = QApplication( sys.argv )

    dialog = Dialog()
    dialog.show()

    qApp.exec_()


问:
Laravel 5 getting ID from URL
I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.

```<code>@foreach ($patients as $patient)
    <tr>
        <td>{{ $patient->pID }}</td>
        <td>{{ $patient->pName }}</td>
        <td>{{ $patient->pAddress }}</td>
        <td>{{ $patient->pBday }}</td>
        <td>{{ $patient->pPhone}}</td>
        <td>{{ $patient->pEcon }}</td>
        <td>{{ $patient->pDreg }}</td>
        <td></td>
        <td>
            <a href="{{ URL::to('visit/'.$patient->pID) }}">
                <img src="../images/viewvisit.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('addeditvisit/'.$patient->pID) }}">
                <img src="../images/visit.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('editpatient/'.$patient->pID) }}">
                <img src="../images/update.png" style="width:30px; height:30px;">
            </a>
        </td>
        <td>
            <a href="{{ URL::to('deletepatient/'.$patient->pID) }}">
                <img src="../images/delete.png" style="width:30px; height:30px;">
            </a>
        </td>
    </tr>
@endforeach
</code>```

what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.

I'm currently stuck with this controller function.

```<code>public function index(Request $request) {

    $doctors = Doctor::where('dStatus', 0)
        ->lists('dName', 'dID');
    $beds = Bed::where('bStatus', 0)
        ->lists('bName', 'bID');
    $patient = Patient::patient();
    // $uri = $request->path('patient');

    return View::make('pages.addeditvisit', [
        'doctors'=>$doctors,
        'beds'=>$beds,
        'patient'=>$patient->pID
    ]);
}
</code>```

答: Or just use it within Blade: {{ request()->route('id') }}

Title: Laravel 5 getting ID from URL

Body:
I have a table view in which I can click an button icon and redirect to another page carrying the id of the row that has been clicked.

@foreach ($patients as $patient)

        {{ $patient->pID }}
        {{ $patient->pName }}
        {{ $patient->pAddress }}
        {{ $patient->pBday }}
        {{ $patient->pPhone}}
        {{ $patient->pEcon }}
        {{ $patient->pDreg }}

            pID) }}">

            pID) }}">

            pID) }}">

            pID) }}">

@endforeach

what I want is to get the id from the URL and put it in a variable so that I can utilize it my other page.

I'm currently stuck with this controller function.

public function index(Request $request) {

    $doctors = Doctor::where('dStatus', 0)
        ->lists('dName', 'dID');
    $beds = Bed::where('bStatus', 0)
        ->lists('bName', 'bID');
    $patient = Patient::patient();
    // $uri = $request->path('patient');

    return View::make('pages.addeditvisit', [
        'doctors'=>$doctors,
        'beds'=>$beds,
        'patient'=>$patient->pID
    ]);
}


问:
CSS Copy and paste problem
I've developed a system in my application where emails are picked up with a regex, and then reversed in the source (to thwart bots). I then add the span class 'obfuscate email'. I then use CSS to reverse the the text back to be displayed and Javascript make sure that mailto: links still work.

I was pretty happy with my solution until I realised that copying and pasting the email puts it in the clipboard backwards. I was wondering if there was any way I could remedy this? I've been testing in Firefox 3 for OS X.

The page in question is available here: http://www.leaklocations.com.au/contact-us/

To see the problem, simply copy and paste the email on that site.

答: Why not use something like MailHide from the reCaptcha folks to hide email addresses instead?</p>

OwnerDisplayName: alex

Title: CSS Copy and paste problem

OwnerDisplayName: tvanfosson


问:
Entity framework MVC Brings all Tables with Data . How to avoid that ? Performance Issue
So i'm concerned about Entity framework perfomace issue, when creating object of my DB entity

QuizzrEntities conDb = new QuizzrEntities();
so 'conDb' brings all the data and tables from database which is not good.
any idea or you guys have tried not to bring all at once . ?

```<code>QuizzrEntities conDb = new QuizzrEntities();
            long LastInsertedUserId = 0,
                    UserSaveResponse = 0,
                 OrderUpdateReponse = 0;
            bool IsMobileNoExist = false;

            var UserMasterEntity = new UserMaster();
            {
                UserMasterEntity.Username = UserDetailInput.Username;
                UserMasterEntity.MobileNumber = UserDetailInput.MobileNumber;
                UserMasterEntity.WhenEntered = DateTime.UtcNow;
            };
            var checkIfMobileNoAlreadyExsist = conDb.UserMasters.Where(m => m.MobileNumber == UserDetailInput.MobileNumber).ToList();
            if (checkIfMobileNoAlreadyExsist.Count > 0)
            {
                IsMobileNoExist = true;
            }
            if (!IsMobileNoExist)
            {
                conDb.UserMasters.Add(UserMasterEntity);
                UserSaveResponse = conDb.SaveChanges();
                LastInsertedUserId = UserMasterEntity.UserId;
            }
</code>```

When i check the conDb it has sql queries includes of all table and with data .
Why entity framework bring all data at once from all tables ?
How do i avoid that?

答:
what do you want exactly Please share in brief.
if you want perticular table of data from database using entity object then you can use linq as follows

```<code>List<emp> data = (from e in conDb.emp select e).TOList();
</code>```

i m Considering that table name will be emp.you should enter your table name in place of emp

Body:
So i'm concerned about Entity framework perfomace issue, when creating object of my DB entity

QuizzrEntities conDb = new QuizzrEntities();
so 'conDb' brings all the data and tables from database which is not good.
any idea or you guys have tried not to bring all at once . ?

QuizzrEntities conDb = new QuizzrEntities();
            long LastInsertedUserId = 0,
                    UserSaveResponse = 0,
                 OrderUpdateReponse = 0;
            bool IsMobileNoExist = false;

            var UserMasterEntity = new UserMaster();
            {
                UserMasterEntity.Username = UserDetailInput.Username;
                UserMasterEntity.MobileNumber = UserDetailInput.MobileNumber;
                UserMasterEntity.WhenEntered = DateTime.UtcNow;
            };
            var checkIfMobileNoAlreadyExsist = conDb.UserMasters.Where(m => m.MobileNumber == UserDetailInput.MobileNumber).ToList();
            if (checkIfMobileNoAlreadyExsist.Count > 0)
            {
                IsMobileNoExist = true;
            }
            if (!IsMobileNoExist)
            {
                conDb.UserMasters.Add(UserMasterEntity);
                UserSaveResponse = conDb.SaveChanges();
                LastInsertedUserId = UserMasterEntity.UserId;
            }

When i check the conDb it has sql queries includes of all table and with data .
Why entity framework bring all data at once from all tables ?
How do i avoid that?

Body:
what do you want exactly Please share in brief.
if you want perticular table of data from database using entity object then you can use linq as follows

List<emp> data = (from e in conDb.emp select e).TOList();

i m Considering that table name will be emp.you should enter your table name in place of emp


问:
FIlter collection_select by value in coffeescript
Well I have this coffeeScript:

```<code>jQuery ->
    $('#cmbPab').change ->
       ubis = $('#cmbUbi').html()
       pabellon = $(this).val()
       options = $('#cmbUbi').filter("FilterByValue")
</code>```

I want it to filter options by value, I already saw railcats stuff but he filters by a different way and I need to do it by value cause value is my id

Here is the cod of both collection_select where cmbPab is my main combo:

```<code>        <div class="form-group">
         <%= f.label :Pabellon %>
         <%= f.collection_select :idubicacion, Mtopabellon.all,
             :codpabellon, :nombre, {prompt: 'Seleccione un pabellón'},
             :class=>'form-control', :id => 'cmbPab'%>
        </div>

        <div class="form-group">
          <%= f.label :Ubicacion %>
          <%= f.collection_select :idubicacion, CrUbicacion.all, :id,
          :nombre, {prompt: 'Seleccione una ubicación'}, :class=>'form-
          control', :id => 'cmbUbi'  %>
        </div>
</code>```

答:
I believe you're after something along these lines:

```<code>$('#cmbPab').change ->
  displayFilterFn = (i, el) -> $(el).val() == 'something?' // do your filtering
  $ubis = $('#cmbUbi')
  $ubis.children().hide()
  $ubis.children().filter(displayFilterFn).show()
</code>```

Without knowing the specifics of how you want to filter your options, other than that it is based on the value, I can't provide you a filtering function implementation (displayFilterFn above). The basic idea is to first hide all options, and then show the ones that match your filter.

For more info on the .filter(), see the jQuery API Documentation.

Body:
Well I have this coffeeScript:

jQuery ->
    $('#cmbPab').change ->
       ubis = $('#cmbUbi').html()
       pabellon = $(this).val()
       options = $('#cmbUbi').filter("FilterByValue")

I want it to filter options by value, I already saw railcats stuff but he filters by a different way and I need to do it by value cause value is my id

Here is the cod of both collection_select where cmbPab is my main combo:

         <%= f.label :Pabellon %>
         <%= f.collection_select :idubicacion, Mtopabellon.all,
             :codpabellon, :nombre, {prompt: 'Seleccione un pabellón'},
             :class=>'form-control', :id => 'cmbPab'%>

          <%= f.label :Ubicacion %>
          <%= f.collection_select :idubicacion, CrUbicacion.all, :id,
          :nombre, {prompt: 'Seleccione una ubicación'}, :class=>'form-
          control', :id => 'cmbUbi'  %>

Body:
I believe you're after something along these lines:

$('#cmbPab').change ->
  displayFilterFn = (i, el) -> $(el).val() == 'something?' // do your filtering
  $ubis = $('#cmbUbi')
  $ubis.children().hide()
  $ubis.children().filter(displayFilterFn).show()

Without knowing the specifics of how you want to filter your options, other than that it is based on the value, I can't provide you a filtering function implementation (displayFilterFn above). The basic idea is to first hide all options, and then show the ones that match your filter.

For more info on the .filter(), see the jQuery API Documentation.