问:
Serializing DbCommand with Newtonsoft.Json
I am trying to serialize Entity Framework DbCommand to json with Newtonsoft.Json:

```<code>public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) {
   var path = "C:/result.json";
   File.WriteAllText(path, JsonConvert.SerializeObject(command));
}
</code>```

However, in result json file the parameters are ToString() values rather than objects:

```<code>"Parameters": ["@0", "@1", "@2"]
</code>```

How do I tell the serializer to serialize the whole objects?

答:
You can log the actual values using a custom JsonConverter.

First, the sample query:

```<code>using (var context = new SchoolDbContext("dbConnectionString"))
{
     var id = 11;
     var dni = 36170503;
     var sql = @"SELECT name FROM dbo.students WHERE Id = {0} OR Dni = {1}";
     context.Database.ExecuteSqlCommand(sql, id, dni);
}
</code>```

Then, add a custom EF interceptor as follows:

```<code>public class MyDBConfiguration : DbConfiguration
{
    public MyDBConfiguration()
    {
        DbInterception.Add(new EntityFrameworkInterceptor());
    }
}

public class EntityFrameworkInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        var path = @"C:\Users\miparnisari\Documents\log.json";
        var serialized = JsonConvert.SerializeObject(command, new DbCommandSerializer());
        File.WriteAllText(path, serialized);
    }
}
</code>```

Finally, the serializer:

```<code>public class DbCommandSerializer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dbCommand = value as DbCommand;
        writer.Formatting = Formatting.Indented;
        writer.WriteStartObject();
        writer.WritePropertyName("Query");
        writer.WriteValue(dbCommand.CommandText);
        writer.WritePropertyName("Parameters");
        writer.WriteStartObject();
        foreach (DbParameter param in dbCommand.Parameters)
        {
            writer.WritePropertyName(param.ParameterName);
            writer.WriteValue(param.Value);
        }

        writer.WriteEndObject();
        writer.WriteEndObject();
        writer.Flush();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(DbCommand).IsAssignableFrom(objectType);
    }
}
</code>```

This logs:

```<code>{
  "Query": "SELECT name FROM dbo.students WHERE Id = @p0 OR Dni = @p1",
  "Parameters": {
    "p0": 11,
    "p1": 36170503
  }
}
</code>```

Body:
I am trying to serialize Entity Framework DbCommand to json with Newtonsoft.Json:

public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) {
   var path = "C:/result.json";
   File.WriteAllText(path, JsonConvert.SerializeObject(command));
}

However, in result json file the parameters are ToString() values rather than objects:

"Parameters": ["@0", "@1", "@2"]

How do I tell the serializer to serialize the whole objects?

Body:
You can log the actual values using a custom JsonConverter.

First, the sample query:

using (var context = new SchoolDbContext("dbConnectionString"))
{
     var id = 11;
     var dni = 36170503;
     var sql = @"SELECT name FROM dbo.students WHERE Id = {0} OR Dni = {1}";
     context.Database.ExecuteSqlCommand(sql, id, dni);
}

Then, add a custom EF interceptor as follows:

public class MyDBConfiguration : DbConfiguration
{
    public MyDBConfiguration()
    {
        DbInterception.Add(new EntityFrameworkInterceptor());
    }
}

public class EntityFrameworkInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        var path = @"C:\Users\miparnisari\Documents\log.json";
        var serialized = JsonConvert.SerializeObject(command, new DbCommandSerializer());
        File.WriteAllText(path, serialized);
    }
}

Finally, the serializer:

public class DbCommandSerializer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dbCommand = value as DbCommand;
        writer.Formatting = Formatting.Indented;
        writer.WriteStartObject();
        writer.WritePropertyName("Query");
        writer.WriteValue(dbCommand.CommandText);
        writer.WritePropertyName("Parameters");
        writer.WriteStartObject();
        foreach (DbParameter param in dbCommand.Parameters)
        {
            writer.WritePropertyName(param.ParameterName);
            writer.WriteValue(param.Value);
        }

        writer.WriteEndObject();
        writer.WriteEndObject();
        writer.Flush();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(DbCommand).IsAssignableFrom(objectType);
    }
}

This logs:

{
  "Query": "SELECT name FROM dbo.students WHERE Id = @p0 OR Dni = @p1",
  "Parameters": {
    "p0": 11,
    "p1": 36170503
  }
}


来源: stackexchange

问:
Python Create a List file and write query
so sorry for my question if it seems so easy but I am newbie user of python and I can not find a way to solve it.

I have a "dish.py" file which includes some sub-lists

```<code>Fruits={"Ap":Apple
        "Br":Black Mulberry
        "Ch":Black Cherry
        }
Meals={"BN":Bean
        "MT":Meat
        "VG":Vegetable
        }
Legumes={"LN":Green Lentil
        "P": Pea
        "PN":Runner Peanut
        }
</code>```

I want to impelement the dish.py file in a code that at the end, I want to create a query inside of the file

```<code>with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
           content = dish.read()
print dish.closed
dm=dict([dish])
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x=str(raw_input("Enter word:"))
   if x in dm:
        print dm[x]
    elif x[0]==("P"):
        nl.append(x)
        print .join( nl)
</code>```

It may be look so messy but

dm=dict([dish]) I want to create a dictionary for query

nl=[x for x in dm if x[0]=='P'] I want to write words begin with "P" letter

Here is my questions:

1. Q: I suppose there is a problem with my dish.py file. How can I reorganize it?

2. Q: How can I apply a query to the file and extract the words begin with "P"
Thank you so much in advance

答:
So I think you have more than these two issues/questions.
First, if you want to include 'hardcoded' lists, dicts and such, you probably want to include dish with dish.py being in your working directory.

That is, if your data structures in the python file are actually in the correct form:

```<code>Fruits={"Ap":'Apple',
        "Br":'Black Mulberry',
        "Ch":'Black Cherry'
        }
Meals={"BN":'Bean',
        "MT":'Meat',
        "VG":'Vegetable'
        }
Legumes={"LN":'Green Lentil',
        "P":'Pea',
        "PN":'Runner Peanut'
        }
</code>```

Finally, you can search in all the datastructures that were named and included in the file, under the created namespace of the include (which is dish).

```<code>for f in [dish.Fruits,dish.Meals,dish.Legumes]:
  for k,v in f.items():
    if k.startswith('P'):
      print k,v
</code>```

Also interesting for you might be pickling (though there are some caveats).

ContentLicense: CC BY-SA 3.0

Body:
so sorry for my question if it seems so easy but I am newbie user of python and I can not find a way to solve it.

I have a "dish.py" file which includes some sub-lists

Fruits={"Ap":Apple
        "Br":Black Mulberry
        "Ch":Black Cherry
        }
Meals={"BN":Bean
        "MT":Meat
        "VG":Vegetable
        }
Legumes={"LN":Green Lentil
        "P": Pea
        "PN":Runner Peanut
        }

I want to impelement the dish.py file in a code that at the end, I want to create a query inside of the file

with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
           content = dish.read()
print dish.closed
dm=dict([dish])
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x=str(raw_input("Enter word:"))
   if x in dm:
        print dm[x]
    elif x[0]==("P"):
        nl.append(x)
        print .join( nl)

It may be look so messy but

dm=dict([dish]) I want to create a dictionary for query

nl=[x for x in dm if x[0]=='P'] I want to write words begin with "P" letter

Here is my questions:

1. Q: I suppose there is a problem with my dish.py file. How can I reorganize it?

2. Q: How can I apply a query to the file and extract the words begin with "P"
Thank you so much in advance

Body:
So I think you have more than these two issues/questions.
First, if you want to include 'hardcoded' lists, dicts and such, you probably want to include dish with dish.py being in your working directory.

That is, if your data structures in the python file are actually in the correct form:

Fruits={"Ap":'Apple',
        "Br":'Black Mulberry',
        "Ch":'Black Cherry'
        }
Meals={"BN":'Bean',
        "MT":'Meat',
        "VG":'Vegetable'
        }
Legumes={"LN":'Green Lentil',
        "P":'Pea',
        "PN":'Runner Peanut'
        }

Finally, you can search in all the datastructures that were named and included in the file, under the created namespace of the include (which is dish).

for f in [dish.Fruits,dish.Meals,dish.Legumes]:
  for k,v in f.items():
    if k.startswith('P'):
      print k,v

Also interesting for you might be pickling (though there are some caveats).


问:
checking the input type in C
I want to check if my input is an integer (and not a char or string for example).
I stumbled across this code (that works):

```<code>#include <stdio.h>

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}
</code>```

Can someone please explain why it works?

答:
this statement:

```<code>scanf("%f",&a);
</code>```

can tell you what you want to know.

When calling any of the scanf() family of functions: Always check the returned value (not the parameter values) to assure the operation was successful.

In this case suggest:

```<code>if( 1 != scanf("%f",&a) )
{ // non digit entered
    ....
}
</code>```

Title: checking the input type in C

Body:
I want to check if my input is an integer (and not a char or string for example).
I stumbled across this code (that works):

#include <stdio.h>

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}

Can someone please explain why it works?

Body:
this statement:

scanf("%f",&a);

can tell you what you want to know.

When calling any of the scanf() family of functions: Always check the returned value (not the parameter values) to assure the operation was successful.

In this case suggest:

if( 1 != scanf("%f",&a) )
{ // non digit entered
    ....
}


问:
JFileChooser: Cannot select Desktop when Selection Mode is File and Directories
I ran into an issue with JFileChooser and wanted to see if there is a workaround.

If the JFileChooser is created and the setFileSelectionMode is FILES_AND_DIRECTORIES, when a user clicks a shortcut button on the left (in XP) such as Desktop or My Documents or drop down to Desktop, the field is not placed in the File Name JTextPane. And when clicking the "Select/Accept" button, nothing happens (because isDirectorySelected() returns false for some reason).

Overriding the approveSeletion does not work because the Event Handler function in BasicFileChooser does not call it.

How would I make it so the Desktop can be selected without having to navigate to it manually, but by clicking the shortcut on the left?

Thanks

答:
In Windows, the desktop is not backed by any file in the file system - it's a shell namespace.  So there really isn't anything that JFileChooser could return to you.  Yes, I know that there is a folder that contains the desktop for the user - but remember that the desktop actually displays as a composite of the user's desktop and the All Users desktop folder - plus other things that are added by the shell but not part of any folder (like the trash bin).  So returning a File object that represents the 'desktop' is pretty much a non-starter.

Long and short:  Ask yourself why you need to do this - chances are that you are going to wind up deep into native code territory, dealing with namespace PIDLs and all sorts of nastiness that you may not want to get into (for the life of me, I cannot understand why M$ had to make this stuff so amazingly difficult to use)...

Here's an intro to Windows shell namespaces so you'll have a feel for what's involved:

http://msdn.microsoft.com/en-us/library/cc144090%28v=vs.85%29.aspx

ContentLicense: CC BY-SA 2.5


问:
Combining CustomBusinessDay and BusinessHour Classes in Pandas
I've recently started using Pandas and found the CustomBusinessDay  and BusinessHour class to be very useful for doing calendar-math while accounting for specific business rules. However, I was wondering if was possible to combine them to calculate timedeltas that respect both classes.

For example, I would like to add n business hours to a start time and have it skip both the "off-hours" defined by the BusinessHour class and as well as all hours in "off-days" defined in the CustomBusinessDay class.

Does anyone with more experience with this library know if this can be easily accomplished or, if not, have a suggestion for how this functionality might be encapsulated in another class?

答:
Starting from version 0.18.1, you can use CustomBusinessHour:

The CustomBusinessHour is a mixture of BusinessHour and
  CustomBusinessDay which allows you to specify arbitrary holidays. For
  details, see Custom Business Hour (GH11514)

```<code>In [1]: from pandas.tseries.offsets import CustomBusinessHour

In [2]: from pandas.tseries.holiday import USFederalHolidayCalendar

In [3]: bhour_us = CustomBusinessHour(calendar=USFederalHolidayCalendar())
Friday before MLK Day

In [4]: dt = datetime(2014, 1, 17, 15)

In [5]: dt + bhour_us
Out[5]: Timestamp('2014-01-17 16:00:00')
Tuesday after MLK Day (Monday is skipped because it’s a holiday)

In [6]: dt + bhour_us * 2
Out[6]: Timestamp('2014-01-21 09:00:00')
</code>```

An example that I am using is

```<code>from pandas.tseries.offsets import CustomBusinessHour
from pandas.tseries.holiday import Holiday, AbstractHolidayCalendar

class MyCalendar(AbstractHolidayCalendar):
    rules = [Holiday('my birthday', month=6, day=6)]

cbh = CustomBusinessHour(2, start='10:00', end='16:00', calendar=MyCalendar())

pd.date_range('20170602', periods=20, freq=cbh)

Out:
DatetimeIndex(['2017-06-02 10:00:00', '2017-06-02 12:00:00',
               '2017-06-02 14:00:00', '2017-06-05 10:00:00',
               '2017-06-05 12:00:00', '2017-06-05 14:00:00',
               '2017-06-07 10:00:00', '2017-06-07 12:00:00',
               '2017-06-07 14:00:00', '2017-06-08 10:00:00',
               '2017-06-08 12:00:00', '2017-06-08 14:00:00',
               '2017-06-09 10:00:00', '2017-06-09 12:00:00',
               '2017-06-09 14:00:00', '2017-06-12 10:00:00',
               '2017-06-12 12:00:00'],
              dtype='datetime64[ns]', freq='2CBH')
</code>```

Body:
Starting from version 0.18.1, you can use CustomBusinessHour:

The CustomBusinessHour is a mixture of BusinessHour and
  CustomBusinessDay which allows you to specify arbitrary holidays. For
  details, see Custom Business Hour (GH11514)

In [1]: from pandas.tseries.offsets import CustomBusinessHour

In [2]: from pandas.tseries.holiday import USFederalHolidayCalendar

In [3]: bhour_us = CustomBusinessHour(calendar=USFederalHolidayCalendar())
Friday before MLK Day

In [4]: dt = datetime(2014, 1, 17, 15)

In [5]: dt + bhour_us
Out[5]: Timestamp('2014-01-17 16:00:00')
Tuesday after MLK Day (Monday is skipped because it’s a holiday)

In [6]: dt + bhour_us * 2
Out[6]: Timestamp('2014-01-21 09:00:00')

An example that I am using is

from pandas.tseries.offsets import CustomBusinessHour
from pandas.tseries.holiday import Holiday, AbstractHolidayCalendar

class MyCalendar(AbstractHolidayCalendar):
    rules = [Holiday('my birthday', month=6, day=6)]

cbh = CustomBusinessHour(2, start='10:00', end='16:00', calendar=MyCalendar())

pd.date_range('20170602', periods=20, freq=cbh)

Out:
DatetimeIndex(['2017-06-02 10:00:00', '2017-06-02 12:00:00',
               '2017-06-02 14:00:00', '2017-06-05 10:00:00',
               '2017-06-05 12:00:00', '2017-06-05 14:00:00',
               '2017-06-07 10:00:00', '2017-06-07 12:00:00',
               '2017-06-07 14:00:00', '2017-06-08 10:00:00',
               '2017-06-08 12:00:00', '2017-06-08 14:00:00',
               '2017-06-09 10:00:00', '2017-06-09 12:00:00',
               '2017-06-09 14:00:00', '2017-06-12 10:00:00',
               '2017-06-12 12:00:00'],
              dtype='datetime64[ns]', freq='2CBH')


问:
Value registerAsTable is not a member of org.apache.spark.rdd.RDD[Tweet]
I am trying to extract twitter data using rest API in zeppelin. Tried both option registerAsTable and registerTempTable, both ways are not working. Please help me to resolve the error. Getting below error while executing zeppelin Tutorial Code:

error: value registerAsTable is not a member of org.apache.spark.rdd.RDD[Tweet] ).foreachRDD(rdd=> rdd.registerAsTable("tweets")

答:
```<code>val data = sc.textFile("/FileStore/tables/uy43p2971496606385819/testweet.json");
</code>```

<p>//convert RDD to DF </p>

```<code>val inputs= data.toDF();
inputs.createOrReplaceTempView("tweets");
</code>```

Body:
val data = sc.textFile("/FileStore/tables/uy43p2971496606385819/testweet.json");

//convert RDD to DF

val inputs= data.toDF();
inputs.createOrReplaceTempView("tweets");


问:
How to use Cmake for OpenGL + Qt 5.8 in OS X Sierra?
I just tried to setup CMake for a project using Qt 5.8 to do OpenGL stuff in OS X Sierra. Here you can see my main CMakeLists

```<code>cmake_minimum_required (VERSION 3.8)

set (PROJECT_NAME "FluidEngine")
project (${PROJECT_NAME})

set (CMAKE_PREFIX_PATH "/Users/BRabbit27/Qt/5.8/clang_64")
set (CMAKE_AUTOMOC ON)
find_package (Qt5Widgets)
find_package (Qt5Gui)
find_package (Qt5OpenGL)

set (CPP_SOURCES "")
set (HPP_SOURCES "")
set (INCLUDE_PATHS "")
add_subdirectory (src)

include_directories (${INCLUDE_PATHS} ${OPENGL_INCLUDE_DIRS})

add_executable (${PROJECT_NAME} ${CPP_SOURCES} ${HPP_SOURCES})
target_link_libraries (${PROJECT_NAME} Qt5::Widgets Qt5::Gui Qt5::OpenGL )
</code>```

It perfectly configures the xcode project, no errors.
Then my code for rendering a basic triangle looks like:

```<code>GLWindow::GLWindow(QWidget* parent) : QOpenGLWidget(parent)
{}

void GLWindow::initializeGL()
{
    initializeOpenGLFunctions();

    GLfloat verts[] =
    {
      0.f, 1.f,
     -1.f, -1.f,
      1.f, -1.f
    };

    GLuint myBufferID;
    glGenBuffers(1, &myBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, myBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
}

void GLWindow::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);
}

void GLWindow::paintGL()
{
    glDrawArrays(GL_TRIANGLES, 0, 3);
}
</code>```

And what I get is a black window. I got this code from this video tutorial

Am I missing something in my cmake file or something subtle in OS X to use OpenGL? Since OS X is now promoting Metal, perhaps something must be enabled but I do not know what.

I already tried setting the version of OpenGL used in the main function

```<code>int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    QSurfaceFormat format;
    format.setVersion(4, 1);
    format.setProfile(QSurfaceFormat::CoreProfile);
    QSurfaceFormat::setDefaultFormat(format);

    GLWindow glwindow;
    glwindow.show();

    return app.exec();
}
</code>```

Any idea?

UPDATE

Added project to github, you can clone it here to test in your machine.

The way I build the project is just cmake -GXcode .. assuming i'm in /path/to/project/build_xcode directory.

Hope this can help you reproduce and perhaps give me a clue on what I could be doing wrong.

答:
I checked all the error messages and from there make my way to found the solution. Fortunately someone already replied in SO with a related problem and had a solution to the problem. You can find the complete answer here OpenGL: INVALID_OPERATION following glEnableVertexAttribArray

For short

You're seeing this error on OS X because it only supports the OpenGL
  Core Profile if you're using OpenGL 3.x or higher. Your code is not
  Core Profile compliant. You were most likely using the Compatibility
  Profile on Windows.

Specifically, the Core Profile requires a Vertex Array Object (VAO) to
  be bound for all vertex related calls. So before calling
  glEnableVertexAttribArray(), or other similar functions, you will
  need to create and bind a VAO.

Body:
I just tried to setup CMake for a project using Qt 5.8 to do OpenGL stuff in OS X Sierra. Here you can see my main CMakeLists

cmake_minimum_required (VERSION 3.8)

set (PROJECT_NAME "FluidEngine")
project (${PROJECT_NAME})

set (CMAKE_PREFIX_PATH "/Users/BRabbit27/Qt/5.8/clang_64")
set (CMAKE_AUTOMOC ON)
find_package (Qt5Widgets)
find_package (Qt5Gui)
find_package (Qt5OpenGL)

set (CPP_SOURCES "")
set (HPP_SOURCES "")
set (INCLUDE_PATHS "")
add_subdirectory (src)

include_directories (${INCLUDE_PATHS} ${OPENGL_INCLUDE_DIRS})

add_executable (${PROJECT_NAME} ${CPP_SOURCES} ${HPP_SOURCES})
target_link_libraries (${PROJECT_NAME} Qt5::Widgets Qt5::Gui Qt5::OpenGL )

It perfectly configures the xcode project, no errors.
Then my code for rendering a basic triangle looks like:

GLWindow::GLWindow(QWidget* parent) : QOpenGLWidget(parent)
{}

void GLWindow::initializeGL()
{
    initializeOpenGLFunctions();

    GLfloat verts[] =
    {
      0.f, 1.f,
     -1.f, -1.f,
      1.f, -1.f
    };

    GLuint myBufferID;
    glGenBuffers(1, &myBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, myBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
}

void GLWindow::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);
}

void GLWindow::paintGL()
{
    glDrawArrays(GL_TRIANGLES, 0, 3);
}

And what I get is a black window. I got this code from this video tutorial

Am I missing something in my cmake file or something subtle in OS X to use OpenGL? Since OS X is now promoting Metal, perhaps something must be enabled but I do not know what.

I already tried setting the version of OpenGL used in the main function

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    QSurfaceFormat format;
    format.setVersion(4, 1);
    format.setProfile(QSurfaceFormat::CoreProfile);
    QSurfaceFormat::setDefaultFormat(format);

    GLWindow glwindow;
    glwindow.show();

    return app.exec();
}

Any idea?

UPDATE

Added project to github, you can clone it here to test in your machine.

The way I build the project is just cmake -GXcode .. assuming i'm in /path/to/project/build_xcode directory.

Hope this can help you reproduce and perhaps give me a clue on what I could be doing wrong.


问:
Add-Migration results in InvalidOperationException error. What is the correct command?
I was doing the tutorial from this website and stuck halfway.

https://learn.microsoft.com/en-us/ef/core/get-started/uwp/getting-started

I was stuck at this line

Add-Migration MyFirstMigration

This are the errors that I get

System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

It seems this error has been going on for some time but so far, Microsoft hasnt respond with a fix.

What should I do?

答:
ApplicationDbContext.cs

```<code>    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=yorudbname.db");

    }

    //ONLY necessary if you needing to use Fluent API
    protected override void OnModelCreating(ModelBuilder mb)
    {
        base.OnModelCreating(mb);   //required reference comment - Order Matters as well.
                                    //ie has to be at the top.
</code>```

now you will need to 2 other piece data in your project.json 1) Design 2) Tools listed below.

project.json

```<code>    "dependencies": {
    "Microsoft.EntityFrameworkCore.Design": "1.1.1",   <<required
    "Microsoft.EntityFrameworkCore.Sqlite": "1.1.1",
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.3.1",  << must be 5.2.2 or higher
    "Microsoft.Xaml.Behaviors.Uwp.Managed": "2.0.0",
    "MvvmLight": "5.3.0",
    "Newtonsoft.Json": "10.0.2",
    "Unity": "4.0.1"
  },
  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.1" << required
</code>```

don't pay any attention to the versions in this example get the latest version available.

make sure all that is correctly placed and recompile, might even have to close project and reopen, commands should run then.

Body:
ApplicationDbContext.cs

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=yorudbname.db");

    }

    //ONLY necessary if you needing to use Fluent API
    protected override void OnModelCreating(ModelBuilder mb)
    {
        base.OnModelCreating(mb);   //required reference comment - Order Matters as well.
                                    //ie has to be at the top.

now you will need to 2 other piece data in your project.json 1) Design 2) Tools listed below.

project.json

    "dependencies": {
    "Microsoft.EntityFrameworkCore.Design": "1.1.1",   <<required
    "Microsoft.EntityFrameworkCore.Sqlite": "1.1.1",
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.3.1",  << must be 5.2.2 or higher
    "Microsoft.Xaml.Behaviors.Uwp.Managed": "2.0.0",
    "MvvmLight": "5.3.0",
    "Newtonsoft.Json": "10.0.2",
    "Unity": "4.0.1"
  },
  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.1" << required

don't pay any attention to the versions in this example get the latest version available.

make sure all that is correctly placed and recompile, might even have to close project and reopen, commands should run then.


问:
How to cut off int at the end of a line
I have a txt file similar to the following:

```<code>f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5
</code>```

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

```<code>f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end
</code>```

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

答:
Give something like this a shot:

```<code>content_ary.each do |content_str|
  segments_ary = content_str.split(':')
  integers_ary = segments_ary[1].strip.split(' ').map{|int_str| int_str.to_i}
  tags_ary = segments_ary[0].strip.split(',')
  case tags_ary[1].strip
  when "max"
    puts "max is here"
    puts "#{integers_ary}"
  when "sum"
    puts "sum is here"
    puts "#{integers_ary}"
  when "prod"
    puts "prod is here"
    puts "#{integers_ary}"
  end
end
</code>```

First, it's more rubyish to use snake_case instead of camelCase. So, content_ary, not contentArray.

Then, do content_ary.each do |content_str| instead of while i < contentArray.size(). Then you don't have to mess wit i+=1.

Next,

```<code>segments_ary = content_str.split(':')
</code>```

splits each line into a two-element array with each element begin the content to the left and right of ':'.

```<code>integers_ary = segments_ary[1].strip.split(' ').map{|int_str| int_str.to_i}
</code>```

extracts your integers on the right-hand side:

```<code>  segments_ary[1]              <= selects the right-hand side
  strip                        <= removes leading and trailing white spaces
  split(' ')                   <= creates an array of strings
  map{|int_str| int_str.to_i}  <= converts the strings to integers
</code>```

then:
      tags_ary = segments_ary[0].strip.split(',')

extracts the tags on the left-hand side of the ':'.

Now, use a case statement instead of the if... elsif... elsif.

Title: How to cut off int at the end of a line

Body:
I have a txt file similar to the following:

f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

Body:
Give something like this a shot:

content_ary.each do |content_str|
  segments_ary = content_str.split(':')
  integers_ary = segments_ary[1].strip.split(' ').map{|int_str| int_str.to_i}
  tags_ary = segments_ary[0].strip.split(',')
  case tags_ary[1].strip
  when "max"
    puts "max is here"
    puts "#{integers_ary}"
  when "sum"
    puts "sum is here"
    puts "#{integers_ary}"
  when "prod"
    puts "prod is here"
    puts "#{integers_ary}"
  end
end

First, it's more rubyish to use snake_case instead of camelCase. So, content_ary, not contentArray.

Then, do content_ary.each do |content_str| instead of while i < contentArray.size(). Then you don't have to mess wit i+=1.

Next,

segments_ary = content_str.split(':')

splits each line into a two-element array with each element begin the content to the left and right of ':'.

integers_ary = segments_ary[1].strip.split(' ').map{|int_str| int_str.to_i}

extracts your integers on the right-hand side:

  segments_ary[1]              <= selects the right-hand side
  strip                        <= removes leading and trailing white spaces
  split(' ')                   <= creates an array of strings
  map{|int_str| int_str.to_i}  <= converts the strings to integers

then:
      tags_ary = segments_ary[0].strip.split(',')

extracts the tags on the left-hand side of the ':'.

Now, use a case statement instead of the if... elsif... elsif.


问:
Cant get While loop to work
I am using a while loop to make it where if the user types anything other than "Yes" or "No" it will tell them to type something new in but everytime they type something else in it just spams "That is not an option" instead of starting back from the top. Can someone explain to me why? Thank you in advance.</p>

```<code>              using System;

class CalculatorProgram
{
    //varibale for do-while loop
    private static string endAnswer;
    public static void Main() // <----- The Entry point
    {
     //Variables
     string Choice1;
    string mathChoice;
    decimal Num1;
    decimal Num2;
    decimal Answer;
    bool userWrong = true;

    Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
    Choice1 = Console.ReadLine();

    while(userWrong)
    {
        if (Choice1 == "Yes")

        {
            do
            {
                Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
                mathChoice = Console.ReadLine();

                //User inputs the 2 numbers

                //Math Choices
                if (mathChoice == "Add")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());

                    Answer = Num1 + Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " + " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Subtract")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 - Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " - " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Multiply")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 * Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " X " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Divide")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 / Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " / " + Num2 + " = " + Answer);
                }

                else
                {
                    Console.WriteLine("This is not an option! Shutting Down..");
                    Console.ReadKey();
                    Environment.Exit(0);
                }

                //varibale for while loop to continue if selected Yes.
                Console.Write("Another Equation?: ");
                endAnswer = Console.ReadLine();

            } while (endAnswer == "Yes");

            //Goodbye Message
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
            userWrong = false;
        }
        //If someone selects no for wanting to use my program.
        else if (Choice1 == "No")
        {
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
        }
        else
        {
            Console.WriteLine("That is not an option");
            Console.ReadLine();

        }

    }

    }
}
</code>```

答:
The program is waiting for the user to input a new answer after it prints out "That is not an option," you just never prompt them for it. You also never store Choice1 again based on their new input, so it will always check the first if condition in your do-while loop with whatever they initially put in.

To fix it, change your else branch body to something like this.

```<code>//...
else
{
    Console.WriteLine("That is not an option");
    // reprompt the user so they know to type something in
    Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
    // store the new choice to recheck next loop iteration
    Choice1 = Console.ReadLine();
}
</code>```

Title: Cant get While loop to work

Body:
I am using a while loop to make it where if the user types anything other than "Yes" or "No" it will tell them to type something new in but everytime they type something else in it just spams "That is not an option" instead of starting back from the top. Can someone explain to me why? Thank you in advance.

              using System;

class CalculatorProgram
{
    //varibale for do-while loop
    private static string endAnswer;
    public static void Main() // <----- The Entry point
    {
     //Variables
     string Choice1;
    string mathChoice;
    decimal Num1;
    decimal Num2;
    decimal Answer;
    bool userWrong = true;

    Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
    Choice1 = Console.ReadLine();

    while(userWrong)
    {
        if (Choice1 == "Yes")

        {
            do
            {
                Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
                mathChoice = Console.ReadLine();

                //User inputs the 2 numbers

                //Math Choices
                if (mathChoice == "Add")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());

                    Answer = Num1 + Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " + " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Subtract")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 - Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " - " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Multiply")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 * Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " X " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Divide")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 / Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " / " + Num2 + " = " + Answer);
                }

                else
                {
                    Console.WriteLine("This is not an option! Shutting Down..");
                    Console.ReadKey();
                    Environment.Exit(0);
                }

                //varibale for while loop to continue if selected Yes.
                Console.Write("Another Equation?: ");
                endAnswer = Console.ReadLine();

            } while (endAnswer == "Yes");

            //Goodbye Message
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
            userWrong = false;
        }
        //If someone selects no for wanting to use my program.
        else if (Choice1 == "No")
        {
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
        }
        else
        {
            Console.WriteLine("That is not an option");
            Console.ReadLine();

        }

    }

    }
}

Body:
The program is waiting for the user to input a new answer after it prints out "That is not an option," you just never prompt them for it. You also never store Choice1 again based on their new input, so it will always check the first if condition in your do-while loop with whatever they initially put in.

To fix it, change your else branch body to something like this.

//...
else
{
    Console.WriteLine("That is not an option");
    // reprompt the user so they know to type something in
    Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
    // store the new choice to recheck next loop iteration
    Choice1 = Console.ReadLine();
}


问:
Modify Django for loop every four iterations
I have a calendar generated by Django and styled with Bootstrap.
Here is the code in the Django template :

```<code><div class="content">
  {% for month in period.get_months %}
    <div class="col-md-3">
      <div class="row row-centered">
        <button class="btn btn-custom active" href="{% url "month_calendar" calendar.slug %}{% querystring_for_date month.start 2 %}">{{month.name}}</button>
      </div>
      <div>
        {% month_table calendar month "small" %}
      </div>
    </div>
  {% endfor %}
</div>
</code>```

Now, since months have a different number of weeks they have different heights I would like to avoid something like this:

I understand from this answer that the best solution would be to use a clearfix.

So, how can I modify the for loop in my template so that Django inserts an extra line

 every four items?

答:
Django templates for loop store current index in forloop.counter variable. You can read about this in docs. So you can try to change you code like this:

```<code><div class="content">
  {% for month in period.get_months %}
    <div class="col-md-3">
      <div class="row row-centered">
        <button class="btn btn-custom active" href="{% url "month_calendar" calendar.slug %}{% querystring_for_date month.start 2 %}">{{month.name}}</button>
      </div>
      <div>
        {% month_table calendar month "small" %}
      </div>
    </div>
    {% if forloop.counter|divisibleby:4 %}
        <div class="clearfix"></div>
    {% endif %}
  {% endfor %}
</div>
</code>```

Body:
I have a calendar generated by Django and styled with Bootstrap.
Here is the code in the Django template :

  {% for month in period.get_months %}

        <button class="btn btn-custom active" href="{% url "month_calendar" calendar.slug %}{% querystring_for_date month.start 2 %}">{{month.name}}</button>

        {% month_table calendar month "small" %}

  {% endfor %}

Now, since months have a different number of weeks they have different heights I would like to avoid something like this:

I understand from this answer that the best solution would be to use a clearfix.

So, how can I modify the for loop in my template so that Django inserts an extra line

 every four items?

Body:
Django templates for loop store current index in forloop.counter variable. You can read about this in docs. So you can try to change you code like this:

<div class="content">
  {% for month in period.get_months %}
    <div class="col-md-3">
      <div class="row row-centered">
        <button class="btn btn-custom active" href="{% url "month_calendar" calendar.slug %}{% querystring_for_date month.start 2 %}">{{month.name}}</button>
      </div>
      <div>
        {% month_table calendar month "small" %}
      </div>
    </div>
    {% if forloop.counter|divisibleby:4 %}
        <div class="clearfix"></div>
    {% endif %}
  {% endfor %}
</div>


问:
Android RadioGroup Radiobutton Java
I have two radiogroups - RadioGroupSelect, questionRG.
In RadioGroupSelect is radioButton1, radioButton2.
In questionRG is radiobutton questionRB1.
How to set any text in questionRB1 if i will select radioButton1 and set other text, if i will select radioButton2? </p>

答:
Use the following code

```<code>    if(radioButton1.isChecked()){
        questionRB1.setText("your text");
    }
</code>```

Do similarly for the other radio button.

Title: Android RadioGroup Radiobutton Java

Body:
Use the following code

    if(radioButton1.isChecked()){
        questionRB1.setText("your text");
    }

Do similarly for the other radio button.


问:
Python: Alternative way to avoid memoryerror when using numpy array?
I am new to python and started using numpy. I am following an algorithm from paper and with my dataset it requires an array of dimension 1million * 1million.

The exact code is larray(np.random.normal(0, sigma**2, size=(794832, 794832))

Although I have a 16GB ram, numpy tries to load the array into memory while creation and hence, I am getting memoryerror. I tried using lazy initialisation with lazyarray and still not working.

Is there any way to create an array which uses file system rather than ram?

Thanks in advance.

答:
The size of the data you are creating will depend on the matrix size and the precision-type of the data.

You are trying to use np.random.normal that creates a matrix with float64 precision type values. The 64 number means that your are using 64 bits for each number, so each number will require a memory of 8 bytes (8bits per byte). If your matrix has a shape/dimension of 4000x794832, that means you need ~23.7GB [4000*794832*8] of memory allocation.

If you have a 16GB RAM it shouldn't be enough, so as it will use SWAP (if enough defined) it may take some time to create it, or just run out of memory.

The question is, do you need a float64  precision? Because it seems to be much for usual scientist developments. So maybe to speed-up any following mathematical operations, you can consider to change your matrix precision type to float16 for example [4000*794832*2].

```<code>import numpy as np
a = np.random.normal(0, 0.7**2, size=(4000,794832))
a.nbytes   # will give a size of 25434624000 [~23.7GB] (huge number)
b = np.random.normal(0, 0.7**2, size=(4000,794832)).astype(np.float16)
b.nbytes   # will give a size of 6358656000 [~5.9GB](big but at least you can do everything on RAM)
</code>```

The problem on this case is that np.random.normal hasn't got option to define directly numpy dtype, so you will create a float64 matrix and then convert it, which is not a very efficient option. But if haven't got any other choice...

Body:
The size of the data you are creating will depend on the matrix size and the precision-type of the data.

You are trying to use np.random.normal that creates a matrix with float64 precision type values. The 64 number means that your are using 64 bits for each number, so each number will require a memory of 8 bytes (8bits per byte). If your matrix has a shape/dimension of 4000x794832, that means you need ~23.7GB [4000*794832*8] of memory allocation.

If you have a 16GB RAM it shouldn't be enough, so as it will use SWAP (if enough defined) it may take some time to create it, or just run out of memory.

The question is, do you need a float64  precision? Because it seems to be much for usual scientist developments. So maybe to speed-up any following mathematical operations, you can consider to change your matrix precision type to float16 for example [4000*794832*2].

import numpy as np
a = np.random.normal(0, 0.7**2, size=(4000,794832))
a.nbytes   # will give a size of 25434624000 [~23.7GB] (huge number)
b = np.random.normal(0, 0.7**2, size=(4000,794832)).astype(np.float16)
b.nbytes   # will give a size of 6358656000 [~5.9GB](big but at least you can do everything on RAM)

The problem on this case is that np.random.normal hasn't got option to define directly numpy dtype, so you will create a float64 matrix and then convert it, which is not a very efficient option. But if haven't got any other choice...


问:
Laravel unknown column
I have a problem with this error:

```<code>https://pastebin.com/cgm5yq0P
</code>```

This is my form:

```<code>https://pastebin.com/bSU5X5EC
</code>```

This is my web.php (route controller):

Route::post('/komentarz', 'VideosController@postComment');

This is my VideoController postComment function:

```<code>https://pastebin.com/SYbEjB8H
</code>```

This is my Comment model:

```<code>https://pastebin.com/SxHX6gTP
</code>```

This is my User model comments function:

```<code>    public function comments() {
    return $this->hasMany('App\Comment');
}
</code>```

This is my Video model comments function:

public function comments(){
        return $this->belongsToMany('App\Comment')->withTimestamps();
    }

And finally, Migration file named create_comments_table:

https://pastebin.com/2cHscQfq

My Routes:
 https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong

答:
Your foreign keys are wrong. Change your migration to this.

```<code>$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

$table->unsignedInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
</code>```

Edit : This adds the comment and attaches it to the video and user.

```<code>// model fillable property

protected $fillable = [
    'text', 'user_id', 'video_id',
];

// route
Route::post('/film/{id}/komentarz', 'VideosController@postComment');

// controller method
public function postComment(CreateCommentRequest $request, $id)
{
    $video = Video::findOrFail($id);

    $video->comments()->create([
        'text' => $request->text,
        'user_id' => auth()->id(),
    ]);

    return 'works';
}

// form
{!! Form::open(['url' => "/film/{$video->id}/komentarz", 'method' => 'post','class' => 'form-horizontal']) !!}
<div class="form-group">
    <div class="col-md-3 control-label">
        {!! Form::label('text', 'Treść komentarza:') !!}
    </div>
    <div class="col-md-8">
        {!! Form::textarea('text', null, ['class'=>'form-control', 'size' => '5x5']) !!}
    </div>
</div>
<div class="form-group">
    <div class="col-md-8 col-md-offset-3">
        {!! Form::submit('Dodaj', ['class'=>'btn btn-primary btn-comment']) !!}
    </div>
</div>
{!! Form::close() !!}
</code>```

Title: Laravel unknown column

Body:
I have a problem with this error:

https://pastebin.com/cgm5yq0P

This is my form:

https://pastebin.com/bSU5X5EC

This is my web.php (route controller):

Route::post('/komentarz', 'VideosController@postComment');

This is my VideoController postComment function:

https://pastebin.com/SYbEjB8H

This is my Comment model:

https://pastebin.com/SxHX6gTP

This is my User model comments function:

    public function comments() {
    return $this->hasMany('App\Comment');
}

This is my Video model comments function:

public function comments(){
        return $this->belongsToMany('App\Comment')->withTimestamps();
    }

And finally, Migration file named create_comments_table:

https://pastebin.com/2cHscQfq

My Routes:
 https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong

Body:
Your foreign keys are wrong. Change your migration to this.

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

$table->unsignedInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');

Edit : This adds the comment and attaches it to the video and user.

// model fillable property

protected $fillable = [
    'text', 'user_id', 'video_id',
];

// route
Route::post('/film/{id}/komentarz', 'VideosController@postComment');

// controller method
public function postComment(CreateCommentRequest $request, $id)
{
    $video = Video::findOrFail($id);

    $video->comments()->create([
        'text' => $request->text,
        'user_id' => auth()->id(),
    ]);

    return 'works';
}

// form
{!! Form::open(['url' => "/film/{$video->id}/komentarz", 'method' => 'post','class' => 'form-horizontal']) !!}
<div class="form-group">
    <div class="col-md-3 control-label">
        {!! Form::label('text', 'Treść komentarza:') !!}
    </div>
    <div class="col-md-8">
        {!! Form::textarea('text', null, ['class'=>'form-control', 'size' => '5x5']) !!}
    </div>
</div>
<div class="form-group">
    <div class="col-md-8 col-md-offset-3">
        {!! Form::submit('Dodaj', ['class'=>'btn btn-primary btn-comment']) !!}
    </div>
</div>
{!! Form::close() !!}


问:
Check if rows exists before adding it to a datagridview
I'm having trouble getting this code to work, I'm adding rows to a datagridview from an SQL (WHILE) query, but while doing that I need to run a foreach inside to check if a row.Cells[0].Value exists before adding it, but i'm getting the following errors:

Error   1   foreach statement cannot operate on variables of type 'System.Windows.Forms.DataGridView' because 'System.Windows.Forms.DataGridView' does not contain a public definition for 'GetEnumerator'  C:\Users................project1.cs

Here is my code:

```<code>//dgData is a datagridview with columns created programmatically, this works already by the way.
dgData.ColumnCount = 3;
dgData.Columns[0].Name = "ColumnA";
dgData.Columns[0].Name = "ColumnB";
dgData.Columns[0].Name = "ColumnC";

string query1 = " SELECT * FROM ....... ";

SqlCommand cmd1 = new SqlCommand(query1, connection);
            //Create a data reader and Execute the command
            SqlDataReader dataReader1 = cmd1.ExecuteReader();

Application.DoEvents();
while (dataReader1.Read())
{

    string[] row1 = new string[] { dataReader1["columnA"].ToString(),     dataReader1["columnB"].ToString(), dataReader1["columnC"].ToString() };
    Boolean found = false;

    // this foreach is what doesn't work.
    foreach (DataGridViewRow row in dgData)
    {
         if (row.Cells[0].Value == dataReader1["columnA"].ToString())
         {
                 // row exists
                 found = true;
                 MessageBox.Show("Row already exists");
         }
    }

    if (!found)
    {
         dgData.Rows.Add(row1);
    }

}
</code>```

答:
I'm not shure, but could it be that you have to use</p>

```<code>foreach (DataGridViewRow row in dgData.Rows)
</code>```

Body:
I'm having trouble getting this code to work, I'm adding rows to a datagridview from an SQL (WHILE) query, but while doing that I need to run a foreach inside to check if a row.Cells[0].Value exists before adding it, but i'm getting the following errors:

Error   1   foreach statement cannot operate on variables of type 'System.Windows.Forms.DataGridView' because 'System.Windows.Forms.DataGridView' does not contain a public definition for 'GetEnumerator'  C:\Users................project1.cs

Here is my code:

//dgData is a datagridview with columns created programmatically, this works already by the way.
dgData.ColumnCount = 3;
dgData.Columns[0].Name = "ColumnA";
dgData.Columns[0].Name = "ColumnB";
dgData.Columns[0].Name = "ColumnC";

string query1 = " SELECT * FROM ....... ";

SqlCommand cmd1 = new SqlCommand(query1, connection);
            //Create a data reader and Execute the command
            SqlDataReader dataReader1 = cmd1.ExecuteReader();

Application.DoEvents();
while (dataReader1.Read())
{

    string[] row1 = new string[] { dataReader1["columnA"].ToString(),     dataReader1["columnB"].ToString(), dataReader1["columnC"].ToString() };
    Boolean found = false;

    // this foreach is what doesn't work.
    foreach (DataGridViewRow row in dgData)
    {
         if (row.Cells[0].Value == dataReader1["columnA"].ToString())
         {
                 // row exists
                 found = true;
                 MessageBox.Show("Row already exists");
         }
    }

    if (!found)
    {
         dgData.Rows.Add(row1);
    }

}

Body:
I'm not shure, but could it be that you have to use

foreach (DataGridViewRow row in dgData.Rows)


问:
last day of last month date expression in ssis
I have to create a derived column to upload a date in OLEDB destination because my source file doesn't contain this date. The date i want to get through derived column is last day of last month. Does anyone know how to get it?</p>

答:
Try the following expression, just substract the current day from the current date using DATEADD Function.

```<code>DATEADD("d", -DAY(GETDATE()), GETDATE())
</code>```

If you want to remove time you have two choices:

convert to string

```<code>LEFT((DT_STR,50,1252)DATEADD("d", -DAY(GETDATE()),GETDATE()),10)
</code>```

convert to string then to date (it will generate time 12:00 AM)

```<code>(DT_DATE)LEFT((DT_STR,50,1252)DATEADD("d", -DAY(GETDATE()),GETDATE()),10)
</code>```

Body:
Try the following expression, just substract the current day from the current date using DATEADD Function.

DATEADD("d", -DAY(GETDATE()), GETDATE())

If you want to remove time you have two choices:

convert to string

LEFT((DT_STR,50,1252)DATEADD("d", -DAY(GETDATE()),GETDATE()),10)

convert to string then to date (it will generate time 12:00 AM)

(DT_DATE)LEFT((DT_STR,50,1252)DATEADD("d", -DAY(GETDATE()),GETDATE()),10)


问:
Python/Psychopy: Logging mouse click locations
Using the code below, I'm trying to open a window for 10 seconds, have the user click anywhere on the screen as many times as they wish, and I want to log the mouse click locations. Every time the user clicks within the window (i.e. myMouse.getPressed) occurs, I'm appending the click location to a list (mouse_click_locations[]). However, the list is being appended with the same click location many times, on every frame. I want to append the click location to the list once, and no more until another click is initiated. I thought that adding 'myMouse.clickReset()' at the end of each frame would do this, but it doesn't make a difference.

After 10 seconds, I want the list to be populated with one location (x,y coord) for each mouse click initiated.

```<code>from psychopy import visual, core, gui, event, sound

win = visual.Window([800,600],color=(1,1,1), colorSpace='rgb',
rgb=None, allowGUI=True, monitor='testMonitor',
units='deg', fullscr=False)

myMouse = event.Mouse(visible=True,win=win)

refresh_rate = 60.0
default_time = 10

time_window = default_time * refresh_rate
time_window = int(time_window)

running = 1
while running:

    mouse_click_locations = []

    for frame in range(time_window):

        mouse_loc = myMouse.getPos()
        mouse_click = myMouse.getPressed()

        if mouse_click:
            mouse_click_locations.append(mouse_loc)

        win.flip()
        myMouse.clickReset()

    running = 0

win.close()

print mouse_click_locations
</code>```

Could someone help me achieve this? am I using myMouse.clickReset() incorrectly?

Cheers,
Jon

答:
This happens because the script checks the mouse state for every iteration in your frame-loop; i.e. 60 times a second. As you say, you only want to get a single event for each mouse-down. Here's one solution where you simply halt the script until all buttons are released. Also note the use of any to explicitly check all buttons.

```<code># Record mouse position if a key is pressed
if any(myMouse.getPressed())  # Any button pressed, no matter which
    mouse_click_locations.append(myMouse.getPos())

# Wait until all buttons are released
while any(myMouse.getPressed()):
    pass
</code>```

No need to use mouse.clickReset. As a small comment, you do not update visual stuff on the screen, so you do not need to include win.flip in the loop. Because it waits for the next monitor update, it effectively rounds off reaction times (if you need these) to nearest 1/60 second interval. This, and relying a bit on defaults, would also simplify the script a great deal:

```<code>default_time = 10

from psychopy import visual, core, event
win = visual.Window(color='white', monitor='testMonitor', units='deg')
myMouse = event.Mouse(visible=True, win=win)
clock = core.ClocK()

# Collect unique click events before time runs out
mouse_click_locations = []
while clock.getTime() < default_time:
    # Record mouse position if a key is pressed
    if any(myMouse.getPressed())  # Any button pressed, no matter which
        mouse_click_locations.append(myMouse.getPos())

    # Wait until all buttons are released
    while any(myMouse.getPressed()):
        pass

print mouse_click_locations
</code>```

Body:
Using the code below, I'm trying to open a window for 10 seconds, have the user click anywhere on the screen as many times as they wish, and I want to log the mouse click locations. Every time the user clicks within the window (i.e. myMouse.getPressed) occurs, I'm appending the click location to a list (mouse_click_locations[]). However, the list is being appended with the same click location many times, on every frame. I want to append the click location to the list once, and no more until another click is initiated. I thought that adding 'myMouse.clickReset()' at the end of each frame would do this, but it doesn't make a difference.

After 10 seconds, I want the list to be populated with one location (x,y coord) for each mouse click initiated.

from psychopy import visual, core, gui, event, sound

win = visual.Window([800,600],color=(1,1,1), colorSpace='rgb',
rgb=None, allowGUI=True, monitor='testMonitor',
units='deg', fullscr=False)

myMouse = event.Mouse(visible=True,win=win)

refresh_rate = 60.0
default_time = 10

time_window = default_time * refresh_rate
time_window = int(time_window)

running = 1
while running:

    mouse_click_locations = []

    for frame in range(time_window):

        mouse_loc = myMouse.getPos()
        mouse_click = myMouse.getPressed()

        if mouse_click:
            mouse_click_locations.append(mouse_loc)

        win.flip()
        myMouse.clickReset()

    running = 0

win.close()

print mouse_click_locations

Could someone help me achieve this? am I using myMouse.clickReset() incorrectly?

Cheers,
Jon

Body:
This happens because the script checks the mouse state for every iteration in your frame-loop; i.e. 60 times a second. As you say, you only want to get a single event for each mouse-down. Here's one solution where you simply halt the script until all buttons are released. Also note the use of any to explicitly check all buttons.

# Record mouse position if a key is pressed
if any(myMouse.getPressed())  # Any button pressed, no matter which
    mouse_click_locations.append(myMouse.getPos())

# Wait until all buttons are released
while any(myMouse.getPressed()):
    pass

No need to use mouse.clickReset. As a small comment, you do not update visual stuff on the screen, so you do not need to include win.flip in the loop. Because it waits for the next monitor update, it effectively rounds off reaction times (if you need these) to nearest 1/60 second interval. This, and relying a bit on defaults, would also simplify the script a great deal:

default_time = 10

from psychopy import visual, core, event
win = visual.Window(color='white', monitor='testMonitor', units='deg')
myMouse = event.Mouse(visible=True, win=win)
clock = core.ClocK()

# Collect unique click events before time runs out
mouse_click_locations = []
while clock.getTime() < default_time:
    # Record mouse position if a key is pressed
    if any(myMouse.getPressed())  # Any button pressed, no matter which
        mouse_click_locations.append(myMouse.getPos())

    # Wait until all buttons are released
    while any(myMouse.getPressed()):
        pass

print mouse_click_locations


问:
Removing default padding in listview items within Android studio
Can someone provide me with any insights on how to remove the default padding around a listview item? I have provided an image with arrows indicating what padding I am talking about.

答: You need to create custom a custom layout file for your list items. And a custom adapter. Then you can control all the appearance.</p>


问:
Spring Integration DSL Unit test cases failure on running all from build script
I have some unit test cases written for spring integration flows. On running the individual test cases from IDE no issues, but on running all test cases from gradle build some test cases are failing.

I found a QC on related issue:
https://jira.spring.io/browse/XD-3709

If any one knows solution for this, please post.

Unit Tests with below annotations:

```<code> @RunWith(SpringRunner.class)
    @Import(AlarmAPIApplication.class)
@PropertySource("classpath:application.properties ")
    @FixMethodOrder
    public class HostRegistrationFlowTest {

        @Value("${em.host.registration.url}")
        String hostRegistrationUrl;
        @Autowired
        RestTemplate restTemplate;

        @Autowired
        SubscribableChannel registerHostInputChannel;

        @Test
        public void testRegisterHost() {
</code>```

Error on running from gradle script:

```<code> java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.springframework.integration.router.MethodInvokingRouter#0] with key 'org.springframework.integration.router.MethodInvokingRouter#0'; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.integration.router:name=org.springframework.integration.router.MethodInvokingRouter#0,type=MethodInvokingRouter
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:628)
    at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:550)
    at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:432)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:781)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:259)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 44 more
Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.integration.router:name=org.springframework.integration.router.MethodInvokingRouter#0,type=MethodInvokingRouter
    at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
    at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
    at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:682)
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:618)
    ... 55 more
</code>```

答:
```<code>javax.management.InstanceAlreadyExistsException: org.springframework.integration.router:name=org.springframework.integration.router.MethodInvokingRouter#0,type=MethodInvokingRouter
</code>```

You have to use @DirtiesContext on the test class level to close all the application contexts after performing their tests. Otherwise the application contexts, created during test class initialization, aren't closed to chase the caching goal in between different test classes.

In your case one of the test classes initialize application context and register MBeans into the JMX. But not closing the application context cause the next one to try to register the MBean again. Just because you use some common configuration for different test classes.

Body:
I have some unit test cases written for spring integration flows. On running the individual test cases from IDE no issues, but on running all test cases from gradle build some test cases are failing.

I found a QC on related issue:
https://jira.spring.io/browse/XD-3709

If any one knows solution for this, please post.

Unit Tests with below annotations:

 @RunWith(SpringRunner.class)
    @Import(AlarmAPIApplication.class)
@PropertySource("classpath:application.properties ")
    @FixMethodOrder
    public class HostRegistrationFlowTest {

        @Value("${em.host.registration.url}")
        String hostRegistrationUrl;
        @Autowired
        RestTemplate restTemplate;

        @Autowired
        SubscribableChannel registerHostInputChannel;

        @Test
        public void testRegisterHost() {

Error on running from gradle script:

 java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.springframework.integration.router.MethodInvokingRouter#0] with key 'org.springframework.integration.router.MethodInvokingRouter#0'; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.integration.router:name=org.springframework.integration.router.MethodInvokingRouter#0,type=MethodInvokingRouter
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:628)
    at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:550)
    at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:432)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:781)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:259)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 44 more
Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.integration.router:name=org.springframework.integration.router.MethodInvokingRouter#0,type=MethodInvokingRouter
    at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
    at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
    at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:682)
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:618)
    ... 55 more

Body:
javax.management.InstanceAlreadyExistsException: org.springframework.integration.router:name=org.springframework.integration.router.MethodInvokingRouter#0,type=MethodInvokingRouter

You have to use @DirtiesContext on the test class level to close all the application contexts after performing their tests. Otherwise the application contexts, created during test class initialization, aren't closed to chase the caching goal in between different test classes.

In your case one of the test classes initialize application context and register MBeans into the JMX. But not closing the application context cause the next one to try to register the MBean again. Just because you use some common configuration for different test classes.


问:
length = raw_input("what is the length of all you walls added together? ") height = raw_input("what is the height of your room? ")
```<code>length = raw_input("what is the length of all you walls added together? ")
height = raw_input("what is the height of your room? ")
area = height*length
paint = raw_input("what paint would you like to use luxury paint, Standard quality, Economy quality? ")
if paint == "LP":
    answer = 2*area
    print answer
if paint == "SQ":
    answer = 1.25*area
    print answer
if paint == "EQ":
    answer = 0.55*area
    print answer
</code>```

This is the code it keeps saying that "typeerror: can't multiply sequence by non-int of type 'str'" does anyone have any idea?

i have another problem i need to set an range of what answers i can have which is between 2 and 25 for length and 1 and 6 for height
 while (length < 2) or (length > 25):
    wrong = raw_input("invalid number please try again? ")
while (height < 1) or (height > 6):
    wrong = raw_input("invalid number please try again? ")
this doesn't work it just says invalid number for everything

答:
Convert the height and length to integers or floats, like this:</p>

```<code>length = float(raw_input("what is the length of all you walls added together? "))
height = float(raw_input("what is the height of your room? "))
</code>```

Body:
length = raw_input("what is the length of all you walls added together? ")
height = raw_input("what is the height of your room? ")
area = height*length
paint = raw_input("what paint would you like to use luxury paint, Standard quality, Economy quality? ")
if paint == "LP":
    answer = 2*area
    print answer
if paint == "SQ":
    answer = 1.25*area
    print answer
if paint == "EQ":
    answer = 0.55*area
    print answer

This is the code it keeps saying that "typeerror: can't multiply sequence by non-int of type 'str'" does anyone have any idea?

i have another problem i need to set an range of what answers i can have which is between 2 and 25 for length and 1 and 6 for height
 while (length < 2) or (length > 25):
    wrong = raw_input("invalid number please try again? ")
while (height < 1) or (height > 6):
    wrong = raw_input("invalid number please try again? ")
this doesn't work it just says invalid number for everything

Body:
Convert the height and length to integers or floats, like this:

length = float(raw_input("what is the length of all you walls added together? "))
height = float(raw_input("what is the height of your room? "))


问:
Repeater with HiddenField
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

```<code> <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>
        <table id="AdminGetAllTBL">
            <tr>
                <td></td>
                <td>Username</td>
                <td>Email Address</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Active?</td>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
       <tr>
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
        <tr class="alternateTemplate">
           <td>
               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>
           </td>
           <td><%# Eval("userName") %></td>
           <td><%# Eval("emailAddress") %></td>
           <td><%# Eval("firstName") %></td>
           <td><%# Eval("lastName") %></td>
           <td><%# Eval("isActive") %></td>
       </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
            <tr>
                <td colspan="2"><a href="#">Add Administrator</a></td>
            </tr>
        </table>
    </FooterTemplate>
</asp:Repeater>
</code>```

I have a linkbutton that fires this code:

```<code>protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");
</code>```

but the hf is coming up null. What am I doing wrong?

答:
One other thing, it may not be encapsulated under your edit button control.

For instance it should look like so for the find control method to work:

```<asp:button id="AdminEdit" runat="server" onclick.... >
   <!-- Now put in your hidden field control inside (encapulated) in your button. -->
   <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
</asp:button>
```

Since AdminEdit.Controls is a container of controls, you should now be able to find that control as a first level child.   If it is not a child of the button, you will either need to make it a child, or reference it from a different method.  This is especially true for dynamically generated controls.  Ie... what control or root element is it a child of?

Title: Repeater with HiddenField

Body:
I have the following HiddenField within a Repeater labeled "AdminGetAllRPT":

 <asp:Repeater ID="AdminGetAllRPT" runat="server" OnLoad="AdminGetAllRPT_Load">
    <HeaderTemplate>

                Username
                Email Address
                First Name
                Last Name
                Active?

    </HeaderTemplate>
    <ItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </ItemTemplate>
    <AlternatingItemTemplate>

               <asp:LinkButton ID="AdminEditLnk" runat="server" OnClick="AdminEdit_OnClick">Edit
               <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
               </asp:LinkButton>

           <%# Eval("userName") %>
           <%# Eval("emailAddress") %>
           <%# Eval("firstName") %>
           <%# Eval("lastName") %>
           <%# Eval("isActive") %>

    </AlternatingItemTemplate>
    <FooterTemplate>

                Add Administrator

    </FooterTemplate>
</asp:Repeater>

I have a linkbutton that fires this code:

protected void AdminEdit_OnClick(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)AdminGetAllRPT.FindControl("editAdminEmail");

but the hf is coming up null. What am I doing wrong?

Body:
One other thing, it may not be encapsulated under your edit button control.

For instance it should look like so for the find control method to work:

<asp:button id="AdminEdit" runat="server" onclick.... >
   <!-- Now put in your hidden field control inside (encapulated) in your button. -->
   <asp:HiddenField ID="editAdminEmail" runat="server" Value='<%# Eval("emailAddress") %>' />
</asp:button>

Since AdminEdit.Controls is a container of controls, you should now be able to find that control as a first level child.   If it is not a child of the button, you will either need to make it a child, or reference it from a different method.  This is especially true for dynamically generated controls.  Ie... what control or root element is it a child of?


问:
Transform each user_id group to a feature vector
I am having a table user_aisles which is a data frame containing user_id grouped by user_aisles and n which is the number of items bought by a user in an aisle.

```<code>kable( head( summarize(user_aisles, n=n()) , 9) )
</code>```

gives

```<code>| user_id| aisle_id|  n|
|-------:|--------:|--:|
|       1|        2|  8|
|       1|        3| 12|
|       1|        4|  5|
|       2|        1|  1|
|       2|        3|  6|
|       2|       14|  1|
|       2|       17|  2|
|       2|       20|  1|
|       2|       21|  5|
</code>```

I would like to transform this into feature vectors for each user id. Such a feature vector should be nrow(aisles) dimensional.

So each user_id gets a corresponding feature vector. Feature vector for user 1 could (based on the data) look like

```<code>1: [0, 8, 12, 5, 0, .., 0]
</code>```

How can I do this?

答:
Assuming you have your data in a dataframe called data you can use tidyr's complete function:

```<code>library(tidyverse)
data %>% complete(user_id, aisle_id = 1:21, fill = list(n = 0))

# A tibble: 42 × 3
   user_id aisle_id     n
     <dbl>    <dbl> <dbl>
1        1        1     0
2        1        2     8
3        1        3    12
4        1        4     5
5        1        5     0
6        1        6     0
7        1        7     0
8        1        8     0
9        1        9     0
10       1       10     0
# ... with 32 more rows
</code>```

Here I'm assuming there are 21 possible aisle ids based on the largest value in your data.

If you want a row for each consumer you can use spread:

```<code>data %>%
complete(user_id, aisle_id = 1:21, fill = list(n = 0)) %>%
mutate(aisle_id = paste0("aisle_", formatC(aisle_id, width = 2, flag = 0))) %>% spread(aisle_id, n)

    # A tibble: 2 × 22
  user_id aisle_01 aisle_02 aisle_03 aisle_04 aisle_05 aisle_06 aisle_07 aisle_08 aisle_09 aisle_10 aisle_11 aisle_12
*   <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>
1       1        0        8       12        5        0        0        0        0        0        0        0        0
2       2        1        0        6        0        0        0        0        0        0        0        0        0
# ... with 9 more variables: aisle_13 <dbl>, aisle_14 <dbl>, aisle_15 <dbl>, aisle_16 <dbl>, aisle_17 <dbl>, aisle_18 <dbl>,
#   aisle_19 <dbl>, aisle_20 <dbl>, aisle_21 <dbl>
</code>```

Body:
I am having a table user_aisles which is a data frame containing user_id grouped by user_aisles and n which is the number of items bought by a user in an aisle.

kable( head( summarize(user_aisles, n=n()) , 9) )

gives

| user_id| aisle_id|  n|
|-------:|--------:|--:|
|       1|        2|  8|
|       1|        3| 12|
|       1|        4|  5|
|       2|        1|  1|
|       2|        3|  6|
|       2|       14|  1|
|       2|       17|  2|
|       2|       20|  1|
|       2|       21|  5|

I would like to transform this into feature vectors for each user id. Such a feature vector should be nrow(aisles) dimensional.

So each user_id gets a corresponding feature vector. Feature vector for user 1 could (based on the data) look like

1: [0, 8, 12, 5, 0, .., 0]

How can I do this?

Body:
Assuming you have your data in a dataframe called data you can use tidyr's complete function:

library(tidyverse)
data %>% complete(user_id, aisle_id = 1:21, fill = list(n = 0))

# A tibble: 42 × 3
   user_id aisle_id     n
     <dbl>    <dbl> <dbl>
1        1        1     0
2        1        2     8
3        1        3    12
4        1        4     5
5        1        5     0
6        1        6     0
7        1        7     0
8        1        8     0
9        1        9     0
10       1       10     0
# ... with 32 more rows

Here I'm assuming there are 21 possible aisle ids based on the largest value in your data.

If you want a row for each consumer you can use spread:

data %>%
complete(user_id, aisle_id = 1:21, fill = list(n = 0)) %>%
mutate(aisle_id = paste0("aisle_", formatC(aisle_id, width = 2, flag = 0))) %>% spread(aisle_id, n)

    # A tibble: 2 × 22
  user_id aisle_01 aisle_02 aisle_03 aisle_04 aisle_05 aisle_06 aisle_07 aisle_08 aisle_09 aisle_10 aisle_11 aisle_12
*   <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>
1       1        0        8       12        5        0        0        0        0        0        0        0        0
2       2        1        0        6        0        0        0        0        0        0        0        0        0
# ... with 9 more variables: aisle_13 <dbl>, aisle_14 <dbl>, aisle_15 <dbl>, aisle_16 <dbl>, aisle_17 <dbl>, aisle_18 <dbl>,
#   aisle_19 <dbl>, aisle_20 <dbl>, aisle_21 <dbl>


问:
Property initializer syntax in ESnext
I understand there is a TC-39 proposal for a new syntax called "property initializer syntax" in JavaScript classes.

I haven't yet found much documentation for this, but it is used in an egghead course when discussing React.

```<code>class Foo {
  bar = () => {
    return this;
  }
}
</code>```

What is the purpose of this proposal? How does it differ from:

```<code>class Foo {
  bar() {
    return this;
  }
}
</code>```

答:
When you use property initializer syntax with an arrow function, this in this function will always refer to the instance of the class, whereas with regular methods, you can change this by using .call() or .bind():

class Foo {
  constructor() {
    this.test = true;
  }
  bar = () => {
    return this;
  }
}
console.log(new Foo().bar.call({}).test); // true

class Foo2 {
  constructor() {
    this.test = true;
  }
  bar() {
    return this;
  }
}
console.log(new Foo2().bar.call({}).test); // undefined```

Also, this syntax can be used for other things than functions.

Title: Property initializer syntax in ESnext

Body:
I understand there is a TC-39 proposal for a new syntax called "property initializer syntax" in JavaScript classes.

I haven't yet found much documentation for this, but it is used in an egghead course when discussing React.

class Foo {
  bar = () => {
    return this;
  }
}

What is the purpose of this proposal? How does it differ from:

class Foo {
  bar() {
    return this;
  }
}

Body:
When you use property initializer syntax with an arrow function, this in this function will always refer to the instance of the class, whereas with regular methods, you can change this by using .call() or .bind():

class Foo {
  constructor() {
    this.test = true;
  }
  bar = () => {
    return this;
  }
}
console.log(new Foo().bar.call({}).test); // true

class Foo2 {
  constructor() {
    this.test = true;
  }
  bar() {
    return this;
  }
}
console.log(new Foo2().bar.call({}).test); // undefined

Also, this syntax can be used for other things than functions.