问:
Unwanted request generated with LINQ to Entities
In order to optimize a method, I look at each line of my code as well as each generated request in order to eliminate a maximum of them. I have serious doubts about the following part:

A planning contains several projects. A project contains several activities. I first load all activities for future needs. This generates, as expected, a "SELECT WHERE IN" request on the Activities table

```<code>var planningProjectIds = p.PlanningProjects.Select(x => x.PlanningProjectId).ToList();
var planningActivities = _db.PlanningActivities.Where(x => planningProjectIds.Contains(x.PlanningProjectId));
var planningActivitiesArr = planningActivities.ToLookup(x => x.PlanningProjectId);
</code>```

Here is a first attempt. The following code generates an unwanted request (between log lines 9b and 10)

```<code>foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId].ToList();
    sw.WriteLine("9b");
    pp.PlanningActivities = pp.PlanningActivities.OrderBy(x => x.Position).ThenBy(x => x.PlanningActivityId).ToList();
    sw.WriteLine("10");
    // ...
}
</code>```

Here is a second attempt. This code does not generate a query

```<code>foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId]
        .OrderBy(x => x.Position)
        .ThenBy(x => x.PlanningActivityId)
        .ToList();
    sw.WriteLine("10");
    // ...
}
</code>```

Could you tell me the reason for that? Thank you in advance ;)

Here is an extract of the log where we can see the extra request

```<code>9b
Opened connection at 06/07/2017 10:22:15 +02:00

SELECT
    [Extent1].[PlanningActivityId] AS [PlanningActivityId],
    [Extent1].[FriendlyName] AS [FriendlyName],
    [Extent1].[PlanningProjectId] AS [PlanningProjectId],
    [Extent1].[ActivityId] AS [ActivityId],
    [Extent1].[ScheduleID] AS [ScheduleID],
    [Extent1].[Position] AS [Position]
    FROM [dbo].[PlanningActivities] AS [Extent1]
    WHERE [Extent1].[PlanningProjectId] = @EntityKeyValue1

-- EntityKeyValue1: '847' (Type = Int32, IsNullable = false)

-- Executing at 06/07/2017 10:22:15 +02:00

-- Completed in 7 ms with result: SqlDataReader

Closed connection at 06/07/2017 10:22:15 +02:00

10
</code>```

Do not hesitate to tell me if I could forget valuable details to solve this small problem :)

答:
In your first block, pp is still connected to the db context so will lazily load the PlanningActivities. You may get better performance and fewer queries if you do everything in a single query and use Include to load child entities. For example:

```<code>var projects = _db.Plannings
    .Where(pl => pl.PlanningId == 1234)
    .PlanningProjects
    .Include(pl => pl.PlanningProjects
        .Select(pp => pp.PlanningActivities))
    .ToList();
</code>```

Body:
In order to optimize a method, I look at each line of my code as well as each generated request in order to eliminate a maximum of them. I have serious doubts about the following part:

A planning contains several projects. A project contains several activities. I first load all activities for future needs. This generates, as expected, a "SELECT WHERE IN" request on the Activities table

var planningProjectIds = p.PlanningProjects.Select(x => x.PlanningProjectId).ToList();
var planningActivities = _db.PlanningActivities.Where(x => planningProjectIds.Contains(x.PlanningProjectId));
var planningActivitiesArr = planningActivities.ToLookup(x => x.PlanningProjectId);

Here is a first attempt. The following code generates an unwanted request (between log lines 9b and 10)

foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId].ToList();
    sw.WriteLine("9b");
    pp.PlanningActivities = pp.PlanningActivities.OrderBy(x => x.Position).ThenBy(x => x.PlanningActivityId).ToList();
    sw.WriteLine("10");
    // ...
}

Here is a second attempt. This code does not generate a query

foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId]
        .OrderBy(x => x.Position)
        .ThenBy(x => x.PlanningActivityId)
        .ToList();
    sw.WriteLine("10");
    // ...
}

Could you tell me the reason for that? Thank you in advance ;)

Here is an extract of the log where we can see the extra request

9b
Opened connection at 06/07/2017 10:22:15 +02:00

SELECT
    [Extent1].[PlanningActivityId] AS [PlanningActivityId],
    [Extent1].[FriendlyName] AS [FriendlyName],
    [Extent1].[PlanningProjectId] AS [PlanningProjectId],
    [Extent1].[ActivityId] AS [ActivityId],
    [Extent1].[ScheduleID] AS [ScheduleID],
    [Extent1].[Position] AS [Position]
    FROM [dbo].[PlanningActivities] AS [Extent1]
    WHERE [Extent1].[PlanningProjectId] = @EntityKeyValue1

-- EntityKeyValue1: '847' (Type = Int32, IsNullable = false)

-- Executing at 06/07/2017 10:22:15 +02:00

-- Completed in 7 ms with result: SqlDataReader

Closed connection at 06/07/2017 10:22:15 +02:00

10

Do not hesitate to tell me if I could forget valuable details to solve this small problem :)

Body:
In your first block, pp is still connected to the db context so will lazily load the PlanningActivities. You may get better performance and fewer queries if you do everything in a single query and use Include to load child entities. For example:

var projects = _db.Plannings
    .Where(pl => pl.PlanningId == 1234)
    .PlanningProjects
    .Include(pl => pl.PlanningProjects
        .Select(pp => pp.PlanningActivities))
    .ToList();


来源: stackexchange

问:
Error Could not load file or assembly 'Nlog, version=4.0.0.0, culture=neutral, publickeytoken=5120e14c030593c'
I have a 2 Sharepoint projects Sharepoint-Svr-App & Sharepoint-svr-Job in one solution and both projects have the NLog reference. Publishing those two projects generates the corresponding *.wsp files without any issue. When I deploy the solution, Sharepoint-svr-App gets deployed without any issue but Sharepoint-Svr-Job failes with Error:

```<code>Could not load file or assembly 'Nlog, version=4.0.0.0, culture=neutral, publickeytoken=5120e14c030593c'
</code>```

Please find the attached screenshot here

Entries inside Sharepoint-Srv-App.csproj are given below:

```<code><ItemGroup>
    <Reference Include="NLog">
      <HintPath>packages\NLog.4.4.5\lib\net45\NLog.dll</HintPath>
    </Reference>
    <Reference Include="NLog.Web">
      <HintPath>packages\NLog.Web.4.4.0\lib\net35\NLog.Web.dll</HintPath>
    </Reference>
<ItemGroup>
</code>```

and Sharepoint-Srv-Job.csproj looks like

```<code><ItemGroup>
    <Reference Include="NLog">
      <HintPath>..\Sharepoint-Svr-App\packages\NLog.4.4.5\lib\net45\NLog.dll</HintPath>
    </Reference>
    <Reference Include="NLog.Web">
      <HintPath>..\Sharepoint-Svr-App\packages\NLog.Web.4.4.0\lib\net35\NLog.Web.dll</HintPath>
    </Reference>
<ItemGroup>
</code>```

packages.config file in both projects is same like below:

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="NLog" version="4.4.5" targetFramework="net45" />
  <package id="NLog.Config" version="4.4.5" targetFramework="net45" />
  <package id="NLog.Schema" version="4.4.5" targetFramework="net45" />
  <package id="NLog.Web" version="4.4.0" targetFramework="net45" />
</packages>
</code>```

答:
Issue got resolved

Try to add your external dlls into your solution and check.

Go to your Package.package->Advanced.

Here is one thread for your reference.

https://social.technet.microsoft.com/Forums/office/en-US/7642b88a-4046-4429-a9d2-e2088c86f3fd/deploying-custom-dlls-in-sharepoint-2013?forum=sharepointadmin

ContentLicense: CC BY-SA 3.0

Body:
I have a 2 Sharepoint projects Sharepoint-Svr-App & Sharepoint-svr-Job in one solution and both projects have the NLog reference. Publishing those two projects generates the corresponding *.wsp files without any issue. When I deploy the solution, Sharepoint-svr-App gets deployed without any issue but Sharepoint-Svr-Job failes with Error:

Could not load file or assembly 'Nlog, version=4.0.0.0, culture=neutral, publickeytoken=5120e14c030593c'

Please find the attached screenshot here

Entries inside Sharepoint-Srv-App.csproj are given below:

<ItemGroup>
    <Reference Include="NLog">
      <HintPath>packages\NLog.4.4.5\lib\net45\NLog.dll</HintPath>
    </Reference>
    <Reference Include="NLog.Web">
      <HintPath>packages\NLog.Web.4.4.0\lib\net35\NLog.Web.dll</HintPath>
    </Reference>
<ItemGroup>

and Sharepoint-Srv-Job.csproj looks like

<ItemGroup>
    <Reference Include="NLog">
      <HintPath>..\Sharepoint-Svr-App\packages\NLog.4.4.5\lib\net45\NLog.dll</HintPath>
    </Reference>
    <Reference Include="NLog.Web">
      <HintPath>..\Sharepoint-Svr-App\packages\NLog.Web.4.4.0\lib\net35\NLog.Web.dll</HintPath>
    </Reference>
<ItemGroup>

packages.config file in both projects is same like below:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="NLog" version="4.4.5" targetFramework="net45" />
  <package id="NLog.Config" version="4.4.5" targetFramework="net45" />
  <package id="NLog.Schema" version="4.4.5" targetFramework="net45" />
  <package id="NLog.Web" version="4.4.0" targetFramework="net45" />
</packages>


问:
Change Tab programatically in TabView Qt QML
How do I change tabs in TabView in Qt Quick QML
here is my code

```<code>TabView {
        id: main_tab
        width: 799
        height: 560
        tabsVisible: false

        Tab {
            id: home_tab
            source: "Home.qml"
            title: "Home"
        }
        Tab {
            id: led_tab
            source: "Led.qml"
            title: "Led"
        }
}
</code>```

I tried to set new tab using main_tab.getTab(1).active = true but it was not a success.

答:
You have to change the currentIndex property of your TabView :

```<code>main_tab.currentIndex = 0 // Will show home_tab
main_tab.currentIndex = 1 // Will show led_tab
</code>```

Body:
How do I change tabs in TabView in Qt Quick QML
here is my code

TabView {
        id: main_tab
        width: 799
        height: 560
        tabsVisible: false

        Tab {
            id: home_tab
            source: "Home.qml"
            title: "Home"
        }
        Tab {
            id: led_tab
            source: "Led.qml"
            title: "Led"
        }
}

I tried to set new tab using main_tab.getTab(1).active = true but it was not a success.

Body:
You have to change the currentIndex property of your TabView :

main_tab.currentIndex = 0 // Will show home_tab
main_tab.currentIndex = 1 // Will show led_tab


问:
Type callback argument to function based on string literal argument
I am trying to type some functions to get correct types when the function is used, with the minimum of explicit typing at this point of use.  Essentially the function is as follows, and I am aiming to type the arg of the callback function dependent on the string passed as the fntype argument.

```<code>fn(fntype: string, callback: (arg: any) => void): void;
</code>```

For example,

```<code>fn('foo', (foo) => {
    foo.somethingInTheFooInterface;
}

fn('bar', (bar) => {
    bar.somethingInTheBarInterface;
}
</code>```

These are the types I have come up with:

```<code>type FooType = "FooType";
const FooType: FooType = 'FooType';

type BarType = 'BarType';
const BarType: BarType = 'BarType';

type ActionTypes = FooType | BarType;

interface Action<T> {
    type: T;
}

interface FooInterface extends Action<FooType> {
    somethingOnTheFooInterface: string;
}

interface BarInterface extends Action<BarType> {
    somethingOnTheBarInterface: string;
}

type CallbackTypes = FooInterface | BarInterface;

type Callback<T extends CallbackTypes> = (action: T) => void;

function fn<T extends CallbackTypes, U extends ActionTypes>(actionType: U, cb: Callback<T>): void;

function fn (actionType, cb) {
    cb();
}
</code>```

Which work fine when things are used explicitly:

```<code>// Works fine if we explicitly type the arg
fn(FooType, (arg: FooInterface) => {
    arg.somethingOnTheFooInterface
});

// Works fine if we define the generics when calling
fn<FooInterface, FooType>(FooType, arg => {
    arg.somethingOnTheFooInterface;
});
</code>```

But doesn't type the callback based on the first argument:

```<code>// TypeError as arg is typed as the union type CallbackTypes
fn(FooType, arg => {
    arg.somethingOnTheFooInterface
})
</code>```

If anyone can offer any guidance as to how to achieve this typing then I would be most grateful.

答:
If I understand you correctly then it seems like a major overkill.

You should be able to achieve your goal with signature overloading:

```<code>interface FooInterface {
    somethingOnTheFooInterface: string;
}

interface BarInterface {
    somethingOnTheBarInterface: string;
}

fn(fntype: "FooType", callback: (arg: FooInterface) => void): void;
fn(fntype: "BarType", callback: (arg: BarInterface) => void): void;
fn(type: string, callback: (arg: any) => void) { ... }
</code>```

Body:
I am trying to type some functions to get correct types when the function is used, with the minimum of explicit typing at this point of use.  Essentially the function is as follows, and I am aiming to type the arg of the callback function dependent on the string passed as the fntype argument.

fn(fntype: string, callback: (arg: any) => void): void;

For example,

fn('foo', (foo) => {
    foo.somethingInTheFooInterface;
}

fn('bar', (bar) => {
    bar.somethingInTheBarInterface;
}

These are the types I have come up with:

type FooType = "FooType";
const FooType: FooType = 'FooType';

type BarType = 'BarType';
const BarType: BarType = 'BarType';

type ActionTypes = FooType | BarType;

interface Action<T> {
    type: T;
}

interface FooInterface extends Action<FooType> {
    somethingOnTheFooInterface: string;
}

interface BarInterface extends Action<BarType> {
    somethingOnTheBarInterface: string;
}

type CallbackTypes = FooInterface | BarInterface;

type Callback<T extends CallbackTypes> = (action: T) => void;

function fn<T extends CallbackTypes, U extends ActionTypes>(actionType: U, cb: Callback<T>): void;

function fn (actionType, cb) {
    cb();
}

Which work fine when things are used explicitly:

// Works fine if we explicitly type the arg
fn(FooType, (arg: FooInterface) => {
    arg.somethingOnTheFooInterface
});

// Works fine if we define the generics when calling
fn<FooInterface, FooType>(FooType, arg => {
    arg.somethingOnTheFooInterface;
});

But doesn't type the callback based on the first argument:

// TypeError as arg is typed as the union type CallbackTypes
fn(FooType, arg => {
    arg.somethingOnTheFooInterface
})

If anyone can offer any guidance as to how to achieve this typing then I would be most grateful.

Body:
If I understand you correctly then it seems like a major overkill.

You should be able to achieve your goal with signature overloading:

interface FooInterface {
    somethingOnTheFooInterface: string;
}

interface BarInterface {
    somethingOnTheBarInterface: string;
}

fn(fntype: "FooType", callback: (arg: FooInterface) => void): void;
fn(fntype: "BarType", callback: (arg: BarInterface) => void): void;
fn(type: string, callback: (arg: any) => void) { ... }


问:
UNIQUE constraint failed: sqlite database : android
I am trying to insert values in table. But there is only one value inserted. I am getting an error in log cat when I am trying to insert new values.

Log cat shows :

```<code>abort at 13 in [INSERT INTO event(totalminutesfrom,dayofweek,title,location,totalminutesto,id) VALUES (?,?,?,?,?,?)]: UNIQUE constraint failed: event.id
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: Error inserting totalminutesfrom=694 dayofweek=null title=qxs location=Eded & Mariz totalminutesto=0 id=0
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: event.id (code 1555)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.EventTableHelper.addEvent(EventTableHelper.java:76)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.AddEventActivity$5.onClick(AddEventActivity.java:217)
</code>```

Its showing error on these two lines while inserting row.

```<code>db.insert(TABLE, null, values);

   db.addEvent(new EventData(eventTitle,dayOfWeek,totalMinutesFrom, totalMinutesTo,location));
</code>```

EventTableHelper

```<code>public class EventTableHelper extends SQLiteOpenHelper {

    private static final String TABLE = "event";
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_LOCATION = "location";
    private static final String KEY_DAY_OF_WEEK = "dayofweek";
    private static final String KEY_TOTAL_MINUTES_FROM = "totalminutesfrom";
    private static final String KEY_TOTAL_MINUTES_TO = "totalminutesto";

    public EventTableHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        //createTable(db);
    }

    public void createTable(SQLiteDatabase db){
        String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
                + KEY_DAY_OF_WEEK +"TEXT" + KEY_TOTAL_MINUTES_FROM +"INTEGER"
                + KEY_TOTAL_MINUTES_TO + "INTEGER" +  KEY_LOCATION + "TEXT" +  ")";

        db.execSQL(CREATE_EVENTS_TABLE);

    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
       // db.execSQL("DROP TABLE IF EXISTS " + TABLE);

      //  createTable(db);

        // Create tables again
        //onCreate(db);
    }

    // code to add the new contact
    public void addEvent(EventData event) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, event.getId());
        values.put(KEY_TITLE,event.getTitle()); // Contact Name
        values.put(KEY_DAY_OF_WEEK,event.getDayofWeek());
        values.put(KEY_TOTAL_MINUTES_FROM,event.getFromMinutes());
        values.put(KEY_TOTAL_MINUTES_TO,event.getToMinutes());
        values.put(KEY_LOCATION,event.getLocation());
        // Inserting Row
        db.insert(TABLE, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    // code to get the single contact
   EventData getEvent(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE, new String[] { KEY_ID,
                        KEY_TITLE, KEY_DAY_OF_WEEK, KEY_TOTAL_MINUTES_FROM,KEY_TOTAL_MINUTES_TO,KEY_LOCATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
       EventData eventData = new EventData(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2),
               cursor.getInt(3),cursor.getInt(4),cursor.getString(5));

        return eventData;
    }

    // code to get all contacts in a list view
    public List<EventData> getAllEvents() {
        List<EventData> conList = new ArrayList<EventData>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {

                EventData event = new EventData();

                event.setId(Integer.parseInt(cursor.getString(0)));
                event.setTitle(cursor.getString(1));
                event.setDayofWeek(cursor.getString(2));
                event.setFromMinutes(cursor.getInt(3));
                event.setToMinutes(cursor.getInt(4));
                event.setLocation(cursor.getString(5));
                // Adding contact to list
                conList.add(event);
            } while (cursor.moveToNext());
        }

        // return contact list
        return conList;
    }
}
</code>```

How to solve this??

答: My mistake was, I tried to fill ID column though it was already defined   as INTEGER PRIMARY KEY AUTOINCREMENT

Body:
I am trying to insert values in table. But there is only one value inserted. I am getting an error in log cat when I am trying to insert new values.

Log cat shows :

abort at 13 in [INSERT INTO event(totalminutesfrom,dayofweek,title,location,totalminutesto,id) VALUES (?,?,?,?,?,?)]: UNIQUE constraint failed: event.id
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: Error inserting totalminutesfrom=694 dayofweek=null title=qxs location=Eded & Mariz totalminutesto=0 id=0
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: event.id (code 1555)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.EventTableHelper.addEvent(EventTableHelper.java:76)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.AddEventActivity$5.onClick(AddEventActivity.java:217)

Its showing error on these two lines while inserting row.

db.insert(TABLE, null, values);

   db.addEvent(new EventData(eventTitle,dayOfWeek,totalMinutesFrom, totalMinutesTo,location));

EventTableHelper

public class EventTableHelper extends SQLiteOpenHelper {

    private static final String TABLE = "event";
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_LOCATION = "location";
    private static final String KEY_DAY_OF_WEEK = "dayofweek";
    private static final String KEY_TOTAL_MINUTES_FROM = "totalminutesfrom";
    private static final String KEY_TOTAL_MINUTES_TO = "totalminutesto";

    public EventTableHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        //createTable(db);
    }

    public void createTable(SQLiteDatabase db){
        String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
                + KEY_DAY_OF_WEEK +"TEXT" + KEY_TOTAL_MINUTES_FROM +"INTEGER"
                + KEY_TOTAL_MINUTES_TO + "INTEGER" +  KEY_LOCATION + "TEXT" +  ")";

        db.execSQL(CREATE_EVENTS_TABLE);

    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
       // db.execSQL("DROP TABLE IF EXISTS " + TABLE);

      //  createTable(db);

        // Create tables again
        //onCreate(db);
    }

    // code to add the new contact
    public void addEvent(EventData event) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, event.getId());
        values.put(KEY_TITLE,event.getTitle()); // Contact Name
        values.put(KEY_DAY_OF_WEEK,event.getDayofWeek());
        values.put(KEY_TOTAL_MINUTES_FROM,event.getFromMinutes());
        values.put(KEY_TOTAL_MINUTES_TO,event.getToMinutes());
        values.put(KEY_LOCATION,event.getLocation());
        // Inserting Row
        db.insert(TABLE, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    // code to get the single contact
   EventData getEvent(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE, new String[] { KEY_ID,
                        KEY_TITLE, KEY_DAY_OF_WEEK, KEY_TOTAL_MINUTES_FROM,KEY_TOTAL_MINUTES_TO,KEY_LOCATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
       EventData eventData = new EventData(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2),
               cursor.getInt(3),cursor.getInt(4),cursor.getString(5));

        return eventData;
    }

    // code to get all contacts in a list view
    public List<EventData> getAllEvents() {
        List<EventData> conList = new ArrayList<EventData>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {

                EventData event = new EventData();

                event.setId(Integer.parseInt(cursor.getString(0)));
                event.setTitle(cursor.getString(1));
                event.setDayofWeek(cursor.getString(2));
                event.setFromMinutes(cursor.getInt(3));
                event.setToMinutes(cursor.getInt(4));
                event.setLocation(cursor.getString(5));
                // Adding contact to list
                conList.add(event);
            } while (cursor.moveToNext());
        }

        // return contact list
        return conList;
    }
}

How to solve this??

ContentLicense: CC BY-SA 4.0


问:
Unwanted outline or border around button when clicked
I have a styled button on my website. But when I click it, it creates an unwanted border or outline (I don't know which). How can I remove that border? Below is all the code that pertains to the button.

button {
    border: hidden;
    cursor: pointer;
    outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>this is my button</button></code>```

答:
Please don't remove the outlines on focus-styles, this makes your site less accessible to your keyboard-only and low-vision users.

If you choose to add something like :focus { outline: none; } to your stylesheets, also add you owns styles for focused elements.

Reading: Never remove CSS outlines

Body:
I have a styled button on my website. But when I click it, it creates an unwanted border or outline (I don't know which). How can I remove that border? Below is all the code that pertains to the button.

button {
    border: hidden;
    cursor: pointer;
    outline: none;
}

<button>this is my button</button>


问:
Tableau first sum by hour and then average by day
I have data in this form. For each day and hour I have demand data. I want to first find the total demand by each hour. And then plot the daily average for the month. How would I do that?

```<code>Date|Hour|Zone|Demand
1/1/2016|1|100|1000
1/1/2016|2|100|900
1/1/2016|3|100|950
...
1/1/2016|1|200|50
1/1/2016|2|200|46
1/1/2016|3|200|52
...
</code>```

And so on.

Thanks.

答:
You should try this. Hope it helps

Drag 'MDY[Date]' in columns & 'SUM[Demand]' in rows

Convert 'Hour' to dimension, if it's not. Drag it to 'Color' Marks. Change it to bar graph.

Drag 'AVG[Demand]' in rows. In Marks, remove 'Hour' from 'Color' of 'AVG[Demand]' Marks. Change it to line graph.

You can very well play around with graph mode and other cosmetic changes you would like.

Body:
I have data in this form. For each day and hour I have demand data. I want to first find the total demand by each hour. And then plot the daily average for the month. How would I do that?

Date|Hour|Zone|Demand
1/1/2016|1|100|1000
1/1/2016|2|100|900
1/1/2016|3|100|950
...
1/1/2016|1|200|50
1/1/2016|2|200|46
1/1/2016|3|200|52
...

And so on.

Thanks.


问:
Jupyter notebook not trusted
I am using Anaconda to work on a Jupyter notebook which displays "Not Trusted" (see on screenshot below).

What does it mean? Is it a problem? How can I solve it?

答:
It is a security feature to disable the execution of arbitrary code from untrusted notebooks, without the user's consent. There is a doc page about it https://jupyter-notebook.readthedocs.io/en/stable/security.html#security-in-notebook-documents

It won't prevent you from manually running the code, that's actually one way of "trusting" the outputs.

Title: Jupyter notebook not trusted


问:
Can anybody explain the concept of pluggable adapter to me with good example?
Can anybody explain the concept of pluggable adapter to me with good example?</p>

答:
You can read this article about adapter/pluggable pattern:

Table of content in this article:

```<code>* 1 Design Patterns
* 2 Intent of Adapter
* 3 Motivation
* 4 Structure
* 5 Applicability
* 6 Consequences
* 7 Implementation
      o 7.1 Known Uses and Sample Code
      o 7.2 Related Patterns
* 8 Conclusions
* 9 Appendix
      o 9.1 References
      o 9.2 Glossary
</code>```

Quote:

Smalltalk introduced the concept of a
  "pluggable adapter" to describe
  classes with built-in interface
  adaptation. This interesting concept
  allows for classes to be introduced
  into existing systems that might
  expect different interfaces to the
  class. This technique can help promote
  class reuse across modules and even
  projects.

Here is a small example:

We have two classes - Foo & Boo that outputs some string to console. Adapter class can adapt methods from both classes to provide interface (SaySomething) required by client. Note that there is no dependency on interface name - we can easily adapt both SayHey and Bark methods.

```<code>class Foo
{
    public static void SayHey() { Console.WriteLine("Hey!"); }
}

class Boo
{
    public static void Bark() { Console.WriteLine("Woof!"); }
}

class Adapter
{
    public Action SaySomething { get; private set;} // "pluggable" adapter

    public Adapter(Action saySomethingAction)
    {
        SaySomething = saySomethingAction;
    }
}

class Program
{
    static void Main(string[] args)
    {
        (new Adapter(Foo.SayHey)).SaySomething();
        (new Adapter(Boo.Bark)).SaySomething();
    }
}
</code>```

OwnerDisplayName: infynyxx

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ates Goral

Body:
You can read this article about adapter/pluggable pattern:

Table of content in this article:

* 1 Design Patterns
* 2 Intent of Adapter
* 3 Motivation
* 4 Structure
* 5 Applicability
* 6 Consequences
* 7 Implementation
      o 7.1 Known Uses and Sample Code
      o 7.2 Related Patterns
* 8 Conclusions
* 9 Appendix
      o 9.1 References
      o 9.2 Glossary

Quote:

Smalltalk introduced the concept of a
  "pluggable adapter" to describe
  classes with built-in interface
  adaptation. This interesting concept
  allows for classes to be introduced
  into existing systems that might
  expect different interfaces to the
  class. This technique can help promote
  class reuse across modules and even
  projects.

Here is a small example:

We have two classes - Foo & Boo that outputs some string to console. Adapter class can adapt methods from both classes to provide interface (SaySomething) required by client. Note that there is no dependency on interface name - we can easily adapt both SayHey and Bark methods.

class Foo
{
    public static void SayHey() { Console.WriteLine("Hey!"); }
}

class Boo
{
    public static void Bark() { Console.WriteLine("Woof!"); }
}

class Adapter
{
    public Action SaySomething { get; private set;} // "pluggable" adapter

    public Adapter(Action saySomethingAction)
    {
        SaySomething = saySomethingAction;
    }
}

class Program
{
    static void Main(string[] args)
    {
        (new Adapter(Foo.SayHey)).SaySomething();
        (new Adapter(Boo.Bark)).SaySomething();
    }
}

OwnerDisplayName: aku

LastEditorDisplayName: aku


问:
Google Maps API 3 fitBounds padding - ensure markers are not obscured by overlaid controls
I'd like to be able add padding to a map view after calling a map.fitBounds(), so all markers can be visible regardless of map controls or things like sliding panels that would cover markers when opened. Leaftlet has an option to add padding to fitBounds, but Google Maps does not.

Sometimes the northmost markers partially hide above the viewport. The westmost markers also often lay under the zoom slider. With API 2 it was possible to form a virtual viewport by reducing given paddings from the map viewport and then call the method showBounds() to calculate and perform zooming and centering based on that virtual viewport:

```<code>map.showBounds(bounds, {top:30,right:10,left:50});
</code>```

A working example of this for API 2 can be found here under the showBounds() example link.

I cannot find similar functionality in API V3, but hopefully there is another way this can be accomplished. Maybe I could grab the northeast and southwest points, then add fake coordinates to extend the bounds further after including them?

UPDATE

(Codepen in case the code below doesn't work)

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    draggable: true,
    streetViewControl: false,
    zoomControl: false
  });

  var marker1 = new google.maps.Marker({
    position: {lat: 37, lng: -121},
    map: map,
  });

  var marker2 = new google.maps.Marker({
    position: {lat: 39.3, lng: -122},
    map: map,
  });

  var bounds = new google.maps.LatLngBounds();
  bounds.extend(marker1.position);
  bounds.extend(marker2.position);
  map.fitBounds(bounds);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
  height: 640px;
  width: 360px;
}
#overlays {
  position: absolute;
  height: 50px;
  width: 340px;
  background: white;
  margin: -80px 10px;
  text-align: center;
  line-height: 50px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>

Controls / Order pizza / ETA / etc.

```

The problem is this:

I've tried adding a control as documented at Custom controls, but the map isn't exactly aware of it - see this fiddle forked from the Maps custom control example. One of the markers is still obscured by the control.

答:
As of June 2017 the Maps JavaScript API is supporting the padding parameter in the fitBounds() method.

```<code>fitBounds(bounds:LatLngBounds|LatLngBoundsLiteral, padding?:number)
</code>```

Please refer to the documentation for further details

https://developers.google.com/maps/documentation/javascript/reference#Map

Body:
I'd like to be able add padding to a map view after calling a map.fitBounds(), so all markers can be visible regardless of map controls or things like sliding panels that would cover markers when opened. Leaftlet has an option to add padding to fitBounds, but Google Maps does not.

Sometimes the northmost markers partially hide above the viewport. The westmost markers also often lay under the zoom slider. With API 2 it was possible to form a virtual viewport by reducing given paddings from the map viewport and then call the method showBounds() to calculate and perform zooming and centering based on that virtual viewport:

map.showBounds(bounds, {top:30,right:10,left:50});

A working example of this for API 2 can be found here under the showBounds() example link.

I cannot find similar functionality in API V3, but hopefully there is another way this can be accomplished. Maybe I could grab the northeast and southwest points, then add fake coordinates to extend the bounds further after including them?

UPDATE

(Codepen in case the code below doesn't work)

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    draggable: true,
    streetViewControl: false,
    zoomControl: false
  });

  var marker1 = new google.maps.Marker({
    position: {lat: 37, lng: -121},
    map: map,
  });

  var marker2 = new google.maps.Marker({
    position: {lat: 39.3, lng: -122},
    map: map,
  });

  var bounds = new google.maps.LatLngBounds();
  bounds.extend(marker1.position);
  bounds.extend(marker2.position);
  map.fitBounds(bounds);
}

#map {
  height: 640px;
  width: 360px;
}
#overlays {
  position: absolute;
  height: 50px;
  width: 340px;
  background: white;
  margin: -80px 10px;
  text-align: center;
  line-height: 50px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>

Controls / Order pizza / ETA / etc.

The problem is this:

I've tried adding a control as documented at Custom controls, but the map isn't exactly aware of it - see this fiddle forked from the Maps custom control example. One of the markers is still obscured by the control.

Body:
As of June 2017 the Maps JavaScript API is supporting the padding parameter in the fitBounds() method.

fitBounds(bounds:LatLngBounds|LatLngBoundsLiteral, padding?:number)

Please refer to the documentation for further details

https://developers.google.com/maps/documentation/javascript/reference#Map


问:
Bottom div alignment issue if upper have boder on hover
The issue when adding border property on hover the below div alignment is getting distorted. I know it is because it increase the height of hovered div which cause. Is there any work around.

The box height is depend on content inside it so we cant fix it. fiddle

.col {
  width: 20%;
  padding: 10px;
  float: left;
  box-sizing: border-box
}

.col:hover {
  border: solid 1px red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="col">1</div>
  <div class="col">2</div>
  <div class="col">3</div>
  <div class="col">4</div>
  <div class="col">5</div>
  <div class="col">6</div>
  <div class="col">7</div>
  <div class="col">8</div>
</div></code>```

Edit

I have added the hover property to top most parent div which add transparent border to all the div. which fix this issue but it does not seem good approach because user can see something moving when hover

答:
Add transparent border to child divs and change color of border on hover</p>

```<code>  .col {  width: 20%;  padding: 10px;  float: left;  box-sizing: border-box;border: solid 1px transparent;}.col:hover {  border-color: red;}
</code>```

Body:
The issue when adding border property on hover the below div alignment is getting distorted. I know it is because it increase the height of hovered div which cause. Is there any work around.

The box height is depend on content inside it so we cant fix it. fiddle

.col {
  width: 20%;
  padding: 10px;
  float: left;
  box-sizing: border-box
}

.col:hover {
  border: solid 1px red
}

1

2

3

4

5

6

7

8

Edit

I have added the hover property to top most parent div which add transparent border to all the div. which fix this issue but it does not seem good approach because user can see something moving when hover

Body:
Add transparent border to child divs and change color of border on hover

  .col {  width: 20%;  padding: 10px;  float: left;  box-sizing: border-box;border: solid 1px transparent;}.col:hover {  border-color: red;}


问:
How to Export an Excel file (.xlsx) format using SQL Server
Actually i looking to export an excel(.xlsx) file format. Below is my query which is used to send .csv file format using sp_send_dbmail

```<code> EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'eMail Notification',
@recipients = 'abc@gmail.com',
@query = 'use [dbname] select im.FullName as EmployeeName, im.MemberIC as NRIC
         from tblIndividualMst im
         where im.RecStatus = ''A''
         and (im.DateOfResign >= getdate() or im.DateOfResign is null)' ,
@subject = 'Test',
@attach_query_result_as_file = 1 ,
@query_attachment_filename = 'test.csv',
@query_result_separator=',',@query_result_width =32767,
@query_result_no_padding=1;
</code>```

So while i tried to modifiy the file format from "test.csv" to "test.xlsx", all the data's messing up in test.xlsx. So how can i modify my query to get correct .xlsx file format.

Any help appreciated. Thanks!!!

答:
I have once tried it earlier. You can use this, though this might not work with sp_send_dbmail :

```<code>insert into OPENROWSET(
   'Microsoft.Jet.OLEDB.4.0',
   'Excel 8.0;Database=d:\testfile.xls;;HDR=YES',
   'SELECT * FROM [Sheet1$]')
select * from table1
</code>```

Alternatively, I will suggest to use SSIS which is actually built to do ETL related task. You can write from any source to excel destination and use send mail task for sending it. It is configurable to be used with SQL Server Agent as well.

SSIS details :

Microsoft link of SSIS

Email excel file using SSIS

Email files using SSIS

Body:
Actually i looking to export an excel(.xlsx) file format. Below is my query which is used to send .csv file format using sp_send_dbmail

 EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'eMail Notification',
@recipients = 'abc@gmail.com',
@query = 'use [dbname] select im.FullName as EmployeeName, im.MemberIC as NRIC
         from tblIndividualMst im
         where im.RecStatus = ''A''
         and (im.DateOfResign >= getdate() or im.DateOfResign is null)' ,
@subject = 'Test',
@attach_query_result_as_file = 1 ,
@query_attachment_filename = 'test.csv',
@query_result_separator=',',@query_result_width =32767,
@query_result_no_padding=1;

So while i tried to modifiy the file format from "test.csv" to "test.xlsx", all the data's messing up in test.xlsx. So how can i modify my query to get correct .xlsx file format.

Any help appreciated. Thanks!!!

Body:
I have once tried it earlier. You can use this, though this might not work with sp_send_dbmail :

insert into OPENROWSET(
   'Microsoft.Jet.OLEDB.4.0',
   'Excel 8.0;Database=d:\testfile.xls;;HDR=YES',
   'SELECT * FROM [Sheet1$]')
select * from table1

Alternatively, I will suggest to use SSIS which is actually built to do ETL related task. You can write from any source to excel destination and use send mail task for sending it. It is configurable to be used with SQL Server Agent as well.

SSIS details :

Microsoft link of SSIS

Email excel file using SSIS

Email files using SSIS


问:
autocomplete is not getting disabled for select element
I tried making autocomplete property to false , none ,off or random string as suggested by some post,

None of the mentioned are working, Do anyone know how can we disable autofill of browser for select element.

```<code>  componentDidMount () {
  //controlNode is select element.

  if(this.props.autoFill === false){
    this.controlNode.setAttribute('autocomplete','none');
  }

  let selectedIndex = -1;
  if (this.controlNode) {
      selectedIndex = this.controlNode.selectedIndex;
  }

  if (selectedIndex >= 0) {
      const inputDOM = ReactDOM.findDOMNode(this.controlNode);

      let tempOption;
      if (inputDOM.childNodes.length === 1) {
          tempOption = document.createElement('option');
          inputDOM.appendChild(tempOption);
      }

      const options = this.controlNode.options;
      const tempIndex = (selectedIndex + 1) % options.length;
      options[tempIndex].selected = true;
      options[selectedIndex].selected = true;

      if (tempOption) {
          inputDOM.removeChild(tempOption);
      }
  }
}
</code>```

Thanks.

答:
Changed autocomplete="disabled" for select box and it seems to be working fine , don't know why this is accepted by chrome browser.

Thanks.

Body:
I tried making autocomplete property to false , none ,off or random string as suggested by some post,

None of the mentioned are working, Do anyone know how can we disable autofill of browser for select element.

  componentDidMount () {
  //controlNode is select element.

  if(this.props.autoFill === false){
    this.controlNode.setAttribute('autocomplete','none');
  }

  let selectedIndex = -1;
  if (this.controlNode) {
      selectedIndex = this.controlNode.selectedIndex;
  }

  if (selectedIndex >= 0) {
      const inputDOM = ReactDOM.findDOMNode(this.controlNode);

      let tempOption;
      if (inputDOM.childNodes.length === 1) {
          tempOption = document.createElement('option');
          inputDOM.appendChild(tempOption);
      }

      const options = this.controlNode.options;
      const tempIndex = (selectedIndex + 1) % options.length;
      options[tempIndex].selected = true;
      options[selectedIndex].selected = true;

      if (tempOption) {
          inputDOM.removeChild(tempOption);
      }
  }
}

Thanks.


答:
You can try doing

```<code>jupyter trust notebook-name.ipynb
</code>```

as is stated in the docs.

After that, open the notebook as usual with

```<code>jupyter notebook notebook-name.ipynb
</code>```

Title: Jupyter notebook not trusted

Body:
I am using Anaconda to work on a Jupyter notebook which displays "Not Trusted" (see on screenshot below).

What does it mean? Is it a problem? How can I solve it?

Body:
You can try doing

jupyter trust notebook-name.ipynb

as is stated in the docs.

After that, open the notebook as usual with

jupyter notebook notebook-name.ipynb


答:
When you add a border of 1px the padding increase by 1px also. You need to account for this and change the padding to 9px when hovered.

Fixed fiddle: https://jsfiddle.net/nmxzzvk5/4/

```<code>.col{width: 20%; padding: 10px; float: left; box-sizing: border-box}
.col:hover{ border: solid 1px red; padding: 9px;}
</code>```

Title: Bottom div alignment issue if upper have boder on hover

Body:
When you add a border of 1px the padding increase by 1px also. You need to account for this and change the padding to 9px when hovered.

Fixed fiddle: https://jsfiddle.net/nmxzzvk5/4/

.col{width: 20%; padding: 10px; float: left; box-sizing: border-box}
.col:hover{ border: solid 1px red; padding: 9px;}


问:
How to get value of selected option of yii2 select2 widget
I am trying to get the value of selected option within same page.
I am using select2 widget.

```<code><?php
echo '<label class="control-label">Group</label>';
$data = ['1' => 'option1', '2' => 'option2'];
echo Select2::widget([
    'name'=> 'group',
    'data' => $data,
    'options' => ['placeholder' => 'Select a option...', 'id' => 'sem'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);
?>
<input type="text" id='items' value="<?=$selectedvalue?> />'
</code>```

Here I want get that selected value within that page in input box.

```<code><input type="text" id='items' value="<?=$selectedvalue?> />
</code>```

I am using Yii2 I am new on it.
can anyone help me?

答:
You can get the selected value with jQuery with:</p>

```<code>$("#id_of_your_select2_widget").on("change", function (e) {
    var id = $("#id_of_your_select2_widget").select2("data")[0].id;

   // Now you can work with the selected value, i.e.:
   $("#items").val(id);
});
</code>```

Body:
I am trying to get the value of selected option within same page.
I am using select2 widget.

<?php
echo 'Group';
$data = ['1' => 'option1', '2' => 'option2'];
echo Select2::widget([
    'name'=> 'group',
    'data' => $data,
    'options' => ['placeholder' => 'Select a option...', 'id' => 'sem'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);
?>
<input type="text" id='items' value="<?=$selectedvalue?> />'

Here I want get that selected value within that page in input box.

<input type="text" id='items' value="<?=$selectedvalue?> />

I am using Yii2 I am new on it.
can anyone help me?

Body:
You can get the selected value with jQuery with:

$("#id_of_your_select2_widget").on("change", function (e) {
    var id = $("#id_of_your_select2_widget").select2("data")[0].id;

   // Now you can work with the selected value, i.e.:
   $("#items").val(id);
});


问:
Java/Hibernate Table does not exist error
I am facing this error for quite a while now. I have managed to find a work-around by mapping the entity in my HibernateUtil class. However, I would like to achieve this using hibernate.cfg.xml.

Error that I am getting:

```<code>Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1441)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:491)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3201)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2411)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at Main.main(Main.java:14)

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydatabase.personentity' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
... 18 more
</code>```

Hibernate Config:

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of mapped classes -->
<mapping class="PersonEntity"/>

</session-factory>
</hibernate-configuration>
</code>```

Entity:

```<code>@Entity
public class PersonEntity
{
private int id;
private String name;

@Id
@Column(name = "ID")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
@Column(name = "Name")
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}
</code>```

Hibernate Util:

```<code>public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
    Configuration configuration = new Configuration();
    configuration.configure();

    StandardServiceRegistry standardRegistry = new
    StandardServiceRegistryBuilder()
            .configure()
            .build();

    return configuration.buildSessionFactory(standardRegistry);
}
catch(Exception e) {
    throw new ExceptionInInitializerError(e);
}
}

public static Session getSession()
{
return sessionFactory.openSession();
}

public static void close()
{
sessionFactory.close();
}
}
</code>```

Main class which is meant to save some hardcoded values:

```<code>public class Main {
public static void main(String[] args) {
    PersonEntity personEntity = new PersonEntity();

    personEntity.setId(1);
    personEntity.setName("Cris");

    Session session = HibernateUtil.getSession();

    session.beginTransaction();
    session.save(personEntity);
    session.getTransaction().commit();

}

}
</code>```

I would be grateful if someone could help, in my opinion the problem lays in hibernate.cfg.xml, but that's just my guess.
Thanks in advance

答:
If the table exists in the database, for example naming person, then you should annotate the entity with @Table:

```<code>@Entity
@Table(name = "person")
public class PersonEntity
</code>```

If you want hibernate to create the table for you, you should change hbm2ddl.auto to create at first, then change it back to update after the table has been created.

```<code><property name="hbm2ddl.auto">create</property>
</code>```

BTW, the mapping class in hibernate.cfg.xml should be full package name.

Body:
I am facing this error for quite a while now. I have managed to find a work-around by mapping the entity in my HibernateUtil class. However, I would like to achieve this using hibernate.cfg.xml.

Error that I am getting:

Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1441)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:491)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3201)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2411)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at Main.main(Main.java:14)

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydatabase.personentity' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
... 18 more

Hibernate Config:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping class="PersonEntity"/>

</session-factory>
</hibernate-configuration>

Entity:

@Entity
public class PersonEntity
{
private int id;
private String name;

@Id
@Column(name = "ID")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
@Column(name = "Name")
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}

Hibernate Util:

public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
    Configuration configuration = new Configuration();
    configuration.configure();

    StandardServiceRegistry standardRegistry = new
    StandardServiceRegistryBuilder()
            .configure()
            .build();

    return configuration.buildSessionFactory(standardRegistry);
}
catch(Exception e) {
    throw new ExceptionInInitializerError(e);
}
}

public static Session getSession()
{
return sessionFactory.openSession();
}

public static void close()
{
sessionFactory.close();
}
}

Main class which is meant to save some hardcoded values:

public class Main {
public static void main(String[] args) {
    PersonEntity personEntity = new PersonEntity();

    personEntity.setId(1);
    personEntity.setName("Cris");

    Session session = HibernateUtil.getSession();

    session.beginTransaction();
    session.save(personEntity);
    session.getTransaction().commit();

}

}

I would be grateful if someone could help, in my opinion the problem lays in hibernate.cfg.xml, but that's just my guess.
Thanks in advance

Body:
If the table exists in the database, for example naming person, then you should annotate the entity with @Table:

@Entity
@Table(name = "person")
public class PersonEntity

If you want hibernate to create the table for you, you should change hbm2ddl.auto to create at first, then change it back to update after the table has been created.

<property name="hbm2ddl.auto">create</property>

BTW, the mapping class in hibernate.cfg.xml should be full package name.


问:
asp.net mvc fileupload ReadTimeout in HttpPostedFileBase inputstream
I have action in asp.net mvc that accepts a uploaded file. The HttpPostedFileBase I get is not null and even ContentLength has value greater than 0, but when I inspect "InputSream", it has following error :

ReadTimeout = '((System.Web.HttpPostedFileWrapper)refile).InputStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

So when I want to convert to readitbytes as follow, the there is nothing except empty array :

```<code>using (var reader = new System.IO.BinaryReader(refile.InputStream))
                    {
                        var a = reader.ReadBytes(model.File.ContentLength);
                    }
</code>```

So "a" get "{byte[0]}".

What is the problem ?

答:
Abp is trying to validate MVC Action parameters and when it tries to read the value of your files parameter to validate it, this exception occurs.

You can ignore HttpPostedFileWrapper types for validation and everything should work perfectly.

Use this to get byte array from it (more details in : Convert HttpPostedFileBase to byte[])

```<code>using (var ms = new MemoryStream())
  {
     refile.InputStream.CopyTo(ms);
     byte[] a = ms.ToArray();

  }
</code>```

Body:
I have action in asp.net mvc that accepts a uploaded file. The HttpPostedFileBase I get is not null and even ContentLength has value greater than 0, but when I inspect "InputSream", it has following error :

ReadTimeout = '((System.Web.HttpPostedFileWrapper)refile).InputStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

So when I want to convert to readitbytes as follow, the there is nothing except empty array :

using (var reader = new System.IO.BinaryReader(refile.InputStream))
                    {
                        var a = reader.ReadBytes(model.File.ContentLength);
                    }

So "a" get "{byte[0]}".

What is the problem ?

Body:
Abp is trying to validate MVC Action parameters and when it tries to read the value of your files parameter to validate it, this exception occurs.

You can ignore HttpPostedFileWrapper types for validation and everything should work perfectly.

Use this to get byte array from it (more details in : Convert HttpPostedFileBase to byte[])

using (var ms = new MemoryStream())
  {
     refile.InputStream.CopyTo(ms);
     byte[] a = ms.ToArray();

  }


问:
python - flask_simpleldap won't bind
I'm using flask_simpleldap and am struggling to get a bind connection to do anything useful.

My LDAP server is active directory.

The stripped down code looks as follows, and looks almost identical to the example:

```<code>from flask import Flask
from flask_simpleldap import LDAP

app = Flask(__name__)
app.secret_key = 'super secret key'
app.debug = True

app.config['LDAP_HOST'] = 'my-ldap-host.example.com'
app.config['LDAP_REALM_NAME'] = 'LDAP Authentication'
app.config['LDAP_SCHEMA'] = 'ldaps'
app.config['LDAP_PORT'] = 636
app.config['LDAP_BASE_DN'] = 'dc=example,dc=com'
app.config['LDAP_USERNAME'] = 'binduser@example.com'
app.config['LDAP_PASSWORD'] = 'binduser_pw'

app.config['LDAP_OBJECTS_DN'] = 'distinguishedName'
app.config['LDAP_OPENLDAP'] = False

ldap = LDAP(app)

@app.route('/ldap')
@ldap.basic_auth_required
def ldap_protected():
    return 'Welcome, {0}!'.format(g.ldap_username)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
</code>```

When running the flask app, i'll get an error such as this:

```<code>LDAPException: Operations error
</code>```

While trying to troubleshoot, i've modified flask_simpleldap __init__.py file to show the info as well as the desc of the error, on line 274; Now i get a bit more info about the error:

```<code>LDAPException: 000004DC: LdapErr: DSID-0C090752,
comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v2580
</code>```

So, i guess what i need to understand is why my initial bind won't work... do i have something wrong in my app.config?

Not sure what the problem could be... ldapsearch seems to work from a shell as such:

```<code>ldapsearch -x -LLL -E pr=200/noprompt -h my-ldap-host.example.com -D "binduser@example.com" -w 'binduser_pw' -b "dc=example, dc=com" -s sub  "(sAMAccountName=binduser)"    | grep distinguishedName

distinguishedName: CN=Bind User,OU=Some_OU,DC=example,DC=com
</code>```

Other details:

I've tried on python2.7 and 3.5, same issues

Centos 7.2

Active Directory is my LDAP server

Any help appreciated, thanks.

答:
Your username must be fully qualified.</p>

```<code>app.config['LDAP_USERNAME'] = 'uid=binduser,dc=example,dc=com'
</code>```

Title: python - flask_simpleldap won't bind

Body:
I'm using flask_simpleldap and am struggling to get a bind connection to do anything useful.

My LDAP server is active directory.

The stripped down code looks as follows, and looks almost identical to the example:

from flask import Flask
from flask_simpleldap import LDAP

app = Flask(__name__)
app.secret_key = 'super secret key'
app.debug = True

app.config['LDAP_HOST'] = 'my-ldap-host.example.com'
app.config['LDAP_REALM_NAME'] = 'LDAP Authentication'
app.config['LDAP_SCHEMA'] = 'ldaps'
app.config['LDAP_PORT'] = 636
app.config['LDAP_BASE_DN'] = 'dc=example,dc=com'
app.config['LDAP_USERNAME'] = 'binduser@example.com'
app.config['LDAP_PASSWORD'] = 'binduser_pw'

app.config['LDAP_OBJECTS_DN'] = 'distinguishedName'
app.config['LDAP_OPENLDAP'] = False

ldap = LDAP(app)

@app.route('/ldap')
@ldap.basic_auth_required
def ldap_protected():
    return 'Welcome, {0}!'.format(g.ldap_username)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)

When running the flask app, i'll get an error such as this:

LDAPException: Operations error

While trying to troubleshoot, i've modified flask_simpleldap __init__.py file to show the info as well as the desc of the error, on line 274; Now i get a bit more info about the error:

LDAPException: 000004DC: LdapErr: DSID-0C090752,
comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v2580

So, i guess what i need to understand is why my initial bind won't work... do i have something wrong in my app.config?

Not sure what the problem could be... ldapsearch seems to work from a shell as such:

ldapsearch -x -LLL -E pr=200/noprompt -h my-ldap-host.example.com -D "binduser@example.com" -w 'binduser_pw' -b "dc=example, dc=com" -s sub  "(sAMAccountName=binduser)"    | grep distinguishedName

distinguishedName: CN=Bind User,OU=Some_OU,DC=example,DC=com

Other details:

I've tried on python2.7 and 3.5, same issues

Centos 7.2

Active Directory is my LDAP server

Any help appreciated, thanks.

Body:
Your username must be fully qualified.

app.config['LDAP_USERNAME'] = 'uid=binduser,dc=example,dc=com'


问:
PowerShell length function
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}
```

<p>Loop is not working, it was working till yesterday.</p>

```Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'
```

答:
I don't see any issue with the posted code but still if you are not getting any result then most probably the pattern you mentioned isn't matching -Pattern "Final result:". You probably want to check that once. You might also want to do a case sensitive matching like

```<code>$select1=Select-String -Path $filePath -Pattern "Final result:" -CaseSensitive
</code>```

Well I tried to simulate your scenario with below text in file sample.txt

```<code>Final result: hey there get lost
hi buddy you come in plz
you need to come early
Final result: hey hello
</code>```

Then when run your command it have multiple matches and thus Line array is null. So instead of checking for $select1.Line.Length -gt 0 you should just check the Length property like

```<code>$select1.Length -gt 0
</code>```

Title: PowerShell length function

Body:
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}

Loop is not working, it was working till yesterday.

Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'

Body:
I don't see any issue with the posted code but still if you are not getting any result then most probably the pattern you mentioned isn't matching -Pattern "Final result:". You probably want to check that once. You might also want to do a case sensitive matching like

$select1=Select-String -Path $filePath -Pattern "Final result:" -CaseSensitive

Well I tried to simulate your scenario with below text in file sample.txt

Final result: hey there get lost
hi buddy you come in plz
you need to come early
Final result: hey hello

Then when run your command it have multiple matches and thus Line array is null. So instead of checking for $select1.Line.Length -gt 0 you should just check the Length property like

$select1.Length -gt 0


问:
Grid of Checkboxes in WPF
I have a WPF UserControl's datacontext tied to a class like this:

```<code>public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}
</code>```

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.

答:
You might consider creating a class that exposes Row, Column, and Value properties, and binding to a collection of these.  This lets you assign row and column positions using the method of your choice, and layout in a grid is very straightforward (once you understand how ItemsControl uses its ItemsPanel and ItemContainerStyle properties, of course):

```<code>      <ItemsControl ItemsSource="{Binding Checkboxes}">
        <ItemsControl.ItemTemplate>
          <DataTemplate>
            <CheckBox IsChecked="{Binding Value, Mode=TwoWay}"/>
          </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
          <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
            </Grid.RowDefinitions>
            </Grid>
          </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
          <Style TargetType="ContentPresenter">
            <Setter Property="Grid.Row" Value="{Binding Row}"/>
            <Setter Property="Grid.Column" Value="{Binding Column}"/>
          </Style>
        </ItemsControl.ItemContainerStyle>
      </ItemsControl>
</code>```

Title: Grid of Checkboxes in WPF

Body:
I have a WPF UserControl's datacontext tied to a class like this:

public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.

Body:
You might consider creating a class that exposes Row, Column, and Value properties, and binding to a collection of these.  This lets you assign row and column positions using the method of your choice, and layout in a grid is very straightforward (once you understand how ItemsControl uses its ItemsPanel and ItemContainerStyle properties, of course):

      <ItemsControl ItemsSource="{Binding Checkboxes}">
        <ItemsControl.ItemTemplate>
          <DataTemplate>
            <CheckBox IsChecked="{Binding Value, Mode=TwoWay}"/>
          </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
          <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
              <ColumnDefinition Width="20"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
              <RowDefinition Height="20"/>
            </Grid.RowDefinitions>
            </Grid>
          </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
          <Style TargetType="ContentPresenter">
            <Setter Property="Grid.Row" Value="{Binding Row}"/>
            <Setter Property="Grid.Column" Value="{Binding Column}"/>
          </Style>
        </ItemsControl.ItemContainerStyle>
      </ItemsControl>


问:
How does one convert the following hashMap<String, String> to a usable JS object?
Long story short.

I'm being given a hashMap from our back end team that has the following output.

{12=Other Services (Assisted), 2=Other Services, 4=Collect, 17=Get New (For Me), 19=Get New (For My Business)}

I'm a front end develop and have never worked with a string like this. I'm unable to split it using jquery.split() because of the '='

Searching online I found a lot of answers to my question but can't get it to work, if it is in fact the correct answer to my question.

Below is what I've tried. ${departmentHash} is an example. My actual code won't make a difference I suppose.

How to iterate HashMap using JSTL forEach loop?

```<code><c:forEach var="department" items="${departmentHash}">
    Country: ${department.key}  - Capital: ${department.value}
</c:forEach>
</code>```

The above didn't return anything in to ${department}

Other links had similar answers that I could not get to work.

How to loop through a HashMap in JSP?

How to iterate an ArrayList inside a HashMap using JSTL?

I might be wording my question wrong so if anyone has a correct link for me or an answer to my question it would be much appreciated.

答:
Parsing the string that you have provided wont work because of integers(12,2,4, etc) in the key section.

If you are getting the hashmap data in the form of a string, the you could try something like the following in javascript:

```<code>var str = '{12=Other Services (Assisted), 2=Other Services, 4=Collect, 17=Get New (For Me), 19=Get New (For My Business)}';

str = str.replace('{','');
str = str.replace('}','');// these lines will remove the leading and trailing braces

var arr = str.split(','); // this will give you an array of strings with each index in the format "12=Other Services (Assisted)"

arr.forEach(function(item){
    // here you can split again with '=' and do what is required
    var s = item.split('=');
    var obj = {key: s[0], value:s[1]}; // this is up to your implementation

})
</code>```

Body:
Long story short.

I'm being given a hashMap from our back end team that has the following output.

{12=Other Services (Assisted), 2=Other Services, 4=Collect, 17=Get New (For Me), 19=Get New (For My Business)}

I'm a front end develop and have never worked with a string like this. I'm unable to split it using jquery.split() because of the '='

Searching online I found a lot of answers to my question but can't get it to work, if it is in fact the correct answer to my question.

Below is what I've tried. ${departmentHash} is an example. My actual code won't make a difference I suppose.

How to iterate HashMap using JSTL forEach loop?

<c:forEach var="department" items="${departmentHash}">
    Country: ${department.key}  - Capital: ${department.value}
</c:forEach>

The above didn't return anything in to ${department}

Other links had similar answers that I could not get to work.

How to loop through a HashMap in JSP?

How to iterate an ArrayList inside a HashMap using JSTL?

I might be wording my question wrong so if anyone has a correct link for me or an answer to my question it would be much appreciated.

Body:
Parsing the string that you have provided wont work because of integers(12,2,4, etc) in the key section.

If you are getting the hashmap data in the form of a string, the you could try something like the following in javascript:

var str = '{12=Other Services (Assisted), 2=Other Services, 4=Collect, 17=Get New (For Me), 19=Get New (For My Business)}';

str = str.replace('{','');
str = str.replace('}','');// these lines will remove the leading and trailing braces

var arr = str.split(','); // this will give you an array of strings with each index in the format "12=Other Services (Assisted)"

arr.forEach(function(item){
    // here you can split again with '=' and do what is required
    var s = item.split('=');
    var obj = {key: s[0], value:s[1]}; // this is up to your implementation

})


问:
How to get hls video width/height in javascript?
I use video tag to play HLS video, and the video size is 0 always.

```<code><video id=video src="http://xxx.m3u8" autoplay controls/>
<script>
    const video = document.getElementById('video')
    video.addEventListener('play', () => {
        console.log(video.videoWidth, video.videoHeight)
        // both are 0
    })
</script>
</code>```

答:
Currently desktop browsers do not support playing an HLS video directly using just the video tag. (Maybe it does work on Safari or IOS).

To reproduce an HLS stream you need to use one of the video players available. You have some open source projects, like hlsjs: https://github.com/video-dev/hls.js. Or comercial players like flowplayer, or jwplayer.

Basic html code using hlsjs player:

```<code><script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  if(Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
</script>
</code>```

Body:
I use video tag to play HLS video, and the video size is 0 always.

<video id=video src="http://xxx.m3u8" autoplay controls/>

Body:
Currently desktop browsers do not support playing an HLS video directly using just the video tag. (Maybe it does work on Safari or IOS).

To reproduce an HLS stream you need to use one of the video players available. You have some open source projects, like hlsjs: https://github.com/video-dev/hls.js. Or comercial players like flowplayer, or jwplayer.

Basic html code using hlsjs player:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video"></video>
<script>
  if(Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play();
  });
 }
</script>


问:
Support vector machine overfitting my data
I am trying to make predictions for the iris dataset. I have decided to use svms for this purpose. But, it gives me an accuracy 1.0. Is it a case of overfitting or is it because the model is very good? Here is my code.

```<code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
svm_model = svm.SVC(kernel='linear', C=1,gamma='auto')
svm_model.fit(X_train,y_train)
predictions = svm_model.predict(X_test)
accuracy_score(predictions, y_test)
</code>```

Here, accuracy_score returns a value of 1. Please help me. I am a beginner in machine learning.

答:
The iris dataset is not a particularly difficult one from where to get good results. However, you are right not trusting a 100% classification accuracy model. In your example, the problem is that the 30 test points are all correctly well classified. But that doesn't mean that your model is able to generalise well for all new data instances. Just try and change the test_size to 0.3 and the results are no longer 100% (it goes down to 97.78%).

The best way to guarantee robustness and avoid overfitting is using cross validation. An example on how to do this easily from your example:

```<code>from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

iris = datasets.load_iris()
X = iris.data[:, :4]
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

svm_model = svm.SVC(kernel='linear', C=1, gamma='auto')
scores = cross_val_score(svm_model, iris.data, iris.target, cv=10) #10 fold cross validation
</code>```

Here cross_val_score uses different parts of the dataset as testing data iteratively (cross validation) while keeping all your previous parameters. If you check score you will see that the 10 accuracies calculated now range from 87.87% to 100%. To report the final model performance you can for example use the mean of the scored values.

Hope this helps and good luck! :)

Body:
I am trying to make predictions for the iris dataset. I have decided to use svms for this purpose. But, it gives me an accuracy 1.0. Is it a case of overfitting or is it because the model is very good? Here is my code.

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
svm_model = svm.SVC(kernel='linear', C=1,gamma='auto')
svm_model.fit(X_train,y_train)
predictions = svm_model.predict(X_test)
accuracy_score(predictions, y_test)

Here, accuracy_score returns a value of 1. Please help me. I am a beginner in machine learning.

Body:
The iris dataset is not a particularly difficult one from where to get good results. However, you are right not trusting a 100% classification accuracy model. In your example, the problem is that the 30 test points are all correctly well classified. But that doesn't mean that your model is able to generalise well for all new data instances. Just try and change the test_size to 0.3 and the results are no longer 100% (it goes down to 97.78%).

The best way to guarantee robustness and avoid overfitting is using cross validation. An example on how to do this easily from your example:

from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

iris = datasets.load_iris()
X = iris.data[:, :4]
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

svm_model = svm.SVC(kernel='linear', C=1, gamma='auto')
scores = cross_val_score(svm_model, iris.data, iris.target, cv=10) #10 fold cross validation

Here cross_val_score uses different parts of the dataset as testing data iteratively (cross validation) while keeping all your previous parameters. If you check score you will see that the 10 accuracies calculated now range from 87.87% to 100%. To report the final model performance you can for example use the mean of the scored values.

Hope this helps and good luck! :)


问:
Xpath for a div specifying a class and just one style attribute
I want to write an xpath to identify a div which has the class foo and the display: block. I wrote

```<code>div[@class="foo" and @style="*display: block*"]
</code>```

but it doesn't work. Is it correct to use and? is it correct to use asterisks like in regex expressions?

答:
your xpath is searching for @style="*display: block*", it means totally equal to value inside quotes. Use contains() instead,
Fyi: there's also starts-with() method

```<code>//div[@class='foo'][contains(@style,'display: block')]
</code>```

There's an issue with using such locator, as sometimes element is visible, though there's no style display:block. So you can use similar locator, but instead of containing block, searche for not-containing "none" (as in display:none), can try it by adding this to main locator [not(contains(@style, 'none'))]. Just remember about such option)

Body:
I want to write an xpath to identify a div which has the class foo and the display: block. I wrote

div[@class="foo" and @style="*display: block*"]

but it doesn't work. Is it correct to use and? is it correct to use asterisks like in regex expressions?

Body:
your xpath is searching for @style="*display: block*", it means totally equal to value inside quotes. Use contains() instead,
Fyi: there's also starts-with() method

//div[@class='foo'][contains(@style,'display: block')]

There's an issue with using such locator, as sometimes element is visible, though there's no style display:block. So you can use similar locator, but instead of containing block, searche for not-containing "none" (as in display:none), can try it by adding this to main locator [not(contains(@style, 'none'))]. Just remember about such option)


问:
What is the return type for JPA query method when query result is not a class?
I have this query in JPA:

```<code>@Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<Object> top10ProgramsOfTherapies();
</code>```

It works great, but it returns a list of Objects, and I can not get the data out of it. What return type should I use to read the result data?

答:
This query will return a list of objects array: Object[] so you need to change your code like this:

```<code>@Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<Object[]> top10ProgramsOfTherapies();
</code>```

And for each item in the list : item[0] will hold the programID value and item[1] will hold the COUNT(id) value, and you should cast them to their respective types as they will be just objects.

Body:
I have this query in JPA:

@Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<Object> top10ProgramsOfTherapies();

It works great, but it returns a list of Objects, and I can not get the data out of it. What return type should I use to read the result data?

Body:
This query will return a list of objects array: Object[] so you need to change your code like this:

@Query("SELECT programId,COUNT(id) FROM Therapy GROUP BY programId ORDER BY COUNT(id) DESC")
List<Object[]> top10ProgramsOfTherapies();

And for each item in the list : item[0] will hold the programID value and item[1] will hold the COUNT(id) value, and you should cast them to their respective types as they will be just objects.