问:
How to move a Visual Studio Code workspace to a new location painlessly?
I thought VS Code saves all the relevant metadata in .vscode folder and .code-workspace file and as these are contained within the workspace folder I assumed it's all self-contained and shouldn't cause problems when moved. But apparently I was gravely mistaken.

After moving my workspace folder to a new location and altering folder paths saved in .code-workspace file accordingly all my opened editor panes and the bottom panel are gone. What I have now is a nice Welcome window.

I'm aware of what the official guide recommends, but that's only moving .code-worskpace metafile - the folder still stays in place.

答:
I've just run into the same issue. My workspace wasn't saved to a file at all (I just use the "Open with Code" option on each project folder), and the Save Workspace As option didn't help as it just created a JSON file with a couple of empty objects in it (which probably makes sense as I haven't really modified any workspace settings, I just want to preserve my open editors and things like that).

On Windows at least, it seems that those kinds of "workspace" settings are actually stored within subfolders of %APPDATA%\Code\User\workspaceStorage, and an SQLite database file is used to store the actual settings, so this is what I ended up doing:

Move your folder to the new location on disk (close all VS Code windows first)

Open the new folder location with VS Code (you'll just get the Welcome tab at this stage, but we just need it to create a settings storage folder for the new location). Then close VS code again.

Open %APPDATA%\Code\User\workspaceStorage in File Explorer, go into each subfolder and open workspace.json (in any old text editor). In my case at least, it only contains a folder property, which is path of the folder that this settings folder relates to (but just changing this won't help us at all, it was the first thing I tried). Use this to figure out which of these subfolders relate to the old and new paths.

Copy state.vscdb from old to new, and delete state.vscdb.backup in new.

Open state.vscdb in new in some sort of SQLite database file editor (I used DB Browser for SQLite and it worked fine, but there's also SQLiteStudio which looks like it might be better in general).

Run an UPDATE query to update all the paths in the database. They seem to be stored in three different formats/levels of escaping - between folders there can be a forward slash, two backslashes, or four backslashes. In my case I wanted to move my project folder from the root of my Windows user folder into my usual documents folder which is within OneDrive, so my query was along the lines of the following, as I only needed to change the middle section of each path. You might have to do something more complicated if you are moving to a different drive for example (would need to have a look at all the existing paths in the database to see how they are encoded).

```<code>UPDATE `ItemTable` SET `value` = REPLACE(REPLACE(REPLACE(`value`, 'User/Project', 'User/OneDrive/Documents/Project'), 'User\\Project', 'User\\OneDrive\\Documents\\Project'), 'User\\\\Project', 'User\\\\OneDrive\\\\Documents\\\\Project')
</code>```

After saving the database, I just opened the new folder in VS Code, and everything seems to have loaded up exactly as it was in the old location :)

(Also just in case anyone is curious, the subfolder names in workspaceStorage seem to be some sort of hash based on the path, because if you delete the subfolder that relates to a folder you've previously opened in VS Code and then open that folder in Code again, it recreates the same subfolder name. So that means just updating the old workspace.json and database file in-place won't work)

Body:
I've just run into the same issue. My workspace wasn't saved to a file at all (I just use the "Open with Code" option on each project folder), and the Save Workspace As option didn't help as it just created a JSON file with a couple of empty objects in it (which probably makes sense as I haven't really modified any workspace settings, I just want to preserve my open editors and things like that).

On Windows at least, it seems that those kinds of "workspace" settings are actually stored within subfolders of %APPDATA%\Code\User\workspaceStorage, and an SQLite database file is used to store the actual settings, so this is what I ended up doing:

Move your folder to the new location on disk (close all VS Code windows first)

Open the new folder location with VS Code (you'll just get the Welcome tab at this stage, but we just need it to create a settings storage folder for the new location). Then close VS code again.

Open %APPDATA%\Code\User\workspaceStorage in File Explorer, go into each subfolder and open workspace.json (in any old text editor). In my case at least, it only contains a folder property, which is path of the folder that this settings folder relates to (but just changing this won't help us at all, it was the first thing I tried). Use this to figure out which of these subfolders relate to the old and new paths.

Copy state.vscdb from old to new, and delete state.vscdb.backup in new.

Open state.vscdb in new in some sort of SQLite database file editor (I used DB Browser for SQLite and it worked fine, but there's also SQLiteStudio which looks like it might be better in general).

Run an UPDATE query to update all the paths in the database. They seem to be stored in three different formats/levels of escaping - between folders there can be a forward slash, two backslashes, or four backslashes. In my case I wanted to move my project folder from the root of my Windows user folder into my usual documents folder which is within OneDrive, so my query was along the lines of the following, as I only needed to change the middle section of each path. You might have to do something more complicated if you are moving to a different drive for example (would need to have a look at all the existing paths in the database to see how they are encoded).

UPDATE `ItemTable` SET `value` = REPLACE(REPLACE(REPLACE(`value`, 'User/Project', 'User/OneDrive/Documents/Project'), 'User\\Project', 'User\\OneDrive\\Documents\\Project'), 'User\\\\Project', 'User\\\\OneDrive\\\\Documents\\\\Project')

After saving the database, I just opened the new folder in VS Code, and everything seems to have loaded up exactly as it was in the old location :)

(Also just in case anyone is curious, the subfolder names in workspaceStorage seem to be some sort of hash based on the path, because if you delete the subfolder that relates to a folder you've previously opened in VS Code and then open that folder in Code again, it recreates the same subfolder name. So that means just updating the old workspace.json and database file in-place won't work)


来源: stackexchange

问:
how compilers detect overflow in numbers while compiling?
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

```<code>typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}
</code>```

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?

答:
I'm not sure what particular algorithms most compliers employ to do this, but here are a few options that could work:

The compiler could try using an existing library (for example, in C++, a stringstream) to try to convert the string into the number of the appropriate type.  This could then be used to check for errors.

The compiler could convert the string into a very high-precision number format (for example, a 128-bit integer) and then check, whenever an assignment is made from a numeric literal to a primitive type, whether the value could fit in that range without a cast.

ContentLicense: CC BY-SA 3.0

Body:
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255.

My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this case - against type limits?

I made a simple algorithm to do that for type 'int' for decimal, octal, hexadecimal and little endian binary but i don't think compiler do such thing like that to detect overflow in numbers.

the algorithm i made are coded in C++:

typedef signed char int8;
typedef signed int  int32;

#define DEC  0
#define HEX  1
#define OCT  2
#define BIN  3

bool isOverflow(const char* value, int32 base)
{
    // left-most digit for maximum and minimum number
    static const char* max_numbers[4][2] =
    {
        //                 INT_MAX                           INT_MIN
        {                       "2147483647",                       "2147483648" }, // decimal
        {                         "7fffffff",                         "80000000" }, // hexadecimal
        {                      "17777777777",                      "20000000000" }, // octal
        { "01111111111111111111111111111111", "10000000000000000000000000000000" }  // binary
    };

    // size of strings in max_numbers array
    static const int32 number_sizes[] = { 10, 8, 11, 32 };

    // input string size
    int32 str_len = strlen(value);

    // is sign mark exist in input string
    int32 signExist = ((base == DEC || base == OCT) && *value == '-');

    // first non zero digit in input number
    int32 non_zero_index = signExist;

    // locate first non zero index
    while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;

    // if non_zero_index equal length then all digits are zero
    if (non_zero_index == str_len) return false;

    // get number of digits that actually represent the number
    int32 diff = str_len - non_zero_index;

    // if difference less than 10 digits then no overflow will happened
    if (diff < number_sizes[base]) return false;
    // if difference greater than 10 digits then overflow will happened
    if (diff > number_sizes[base]) return true;

    // left digit in input and search strings
    int8 left1 = 0, left2 = 0;

    // if digits equal to 10 then loop over digits from left to right and compare
    for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
    {
        // get input digit
        left1 = value[non_zero_index];
        // get match digit
        left2 = max_numbers[signExist][i];

        // if digits not equal then if left1 is greater overflow will occurred, false otherwise
        if (left1 != left2) return left1 > left2;
    }

    // overflow won't happened
    return false;
}

This algorithm can be optimized to work with all integers types but with float-point i have to make new one to work with IEEE float-point representation.

i think compilers use efficient algorithm to detect overflow other than mine, don't you?


问:
How do I rerun a static integer array?
here's the array I want to rerun:

```<code>public static int[] rollDice(int dice[]) {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }

    return dice;
}
</code>```

If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.

答:
There is no point in returning the array, since you already have a reference to the array when you call the method rollDice().

Arrays are sent by reference and not by value, which means you are not working with a copy like you do with ints, instead you are modifing the original array.

Change the return type to void and remove the return and your code should work as intended.

ContentLicense: CC BY-SA 4.0

Title: How do I rerun a static integer array?

Body:
here's the array I want to rerun:

public static int[] rollDice(int dice[]) {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }

    return dice;
}

If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.


问:
Using Multi-threading for Slow Ms Interop
I have a program that creates two pdf files when a button is clicked. It uses Microsoft office interop in WinForms and the file creation goes like this;

User works on something in the program

Clicks the button

Program creates a word file based on a template that has bookmarks in it

Writes into the bookmarks as well as its table

Saves it as pdf

Closes active documents

Closes the word app

Closes the child form and switches to another one

*the word app is not visible to the user

It works fine on its own, but then it takes up 8 seconds to complete the two files, so I tried using multi-threading so that the user won't have to wait and can work on other things or proceed to step 1 again.

However, it throws various errors; COM, RPC, etc. even in the database connection ones, and I think the reason is that since there are two separate threads that works and it uses the same resources, some point in time the other might have close the resources that the other thread is using / about to use
So I tried using join(), so that the other thread might finish its job first, close its respective resources, then proceeds to the next one.

This works fine, IF, the user does not click the button to create another file right after the other (in a scenario that the user finishes the first step faster than expected)

The join() is sufficient enough to handle the errors as well as to work on the file creations on background, however, I want to deal with the scenario when the file creation is done right after the other, because in this scenarios, it then seems like the process is linear due to the threads waiting for each other, aside from it creates bottlenecks wherein the threads are now in line and blocks the main thread, which makes the user wait for 12 seconds or more.

What I want to know / to be clarified in is that;

Can I create those two files that uses interop use different resources so that it won’t produce errors?

Can I use or is there an alternative to join() wherein it does not block the UI thread or the main thread? So that the file creating threads just line up in background (still waits for each other to finish) without making the user wait.

Did I incorrectly use join() or the threads that ends up eating more time?

Here is my code;

Procedure and public variables in a module for creating the documents:

```<code>Public tsThread As Thread
Public psThread As Thread

Sub SaveDoc(docType,someArgs)
        Dim wordApp = New Word.Application
        Dim templateBookmarks As Word.Bookmarks
        Dim templateName As String
        Dim template As New Word.Document
        wordApp = CreateObject("Word.Application")

        Select Case docType
            Case "Type1"
                templateName = "SampleType.docx"
                template = wordApp.Documents.Add(templatePath & templateName)
                templateBookmarks = template.Bookmarks

                templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"
                template.Tables(1).Cell(msWordRow, 1).Range.Text = "Value in cell 1"
            Case "Type2"
                ‘Same thing, just different values and template
            Case "Type3"
        End select
        template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
        wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
        wordApp.Quit()
End Sub
</code>```

Procedure in the child form when the button is clicked:

```<code>        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        If Not IsNothing(psThread) Then
            If psThread.IsAlive Then
                psThread.Join()
            End If
        End If
        tsThread = New Thread(Sub() SaveDoc(docType1,someArgs))
        tsThread.Start()

        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        psThread = New Thread(Sub() SaveDoc(docType2,someArgs))
        psThread.Start()

        If records = maxRecords Then
            If psThread.IsAlive or tsThread.isAlive Then
                tsThread.Join()
                psThread.Join()
                Dim fooThread = New Thread(Sub() SaveDoc(docType3,someArgs))
                fooThread.Start()
            End If
        End If
   SwitchForm("Child Form for Step 1")
   End Sub
</code>```

The errors i.e. without using the join() are commonly in these parts of code:

wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

or in

wordApp.Quit()

Or in the bookmarks

templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"

Or sometimes anywhere inside one of the cases in different timings or in database connection procedures.

I am still relatively new to multi-threading as well as in Ms Interop so I seek help if I have any misconceptions. The code is in VB but I can understand C# as well. Any help / guidance is greatly appreciated. Thanks!

答:
I would not try to use any word/office interop from more than one thread at a time. In my experience these things are unreliable enough as it is, without introducing possible concurrency issues. But this might depend on what exactly you are doing.

Thread and join are rather old-school way to handle multiple threads. The newer method is to use Tasks and async/await. This may help to enforce a consistent ordering, without blocking the main-thread.

You should typically avoid any method that can block when executing from the main thread, including .Join().

I would consider using producer/consumer pattern. The main thread would produce documents to process when the user clicks a button, while the background thread would consume the documents and do the processing. A blocking collection can typically be used as the interface between the two threads.

Another alternative is a limited concurrency task scheduler. This lets you schedule tasks to do the processing, while ensuring only one (or some other limit) are processed concurrently.

Body:
I have a program that creates two pdf files when a button is clicked. It uses Microsoft office interop in WinForms and the file creation goes like this;

User works on something in the program

Clicks the button

Program creates a word file based on a template that has bookmarks in it

Writes into the bookmarks as well as its table

Saves it as pdf

Closes active documents

Closes the word app

Closes the child form and switches to another one

*the word app is not visible to the user

It works fine on its own, but then it takes up 8 seconds to complete the two files, so I tried using multi-threading so that the user won't have to wait and can work on other things or proceed to step 1 again.

However, it throws various errors; COM, RPC, etc. even in the database connection ones, and I think the reason is that since there are two separate threads that works and it uses the same resources, some point in time the other might have close the resources that the other thread is using / about to use
So I tried using join(), so that the other thread might finish its job first, close its respective resources, then proceeds to the next one.

This works fine, IF, the user does not click the button to create another file right after the other (in a scenario that the user finishes the first step faster than expected)

The join() is sufficient enough to handle the errors as well as to work on the file creations on background, however, I want to deal with the scenario when the file creation is done right after the other, because in this scenarios, it then seems like the process is linear due to the threads waiting for each other, aside from it creates bottlenecks wherein the threads are now in line and blocks the main thread, which makes the user wait for 12 seconds or more.

What I want to know / to be clarified in is that;

Can I create those two files that uses interop use different resources so that it won’t produce errors?

Can I use or is there an alternative to join() wherein it does not block the UI thread or the main thread? So that the file creating threads just line up in background (still waits for each other to finish) without making the user wait.

Did I incorrectly use join() or the threads that ends up eating more time?

Here is my code;

Procedure and public variables in a module for creating the documents:

Public tsThread As Thread
Public psThread As Thread

Sub SaveDoc(docType,someArgs)
        Dim wordApp = New Word.Application
        Dim templateBookmarks As Word.Bookmarks
        Dim templateName As String
        Dim template As New Word.Document
        wordApp = CreateObject("Word.Application")

        Select Case docType
            Case "Type1"
                templateName = "SampleType.docx"
                template = wordApp.Documents.Add(templatePath & templateName)
                templateBookmarks = template.Bookmarks

                templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"
                template.Tables(1).Cell(msWordRow, 1).Range.Text = "Value in cell 1"
            Case "Type2"
                ‘Same thing, just different values and template
            Case "Type3"
        End select
        template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
        wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
        wordApp.Quit()
End Sub

Procedure in the child form when the button is clicked:

        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        If Not IsNothing(psThread) Then
            If psThread.IsAlive Then
                psThread.Join()
            End If
        End If
        tsThread = New Thread(Sub() SaveDoc(docType1,someArgs))
        tsThread.Start()

        If Not IsNothing(tsThread) Then
            If tsThread.IsAlive Then
                tsThread.Join()
            End If
        End If
        psThread = New Thread(Sub() SaveDoc(docType2,someArgs))
        psThread.Start()

        If records = maxRecords Then
            If psThread.IsAlive or tsThread.isAlive Then
                tsThread.Join()
                psThread.Join()
                Dim fooThread = New Thread(Sub() SaveDoc(docType3,someArgs))
                fooThread.Start()
            End If
        End If
   SwitchForm("Child Form for Step 1")
   End Sub

The errors i.e. without using the join() are commonly in these parts of code:

wordApp.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

or in

wordApp.Quit()

Or in the bookmarks

templateBookmarks.Item("bookmarkInWord").Range.Text = "Foo"

Or sometimes anywhere inside one of the cases in different timings or in database connection procedures.

I am still relatively new to multi-threading as well as in Ms Interop so I seek help if I have any misconceptions. The code is in VB but I can understand C# as well. Any help / guidance is greatly appreciated. Thanks!


问:
Angular - boolean value doesn't change
I'm facing issue with my app.
I'm trying to create a list of checkboxes, when the checkbox is clicked the value should be true and when clicked again the value should be false. Simple.

Here is my html

```<code>  <li *ngFor="let checkbox of checkboxSelect">
      <div class="checkbox-style">
          <input type="checkbox" name ="{{checkbox.inputName}}"
                [checked]="checkbox.name"
                (change)="checkbox.name= !checkbox.name"/>
             <div class="state">
                 <label>{{checkbox.label}}</label>
             </div>
      </div>
  </li>
</code>```

Here is my component.ts

```<code>showFirstName = true;
showLastName = true;

checkboxSelect: any[] = [{
        label: 'First name',
        name: this.showFirstName,
        inputName: 'showFirstName'
    }, {
        label: 'Last name',
        name: this.showLastName,
        inputName: 'showLastName'

    },
];
</code>```

Everything is working except my 'name' value doesn't change to true/false when clicked.

On the other hand when I put that straight to html without *ngFor it's working

```<code>  <li>
      <div class="checkbox-style">
          <input type="checkbox" name = "firstName"
                [checked]="showFirstName"
                (change)="showFirstName = !showFirstName"/>
             <div class="state">
                 <label>First Name</label>
             </div>
      </div>
  </li>
</code>```

I wasn't so clear, my goal is to display divs depend on true/false

```<code> <div *ngIf="showFirstName" scope="col">First name</div>
<div *ngIf="showLastName" scope="col">Second name</div>
</code>```

But it doesn't change at all.

Does anyone have an idea what's wrong with my code?

答:
Change your html to :- </p>

```<code><li *ngFor="let checkbox of checkboxSelect">
      <div class="checkbox-style">
          <input type="checkbox" [name] ="checkbox.inputName"
                [checked]="checkbox.name"
                (change)="checkbox.name = !checkbox.name"/>
             <div class="state">
                 <label>{{checkbox.label}}</label>
             </div>
      </div>
  </li>
</code>```

Title: Angular - boolean value doesn't change

Body:
I'm facing issue with my app.
I'm trying to create a list of checkboxes, when the checkbox is clicked the value should be true and when clicked again the value should be false. Simple.

Here is my html

          <input type="checkbox" name ="{{checkbox.inputName}}"
                [checked]="checkbox.name"
                (change)="checkbox.name= !checkbox.name"/>

                 {{checkbox.label}}

Here is my component.ts

showFirstName = true;
showLastName = true;

checkboxSelect: any[] = [{
        label: 'First name',
        name: this.showFirstName,
        inputName: 'showFirstName'
    }, {
        label: 'Last name',
        name: this.showLastName,
        inputName: 'showLastName'

    },
];

Everything is working except my 'name' value doesn't change to true/false when clicked.

On the other hand when I put that straight to html without *ngFor it's working

          <input type="checkbox" name = "firstName"
                [checked]="showFirstName"
                (change)="showFirstName = !showFirstName"/>

                 First Name

I wasn't so clear, my goal is to display divs depend on true/false

First name

Second name

But it doesn't change at all.

Does anyone have an idea what's wrong with my code?

Body:
Change your html to :-

<li *ngFor="let checkbox of checkboxSelect">
      <div class="checkbox-style">
          <input type="checkbox" [name] ="checkbox.inputName"
                [checked]="checkbox.name"
                (change)="checkbox.name = !checkbox.name"/>
             <div class="state">
                 <label>{{checkbox.label}}</label>
             </div>
      </div>
  </li>


问:
How to add StumbleUpon and Delicious Scripts to existing images
I have 2 images already, one for StumbleUpon and one for Delicious. Now I want to link it with the necessary script, I have spend a couple of hours now, and can't find the necessary good links.

I only find the ready made scripts, which include their own images etc. To give you an example of what I mean, the site I am working on is this one: http://www.icephoenix.co . I already have those images, I only want to call the script which bookmarks it etc.

答:
The links as you've shown there shouldn't really use an  tag - you should be setting the icon image as a background to the  element with CSS. Here's an example: http://jsfiddle.net/H5V3m/

It should be very simple to attach the ready-made scripts to the  element. Why don't you post a link to those scripts so we can take a look?

Body:
The links as you've shown there shouldn't really use an <img> tag - you should be setting the icon image as a background to the <a> element with CSS. Here's an example: http://jsfiddle.net/H5V3m/

It should be very simple to attach the ready-made scripts to the <a> element. Why don't you post a link to those scripts so we can take a look?


问:
How to add this if statement to a template with Django and improve the views.py
My knowledge of html and Django is very limited but I have this Django project with multiple (12) HTML pages that display information in a table similar to the code below. The table is conditionally displayed if there are any fixes left to make. If any of the data in the fixes was already tested it should be highlighted in red to avoid editing. I recently added the
 bit to do the highlighting but it felt really dumb to have to add it manually to all 12 pages. Is there a way that I can add it as part of an external template?

```<code>{% extends "admin/base_site.html" %}
{% load static %}

{% block content %}

<p><b>Description:</b> {{ docstring }}</p>
{% if count|length %}
    <p><b>Action:</b> Investigate why and fix.</p>
    <p style="color:red">If any table rows are highlighted red, indicating a tested profile, flag immediately to health report owner/Automation before editing.</p>
    <table>
      <tr bgcolor="#ccc">
        <th>Profile</th>
        <th>Name</th>
        <th>Type</th>
        <th>Tested</th>
        <th>e.g. Device</th>
      </tr>
    {% for p in count %}
      <tr {% if p.tested in green_tested %} bgcolor="red" {% endif %}>
        <td><a href={{ p.profile_url }}>{{ p.url }}</a></td>
        <td>{{ p.name }}</td>
        <td>{{ p.type }}</td>
        <td>{{ p.tested }}</td>
        <td><a href={{ p.device_url }}>{{ p.dev_id }}</a></td>
    {% endfor %}
      </tr>
    </table>
{% else %}
No fixes left to make!
{% endif %}

{% endblock %}
</code>```

My function in the views.py looks something like this:

```<code>def test_function(request):
    count = test_function_count()
    context = {'count': count,
                'green_tested': list(map(lambda x: x[0], models.GREEN_TESTED)),
                'docstring': test_function_count.__doc__}
    return render(request, 'health_report/test-function-page.html', context)
</code>```

It would also be nice to not have to add the 'green_tested' to all my functions in views.

答:
For the problem with green_tested in every view, I suggest using a context processor.
First You have to create a new file context_processors.py, in the same location where your view.py is. Sth like that:

```<code>def function_name(request):
    data = # here put logic you want
    return {
        'context_data': data
    }
</code>```

Then You need to register your context processor in settings.py file in TEMPLATES. The pattern is: YourAppName.FileName.FunctionName
Example here (I don't replace YourAppName because I don't know it):

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['YourAppName/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

                # Here is new line
                'YourAppName.context_processor.function_name',
            ],
        },
    },
]
</code>```

Then You can in any template use {{ context_data }}, name of the key in the dictionary returned by the function.

For the primary problem, I have only a suggestion. You could create some kind of parent template, like your "base_site.html". Something between base_site.html and current template. But the line You want to place is somewhere in the middle so I'm not sure if that is gonna work for You or how these templates are similar to each other. It could make more problem than putting that line 12 times.

```<code>{% extends "admin/base_site.html" %}
{% load static %}

{% block content1 %}
{% endblock %}

 Here the code you want in each template.

{% block content2 %}
{% endblock %}
</code>```

Body:
My knowledge of html and Django is very limited but I have this Django project with multiple (12) HTML pages that display information in a table similar to the code below. The table is conditionally displayed if there are any fixes left to make. If any of the data in the fixes was already tested it should be highlighted in red to avoid editing. I recently added the
 bit to do the highlighting but it felt really dumb to have to add it manually to all 12 pages. Is there a way that I can add it as part of an external template?

{% extends "admin/base_site.html" %}
{% load static %}

{% block content %}

Description: {{ docstring }}

{% if count|length %}

Action: Investigate why and fix.

If any table rows are highlighted red, indicating a tested profile, flag immediately to health report owner/Automation before editing.

        Profile
        Name
        Type
        Tested
        e.g. Device

    {% for p in count %}

        {{ p.url }}
        {{ p.name }}
        {{ p.type }}
        {{ p.tested }}
        {{ p.dev_id }}
    {% endfor %}

{% else %}
No fixes left to make!
{% endif %}

{% endblock %}

My function in the views.py looks something like this:

def test_function(request):
    count = test_function_count()
    context = {'count': count,
                'green_tested': list(map(lambda x: x[0], models.GREEN_TESTED)),
                'docstring': test_function_count.__doc__}
    return render(request, 'health_report/test-function-page.html', context)

It would also be nice to not have to add the 'green_tested' to all my functions in views.

Body:
For the problem with green_tested in every view, I suggest using a context processor.
First You have to create a new file context_processors.py, in the same location where your view.py is. Sth like that:

def function_name(request):
    data = # here put logic you want
    return {
        'context_data': data
    }

Then You need to register your context processor in settings.py file in TEMPLATES. The pattern is: YourAppName.FileName.FunctionName
Example here (I don't replace YourAppName because I don't know it):

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['YourAppName/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

                # Here is new line
                'YourAppName.context_processor.function_name',
            ],
        },
    },
]

Then You can in any template use {{ context_data }}, name of the key in the dictionary returned by the function.

For the primary problem, I have only a suggestion. You could create some kind of parent template, like your "base_site.html". Something between base_site.html and current template. But the line You want to place is somewhere in the middle so I'm not sure if that is gonna work for You or how these templates are similar to each other. It could make more problem than putting that line 12 times.

{% extends "admin/base_site.html" %}
{% load static %}

{% block content1 %}
{% endblock %}

 Here the code you want in each template.

{% block content2 %}
{% endblock %}


问:
TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds
I'm getting this error after upgrading to angular 9. I'm using visual studio 2019, ASP .NET core with angular. Even if I create new project and update angular to 9 version, It stops working.

Complete list of page response is :

TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds. Check the log output for error information. Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, string message) Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s) Microsoft.AspNetCore.Builder.SpaProxyingExtensions+<>c__DisplayClass2_0+<b__0>d.MoveNext() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

My package.json is:

```<code>{
  "name": "webapplication10",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "build:ssr": "ng run WebApplication10:server:dev",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "9.0.0",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "9.0.0",
    "@angular/compiler": "9.0.0",
    "@angular/core": "9.0.0",
    "@angular/forms": "9.0.0",
    "@angular/material": "~9.0.0",
    "@angular/platform-browser": "9.0.0",
    "@angular/platform-browser-dynamic": "9.0.0",
    "@angular/platform-server": "9.0.0",
    "@angular/router": "9.0.0",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "aspnet-prerendering": "^3.0.1",
    "bootstrap": "^4.4.1",
    "core-js": "^3.6.4",
    "jquery": "3.4.1",
    "oidc-client": "^1.10.1",
    "popper.js": "^1.16.1",
    "rxjs": "^6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.900.1",
    "@angular/cli": "9.0.1",
    "@angular/compiler-cli": "9.0.0",
    "@angular/language-service": "9.0.0",
    "@types/jasmine": "^3.5.3",
    "@types/jasminewd2": "~2.0.8",
    "@types/node": "^12.12.27",
    "codelyzer": "^5.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~3.1.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "typescript": "3.7.5"
  },
  "optionalDependencies": {
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "ts-node": "~8.4.1",
    "tslint": "~5.20.0"
  }
}
```
```

答:
I resolved it by changing:

```<code>"scripts": {
        "start": "ng serve",
</code>```

to:

```<code> "scripts": {
        "start": "echo Starting... && ng serve",
</code>```

in package.json

Body:
I'm getting this error after upgrading to angular 9. I'm using visual studio 2019, ASP .NET core with angular. Even if I create new project and update angular to 9 version, It stops working.

Complete list of page response is :

TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds. Check the log output for error information. Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, string message) Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s) Microsoft.AspNetCore.Builder.SpaProxyingExtensions+<>c__DisplayClass2_0+<b__0>d.MoveNext() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

My package.json is:

{
  "name": "webapplication10",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "build:ssr": "ng run WebApplication10:server:dev",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "9.0.0",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "9.0.0",
    "@angular/compiler": "9.0.0",
    "@angular/core": "9.0.0",
    "@angular/forms": "9.0.0",
    "@angular/material": "~9.0.0",
    "@angular/platform-browser": "9.0.0",
    "@angular/platform-browser-dynamic": "9.0.0",
    "@angular/platform-server": "9.0.0",
    "@angular/router": "9.0.0",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "aspnet-prerendering": "^3.0.1",
    "bootstrap": "^4.4.1",
    "core-js": "^3.6.4",
    "jquery": "3.4.1",
    "oidc-client": "^1.10.1",
    "popper.js": "^1.16.1",
    "rxjs": "^6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.900.1",
    "@angular/cli": "9.0.1",
    "@angular/compiler-cli": "9.0.0",
    "@angular/language-service": "9.0.0",
    "@types/jasmine": "^3.5.3",
    "@types/jasminewd2": "~2.0.8",
    "@types/node": "^12.12.27",
    "codelyzer": "^5.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~3.1.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "typescript": "3.7.5"
  },
  "optionalDependencies": {
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "ts-node": "~8.4.1",
    "tslint": "~5.20.0"
  }
}
```

Body:
I resolved it by changing:

"scripts": {
        "start": "ng serve",

to:

 "scripts": {
        "start": "echo Starting... && ng serve",

in package.json


问:
How to filter specific paths in neo4j?
I have a graph db that maps out the relations between source files. I have the following query which finds all files that are calling the methods defined in the given source file.

```<code>MATCH (sourceFile:JSSourceFile {filename: 'test.js'})-[:Defines]->(sourceMethod:Method)
<-[:Calls*1..5]-
(callerMethod:Method)<-[:Defines]-(callerFile:TSSourceFile)
RETURN sourceFile.fileName AS sourceFile, COLLECT(DISTINCT callerFile.fileName) AS callerFile
ORDER BY sourceFile
</code>```

Now I have added another label Utility to some of the existing JSSourceFile nodes. I need to filter out the TSSourceFile whose methods calls the utilityMethods. Doing this to avoid the utility method calls which in turn being called by the TSSoureFiles and end up polluting the results

```<code>(:JSSourceFile)-[:Defines]-(sourceMethods:Methods)<-[:Calls*1..5]-(:Method)<-[:Defines]-(callerMethod:TSSourceFile)
(:JSSourceFile:Utility)-[:Defines]->(utilityMethods:Method)
Need to eliminate this relationship:
(sourceMethods)-[:Calls]->(utilityMethods)<-[:Calls]-(callerMethod)
</code>```

I have tried the following queries but they are running forever on depth 2+ and I need depth in range of 1..5.

```<code>MATCH (:JSSourceFile:Utility)-[:Defines]->(utilityMethods:Method)
WITH DISTINCT (:TSSourceFile)-[:Defines]->(:Method)-[:Calls]->(utilityMethods) AS utilityCallerFile
MATCH
results=((sourceFile:JSSourceFile {fileName:"test.js"})-[:Defines]->(:Method)
<-[:Calls]-
(callerSub:Method)<-[:Defines]-(callerFile:TSSourceFile))
WITH DISTINCT [result IN nodes(results) WHERE "TSSourceFile" IN labels(result)] as results, sourceFile.fileName AS sourceFile, utilityCallerFile AS utilityCallerFile
RETURN sourceFile, COLLECT(DISTINCT [result IN results WHERE NOT(result IN utilityCallerFile) | result.fileName]) AS callerFile
ORDER BY sourceFile
</code>```

```<code>MATCH
(sourceFile:JSSourceFile {fileName:"test.js"})-[:Defines]->(:Method)
<-[:Calls*1..3]-
(callerMethod:Method)<-[:Defines]-(callerFile:TSSourceFile)
WHERE NOT EXISTS((callerMethod)-[:Calls]->(sourceFile:Utility))
RETURN sourceFile.fileName, collect(DISTINCT callerFile.fileName)
</code>```

I'm a beginner in neo4j and any guidance would be really helpful.

答:
I feel I may be oversimplifying your problem but if just want to exclude the :JSSourceFile nodes that also have the :Utility label then I believe this modification of your first query will work:

```<code>MATCH (sourceFile:JSSourceFile)-[:Defines]->(sourceMethod:Method)<-[:Calls*1..5]-(callerMethod:Method)<-[:Defines]-(callerFile:TSSourceFile)
WHERE NOT sourceFile:Utility
RETURN sourceFile.fileName AS sourceFile, COLLECT(DISTINCT callerFile.fileName) AS callerFile
ORDER BY sourceFile
</code>```

I added the WHERE NOT clause to strip out the :Utility nodes.

Title: How to filter specific paths in neo4j?

Body:
I have a graph db that maps out the relations between source files. I have the following query which finds all files that are calling the methods defined in the given source file.

MATCH (sourceFile:JSSourceFile {filename: 'test.js'})-[:Defines]->(sourceMethod:Method)
<-[:Calls*1..5]-
(callerMethod:Method)<-[:Defines]-(callerFile:TSSourceFile)
RETURN sourceFile.fileName AS sourceFile, COLLECT(DISTINCT callerFile.fileName) AS callerFile
ORDER BY sourceFile

Now I have added another label Utility to some of the existing JSSourceFile nodes. I need to filter out the TSSourceFile whose methods calls the utilityMethods. Doing this to avoid the utility method calls which in turn being called by the TSSoureFiles and end up polluting the results

(:JSSourceFile)-[:Defines]-(sourceMethods:Methods)<-[:Calls*1..5]-(:Method)<-[:Defines]-(callerMethod:TSSourceFile)
(:JSSourceFile:Utility)-[:Defines]->(utilityMethods:Method)
Need to eliminate this relationship:
(sourceMethods)-[:Calls]->(utilityMethods)<-[:Calls]-(callerMethod)

I have tried the following queries but they are running forever on depth 2+ and I need depth in range of 1..5.

MATCH (:JSSourceFile:Utility)-[:Defines]->(utilityMethods:Method)
WITH DISTINCT (:TSSourceFile)-[:Defines]->(:Method)-[:Calls]->(utilityMethods) AS utilityCallerFile
MATCH
results=((sourceFile:JSSourceFile {fileName:"test.js"})-[:Defines]->(:Method)
<-[:Calls]-
(callerSub:Method)<-[:Defines]-(callerFile:TSSourceFile))
WITH DISTINCT [result IN nodes(results) WHERE "TSSourceFile" IN labels(result)] as results, sourceFile.fileName AS sourceFile, utilityCallerFile AS utilityCallerFile
RETURN sourceFile, COLLECT(DISTINCT [result IN results WHERE NOT(result IN utilityCallerFile) | result.fileName]) AS callerFile
ORDER BY sourceFile

MATCH
(sourceFile:JSSourceFile {fileName:"test.js"})-[:Defines]->(:Method)
<-[:Calls*1..3]-
(callerMethod:Method)<-[:Defines]-(callerFile:TSSourceFile)
WHERE NOT EXISTS((callerMethod)-[:Calls]->(sourceFile:Utility))
RETURN sourceFile.fileName, collect(DISTINCT callerFile.fileName)

I'm a beginner in neo4j and any guidance would be really helpful.

Body:
I feel I may be oversimplifying your problem but if just want to exclude the :JSSourceFile nodes that also have the :Utility label then I believe this modification of your first query will work:

MATCH (sourceFile:JSSourceFile)-[:Defines]->(sourceMethod:Method)<-[:Calls*1..5]-(callerMethod:Method)<-[:Defines]-(callerFile:TSSourceFile)
WHERE NOT sourceFile:Utility
RETURN sourceFile.fileName AS sourceFile, COLLECT(DISTINCT callerFile.fileName) AS callerFile
ORDER BY sourceFile

I added the WHERE NOT clause to strip out the :Utility nodes.


问:
Room exception on table: Pre-packaged database has an invalid schema
my task is to migrate the current architecture of our app (using Cupboard) to Room and I am encountering some issues on the very first piece of work, which is migrating the database objects, written in Java for now (Cupboard only supports Java), to make them work with Room. This is an example:

```<code>public class ItemDb {

public Long _id;
public String type;
public String subtype;
public long scheduledTime;
public int iteration;
public String data1;
public String data2;
public String data3;
</code>```

and this is how it looks like in the database:

What I've done with this entity is creating an @Entity class in Kotlin to be used in Room and it looks like this:

```<code>@Entity(tableName = "ItemDb")
data class ItemDb(
        @PrimaryKey(autoGenerate = true)
        val _id: Long? = 0,
        val type: String,
        val subtype: String,
        val scheduledTime: Long,
        val iteration: Int,
        val data1: String? = null,
        val data2: String? = null,
        val data3: String? = null
)
</code>```

Whenever I try to query the database I get this exception:

Pre-packaged database has an invalid schema: ItemDb(com.example.room.model.items.ItemDb).
       Expected:
      TableInfo{name='ItemDb', columns={scheduledTime=Column{name='scheduledTime', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, subtype=Column{name='subtype', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, data3=Column{name='data3', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data2=Column{name='data2', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data1=Column{name='data1', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, iteration=Column{name='iteration', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, _id=Column{name='_id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, type=Column{name='type', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}
       Found:
      TableInfo{name='ItemDb', columns={scheduledTime=Column{name='scheduledTime', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, subtype=Column{name='subtype', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data3=Column{name='data3', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data2=Column{name='data2', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data1=Column{name='data1', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, iteration=Column{name='iteration', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, _id=Column{name='_id', type='integer', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, type=Column{name='type', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}

By comparing the twos I can see that some fields are expected to be marked notNull but they seem to be marked nullable instead even though the Kotlin class is declaring the fields as notNull by avoid using the nullable ?.

What am I doing wrong?
If you need more information regarding the architecture of the Database I can provide them easily. Thanks!

答:
In the error message, the "expected" schema is what Room created from your Kotlin declaration of ItemDb.  It correctly shows type, subType, scheduledTime and iteration as non-null columns, with all others nullable.

I've not used Cupboard and am presuming it creates a database from your ItemDb Java declaration.  The "found" schema, which reports the schema for the prepackaged Cupboard database, indicates that when Cupboard created the database, all columns were declared nullable (i.e. without NOT NULL).

To use the prepackaged database, you will need to perform a migration step that will create a new table with NOT NULL specified for the applicable fields. You then need to copy all the rows from the ItemDb table in the prepackaged database to the new table, with some table re-names (see example below).

The create-statement for the new table will be something like this:

```<code>CREATE TABLE new_ItemDb (_id INTEGER PRIMARY KEY AUTOINCREMENT,
    type INTEGER NOT NULL, subType INTEGER NOT NULL, scheduledTime INTEGER NOT NULL,
    iteration INTEGER NOT NULL, data1 TEXT, data2 TEXT, data3 TEXT)
</code>```

The migration operations can be modeled after this example copied from the documentation for migrations:

```<code>// Migration from 2 to 3, Room 2.2.0
val MIGRATION_2_3 = object : Migration(2, 3) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("""
                CREATE TABLE new_Song (
                    id INTEGER PRIMARY KEY NOT NULL,
                    name TEXT,
                    tag TEXT NOT NULL DEFAULT ''
                )
                """.trimIndent())
        database.execSQL("""
                INSERT INTO new_Song (id, name, tag)
                SELECT id, name, tag FROM Song
                """.trimIndent())
        database.execSQL("DROP TABLE Song")
        database.execSQL("ALTER TABLE new_Song RENAME TO Song")
    }
}
</code>```

Before investing the time making the code changes described above, you could confirm my analysis by temporarily changing your Kotlin definition of ItemDb to make all fields nullable, then retrying your use of the prepackaged database.  I would expect the import to succeed.

Body:
my task is to migrate the current architecture of our app (using Cupboard) to Room and I am encountering some issues on the very first piece of work, which is migrating the database objects, written in Java for now (Cupboard only supports Java), to make them work with Room. This is an example:

public class ItemDb {

public Long _id;
public String type;
public String subtype;
public long scheduledTime;
public int iteration;
public String data1;
public String data2;
public String data3;

and this is how it looks like in the database:

What I've done with this entity is creating an @Entity class in Kotlin to be used in Room and it looks like this:

@Entity(tableName = "ItemDb")
data class ItemDb(
        @PrimaryKey(autoGenerate = true)
        val _id: Long? = 0,
        val type: String,
        val subtype: String,
        val scheduledTime: Long,
        val iteration: Int,
        val data1: String? = null,
        val data2: String? = null,
        val data3: String? = null
)

Whenever I try to query the database I get this exception:

Pre-packaged database has an invalid schema: ItemDb(com.example.room.model.items.ItemDb).
       Expected:
      TableInfo{name='ItemDb', columns={scheduledTime=Column{name='scheduledTime', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, subtype=Column{name='subtype', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, data3=Column{name='data3', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data2=Column{name='data2', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data1=Column{name='data1', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, iteration=Column{name='iteration', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, _id=Column{name='_id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, type=Column{name='type', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}
       Found:
      TableInfo{name='ItemDb', columns={scheduledTime=Column{name='scheduledTime', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, subtype=Column{name='subtype', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data3=Column{name='data3', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data2=Column{name='data2', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, data1=Column{name='data1', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, iteration=Column{name='iteration', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, _id=Column{name='_id', type='integer', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, type=Column{name='type', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}

By comparing the twos I can see that some fields are expected to be marked notNull but they seem to be marked nullable instead even though the Kotlin class is declaring the fields as notNull by avoid using the nullable ?.

What am I doing wrong?
If you need more information regarding the architecture of the Database I can provide them easily. Thanks!

Body:
In the error message, the "expected" schema is what Room created from your Kotlin declaration of ItemDb.  It correctly shows type, subType, scheduledTime and iteration as non-null columns, with all others nullable.

I've not used Cupboard and am presuming it creates a database from your ItemDb Java declaration.  The "found" schema, which reports the schema for the prepackaged Cupboard database, indicates that when Cupboard created the database, all columns were declared nullable (i.e. without NOT NULL).

To use the prepackaged database, you will need to perform a migration step that will create a new table with NOT NULL specified for the applicable fields. You then need to copy all the rows from the ItemDb table in the prepackaged database to the new table, with some table re-names (see example below).

The create-statement for the new table will be something like this:

CREATE TABLE new_ItemDb (_id INTEGER PRIMARY KEY AUTOINCREMENT,
    type INTEGER NOT NULL, subType INTEGER NOT NULL, scheduledTime INTEGER NOT NULL,
    iteration INTEGER NOT NULL, data1 TEXT, data2 TEXT, data3 TEXT)

The migration operations can be modeled after this example copied from the documentation for migrations:

// Migration from 2 to 3, Room 2.2.0
val MIGRATION_2_3 = object : Migration(2, 3) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("""
                CREATE TABLE new_Song (
                    id INTEGER PRIMARY KEY NOT NULL,
                    name TEXT,
                    tag TEXT NOT NULL DEFAULT ''
                )
                """.trimIndent())
        database.execSQL("""
                INSERT INTO new_Song (id, name, tag)
                SELECT id, name, tag FROM Song
                """.trimIndent())
        database.execSQL("DROP TABLE Song")
        database.execSQL("ALTER TABLE new_Song RENAME TO Song")
    }
}

Before investing the time making the code changes described above, you could confirm my analysis by temporarily changing your Kotlin definition of ItemDb to make all fields nullable, then retrying your use of the prepackaged database.  I would expect the import to succeed.


问:
Hover over one element to make a different element visible
I have been told that this isn't possible via CSS alone and so have turned to javascript.

Using onmouseover but I cannot get the hidden element to appear. I want it so that when hovering over element with ID #a, element with class .excerpt-box appears and then disappears when the mouse is moved away.

Does anyone know where I am going wrong? Thanks

Here's the code I've written so far:

The CSS includes visibility hidden for .excerpt-box.

 Read more

This is an example excerpt title...

          <img class="excerpts-fi" src="<?php echo BASE_URL . '/assets/images/water.jpg'; ?>" alt="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>function showExcerpt() {
  document.getElementByClass('excerpt-box').style.visibility = 'visible';
}</code>```

答:
Your HTML structure allows to do the same via CSS as well.

.excerpt-box goes right after the .ind-circle and can be targeted via adjacent sibling combinator.

.excerpt-box {
  display: none;
}

.ind-circle:hover + .excerpt-box {
  display: block;
}
```

Body:
I have been told that this isn't possible via CSS alone and so have turned to javascript.

Using onmouseover but I cannot get the hidden element to appear. I want it so that when hovering over element with ID #a, element with class .excerpt-box appears and then disappears when the mouse is moved away.

Does anyone know where I am going wrong? Thanks

Here's the code I've written so far:

The CSS includes visibility hidden for .excerpt-box.

 Read more

This is an example excerpt title...

          <img class="excerpts-fi" src="<?php echo BASE_URL . '/assets/images/water.jpg'; ?>" alt="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

function showExcerpt() {
  document.getElementByClass('excerpt-box').style.visibility = 'visible';
}


问:
How to Adjust the size of graphs in Dash with Python?
The objective is to maximise the pie chart view at each place card. As can be seen in the figure below, the pie chart is small and not properly fit the window of each place card.

OP1 shed some workaround, but I am unable to reproduce it correctly.

Appreciate if someone can shed some light on how to address this problem.

The code to reproduce the above figure is:

```<code>import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import plotly.graph_objs as go

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.config.suppress_callback_exceptions = True

labels = [['monkeys', 'elephants'],
          ['birds', 'dinosaurs'],
          ['unicorns', 'giraffes']]

values = [[50, 40],
          [100, 10],
          [100, 20]]
data = []
for label, value in zip(labels, values):
    data.append(html.Div([dcc.Graph(figure={'data': [go.Pie(labels=label,
                                                            values=value,
                                                            hoverinfo='label+value+percent', textinfo='value'
                                                            )]})
                          ], className='col-sm-4'))

labels_second = [['Human', 'Animal']]
values_second = [[40, 60]]
data_second = []
for label, value in zip(labels_second, values_second):
    data_second.append(html.Div([dcc.Graph(figure={'data': [go.Pie(labels=label,
                                                                   values=value,
                                                                   hoverinfo='label+value+percent', textinfo='value'
                                                                   )]})
                                 ], className='col-sm-4'))

def color_font():
    selected_color = 'yellow'
    style = {'textAlign': 'center', 'background': selected_color}
    return style

def second_row():
    return html.Div(className='four columns div-user-controls',
                    children=[
                        html.H2('Second Row', style=color_font()),
                        html.P('Display data Left')])

def multiple_rows():
    return html.Div(className='rowxxx',
                    children=[
                        second_row(),
                        second_row(),

                        # my_tab(),
                        # html.Div(id='tabs-example-content')
                    ])

def pie_chart_side_by_side():
    return html.Div(data, className='row')

def pie_chart_single():
    return html.Div(data_second, className='row')

def multiple_columns():
    """
    Testing multiple column
    """
    return dbc.Row(
        [
            dbc.Col(multiple_rows(), width=1),
            dbc.Col(pie_chart_single()),
            dbc.Col(pie_chart_side_by_side()),
        ], no_gutters=True,  # Disable spacing between column
    )

app.layout = html.Div(
    children=[
        multiple_columns(),
    ]

)

# Callback for
@app.callback(Output('tabs-example-content', 'children'),
              [Input('tabs-example', 'value')])
def render_content(tab):
    if tab == 'tab-1':
        return html.Div([
            html.H3('Tab content 1')
        ])
    elif tab == 'tab-2':
        return html.Div([
            html.H3('Tab content 2')
        ])
    elif tab == 'tab-3':
        return html.Div([
            html.H3('Tab content 3')
        ])

# Run the app
if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

答:
The parameter style is responsible to adjust the plot size.

For example,

```<code>style={"height": "50%", "width": "40%"}
</code>```

The style can be incorporated as below,

```<code>html.Div(html.Div([dcc.Graph(figure = {'data': [go.Pie(labels=['Human', 'Animal', 'Alien'],
                              values=[40, 59.1, 0.9],
                              title='Trend',
                              showlegend=False,
                              hoverinfo='label+value+percent', textinfo='value')]}
                                        )
                              ], style={"height": "60%", "width": "80%"}))
</code>```

Which produce something like the attachement below;

Body:
The objective is to maximise the pie chart view at each place card. As can be seen in the figure below, the pie chart is small and not properly fit the window of each place card.

OP1 shed some workaround, but I am unable to reproduce it correctly.

Appreciate if someone can shed some light on how to address this problem.

The code to reproduce the above figure is:

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import plotly.graph_objs as go

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.config.suppress_callback_exceptions = True

labels = [['monkeys', 'elephants'],
          ['birds', 'dinosaurs'],
          ['unicorns', 'giraffes']]

values = [[50, 40],
          [100, 10],
          [100, 20]]
data = []
for label, value in zip(labels, values):
    data.append(html.Div([dcc.Graph(figure={'data': [go.Pie(labels=label,
                                                            values=value,
                                                            hoverinfo='label+value+percent', textinfo='value'
                                                            )]})
                          ], className='col-sm-4'))

labels_second = [['Human', 'Animal']]
values_second = [[40, 60]]
data_second = []
for label, value in zip(labels_second, values_second):
    data_second.append(html.Div([dcc.Graph(figure={'data': [go.Pie(labels=label,
                                                                   values=value,
                                                                   hoverinfo='label+value+percent', textinfo='value'
                                                                   )]})
                                 ], className='col-sm-4'))

def color_font():
    selected_color = 'yellow'
    style = {'textAlign': 'center', 'background': selected_color}
    return style

def second_row():
    return html.Div(className='four columns div-user-controls',
                    children=[
                        html.H2('Second Row', style=color_font()),
                        html.P('Display data Left')])

def multiple_rows():
    return html.Div(className='rowxxx',
                    children=[
                        second_row(),
                        second_row(),

                        # my_tab(),
                        # html.Div(id='tabs-example-content')
                    ])

def pie_chart_side_by_side():
    return html.Div(data, className='row')

def pie_chart_single():
    return html.Div(data_second, className='row')

def multiple_columns():
    """
    Testing multiple column
    """
    return dbc.Row(
        [
            dbc.Col(multiple_rows(), width=1),
            dbc.Col(pie_chart_single()),
            dbc.Col(pie_chart_side_by_side()),
        ], no_gutters=True,  # Disable spacing between column
    )

app.layout = html.Div(
    children=[
        multiple_columns(),
    ]

)

# Callback for
@app.callback(Output('tabs-example-content', 'children'),
              [Input('tabs-example', 'value')])
def render_content(tab):
    if tab == 'tab-1':
        return html.Div([
            html.H3('Tab content 1')
        ])
    elif tab == 'tab-2':
        return html.Div([
            html.H3('Tab content 2')
        ])
    elif tab == 'tab-3':
        return html.Div([
            html.H3('Tab content 3')
        ])

# Run the app
if __name__ == '__main__':
    app.run_server(debug=True)

Body:
The parameter style is responsible to adjust the plot size.

For example,

style={"height": "50%", "width": "40%"}

The style can be incorporated as below,

html.Div(html.Div([dcc.Graph(figure = {'data': [go.Pie(labels=['Human', 'Animal', 'Alien'],
                              values=[40, 59.1, 0.9],
                              title='Trend',
                              showlegend=False,
                              hoverinfo='label+value+percent', textinfo='value')]}
                                        )
                              ], style={"height": "60%", "width": "80%"}))

Which produce something like the attachement below;


问:
Android Studio Update: Some conflicts found in installation area (studio.exe | uninstall.exe)
When I start Android Studio, it shows popup regarding new update of 1.1 release. But when I start updating, After downloading all patch files, while restarting, it shows following error:

I searched almost everywhere on Google and Stackoverflow. There are already two questions on so: this and this. But none of them are have any correct answer. I also tried running as administrator, restarting PC, turning off the firewall, uninstalling antivirus. But none of them worked.

I am using windows 7 32-bit. How to solve this problem? Can anyone help?

答: I also had the same error when upgrading from 3.5 to 3.6, I managed to solve this without losing any sdk platforms and virtual machines in avd by installing the latest version of android,First Export the settings and then delete the two folders ".AndroidStudio3.x" in home directory and the "android-studio" in /usr/local or /opt directory, then  download the zip file of latest version of android studio and move the "android-studio" folder to /usr/local or /opt. Now run the /android-studio/bin/studio.sh and import the settings,Now Latest version will be installed.</p>


问:
How to simple test the file download and upload?
I have two api for file download and upload. (/static/{filename} api for downloading, /upload api for uploading) For consistency, it need a test file to ensure the functionality of them two. I check the official fs_test.go, but it is too massive to use, is there a trick way to do it?

答:
Do you need a unit test? If you are supposed to test saving the file you can use a brute force.

Create file

Check if it exists (optional: check the file data)

Delete file


问:
SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified
Well i have a big problem that i'm trying for days to solve but i could not do it, so i need your help. I have a web application in asp.net 4.0 where i implemented custom membership and role providers. When i open the app homepage in it connects to the database and retrieves some information. There is also a login form and when i login it validates the user through the database and redirects me to the reserved pages but than this error appears:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

Description:

An unhandled exception occurred during the execution of the current
  web request. Please review the stack trace for more information about
  the error and where it originated in the code.

Exception Details:

System.Data.SqlClient.SqlException: A network-related or
  instance-specific error occurred while establishing a connection to
  SQL Server. The server was not found or was not accessible. Verify
  that the instance name is correct and that SQL Server is configured to
  allow remote connections. (provider: SQL Network Interfaces, error: 26
  - Error Locating Server/Instance Specified)

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

I tried many things, some solution i found in stackoverflow but nothing worked. Here are my connectionstrings:

```<code><connectionStrings>
  <clear/>
  <remove name="LocalSqlServer"/>
     <add name="LocalSqlServer" connectionString="Data Source=MSSQL2008-1;Initial Catalog=agency;
        Integrated Security=False;User ID=adis_agency;Password=niarda2012;Connect Timeout=180;Encrypt=False;
        Packet Size=4096" providerName="System.Data.SqlClient" />
     <add name="AgencyConn" connectionString="Data Source=MSSQL2008-1;Initial Catalog=agency;
        Integrated Security=False;User ID=adis_agency;Password=niarda2012;Connect Timeout=180;Encrypt=False;
        Packet Size=4096" providerName="System.Data.SqlClient"/>
</connectionStrings>
</code>```

Below are also the membership and role manager web.config section:

```<code><membership defaultProvider="AuthProvider">
  <providers>
    <clear/>
      <add name="AuthProvider" type="AuthenticationProvider" applicationName="~/Reserved/" connectionStringName="AgencyConn"/>
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="MyRoleProvider">
  <providers>
    <clear/>
      <add name="MyRoleProvider" type="RoleAccessProvider" connectionStringName="AgencyConn"/>
  </providers>
</roleManager>
</code>```

Please can anybody help to figure out whats wrong?

答: Had the same issue then I used the connection string without ./ (like DESKTOP-E53DUML instead of this ./DESKTOP-E53DUML)

Body:
Well i have a big problem that i'm trying for days to solve but i could not do it, so i need your help. I have a web application in asp.net 4.0 where i implemented custom membership and role providers. When i open the app homepage in it connects to the database and retrieves some information. There is also a login form and when i login it validates the user through the database and redirects me to the reserved pages but than this error appears:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

Description:

An unhandled exception occurred during the execution of the current
  web request. Please review the stack trace for more information about
  the error and where it originated in the code.

Exception Details:

System.Data.SqlClient.SqlException: A network-related or
  instance-specific error occurred while establishing a connection to
  SQL Server. The server was not found or was not accessible. Verify
  that the instance name is correct and that SQL Server is configured to
  allow remote connections. (provider: SQL Network Interfaces, error: 26
  - Error Locating Server/Instance Specified)

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

I tried many things, some solution i found in stackoverflow but nothing worked. Here are my connectionstrings:

<connectionStrings>
  <clear/>
  <remove name="LocalSqlServer"/>
     <add name="LocalSqlServer" connectionString="Data Source=MSSQL2008-1;Initial Catalog=agency;
        Integrated Security=False;User ID=adis_agency;Password=niarda2012;Connect Timeout=180;Encrypt=False;
        Packet Size=4096" providerName="System.Data.SqlClient" />
     <add name="AgencyConn" connectionString="Data Source=MSSQL2008-1;Initial Catalog=agency;
        Integrated Security=False;User ID=adis_agency;Password=niarda2012;Connect Timeout=180;Encrypt=False;
        Packet Size=4096" providerName="System.Data.SqlClient"/>
</connectionStrings>

Below are also the membership and role manager web.config section:

<membership defaultProvider="AuthProvider">
  <providers>
    <clear/>
      <add name="AuthProvider" type="AuthenticationProvider" applicationName="~/Reserved/" connectionStringName="AgencyConn"/>
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="MyRoleProvider">
  <providers>
    <clear/>
      <add name="MyRoleProvider" type="RoleAccessProvider" connectionStringName="AgencyConn"/>
  </providers>
</roleManager>

Please can anybody help to figure out whats wrong?


问:
Replace Value with the number of times a group of numbers has appeared in the vector up to that point
I have a vector like this of 1s and 0s next to each other.

```<code>vec <- c(1,1,1,0,0,1,1,1,1,0,0,0,1,1,1)

</code>```

I want to replace the 1s with the number the consecutive 1s showed up so the final vector would look like the one below.

```<code>vec1 <- c(1,1,1,0,0,2,2,2,2,0,0,0,3,3,3)

</code>```

I am not sure how to even start with this problem. Any help is appreciated.

答:
One base R option could be:

```<code>cumsum(vec & c(0, head(vec, -1)) == 0) * vec

[1] 1 1 1 0 0 2 2 2 2 0 0 0 3 3 3
</code>```

Body:
I have a vector like this of 1s and 0s next to each other.

vec <- c(1,1,1,0,0,1,1,1,1,0,0,0,1,1,1)

I want to replace the 1s with the number the consecutive 1s showed up so the final vector would look like the one below.

vec1 <- c(1,1,1,0,0,2,2,2,2,0,0,0,3,3,3)

I am not sure how to even start with this problem. Any help is appreciated.

Body:
One base R option could be:

cumsum(vec & c(0, head(vec, -1)) == 0) * vec

[1] 1 1 1 0 0 2 2 2 2 0 0 0 3 3 3


问:
Runtime complexity: sorting 2d array where each row, column and diagonals are sorted?
Given the following 2d array:

```<code>6   8   11  17
9   11  14  20
18  20  23  29
24  26  29  35
</code>```

Each row and column is sorted as well as the diagonals are sorted too (top left to bottom right). Assuming we have n² elements in the array (n = 4 in this case), it is trivial to use quicksort which takes O(n² log(n²)) = O(n² log(n)) to sort the 2d array. My question is can we sort this in O(n²)?

The goal is to use the given semi-sorted 2d array and come-up with a clever solution.

The target output is:

```<code>6   8   9   11
11  14  17  18
20  20  23  24
26  29  29  35
</code>```

答:
Yes, we can sort this in O(n^2) time.

Reduction to sorting a 1D array

Let us first show that this new problem of sorting a 2D array (such that each row, column, and top-left-to-bottom-right diagonal is sorted) can be reduced to the problem of sorting a 1D array of n^2 elements.

Suppose we have a sorted 1D array of n^2 elements. We can trivially rearrange this in to a sorted n x n array by setting the first n numbers as the first row, followed by the next n numbers as the second row, and repeat until we exhaust the array.

Hence, given a 2D array of n^2 numbers, we can transform it into a 1D array in O(n^2) time, sort this array, then transform it back to the desired 2D array in O(n^2) time. Thus, if we can find a sorting algorithm for a 1D array in O(n^2), we can equivalently solve this new problem in O(n^2) time.

Sorting a 1D array in linear time

Given this, we simply need to provide a linear time sort. i.e. given n^2 elements, sort them in O(n^2) time. Conveniently, there are multiple algorithms you can use to accomplish this such as counting sort or radix sort, although they do come with various caveats. However, assuming a reasonable range of numerical values given the number of items to be sorted, these sorts will run in linear time.

Thus given n^2 elements in an n x n array, this 2D sorting problem can be reduced in O(n^2) time to a 1D sorting problem, which can then be solved with various linear time sorting algorithms in O(n^2) time. Hence, overall, this problem can be solved in O(n^2) time.

Sorting with a comparison sort

Following the discussion in the comments, the next step is to ask: what about comparison sorts. Comparison sorts are beneficial because it would allow us to avoid the previously mentioned caveats of counting and radix sorts.

However, even with this additional information, a linear time comparison sort is unlikely in practice, because this would require us to compute the final position of each number in O(1) time. We know this isn't possible using a comparison sort.

Let's consider a small example: what should be the final sorted position of the number originally in row 1, column 2? We know that it has to be the first of the numbers in columns 2...n. However, we don't know where it belongs relative to the numbers in column 1 (other than the number in row 1, column 1).

In general, for any number in the original square, we are uncertain of its final sorted position relative to all numbers to its lower left and the numbers to its upper right. It would take O(log_2(n)) comparisons to find the relative position of each number, and there are O(n^2) numbers to position. This uncertainty prevents us from achieving a linear time sort in practice.

But the additional information that we have should allow us to achieve some speedups. For example, we could adapt merge sort to this problem. In a standard merge sort we start by splitting our original array into half and repeat until we have arrays of size 1 that are guaranteed to be sorted,
then we repeatedly merge these subarrays until we have one single array. For n^2 elements, we have to create a binary tree with log_2(n^2) layers, and each layer takes O(n^2) time to merge.

Using the additional information in your problem setup, we don't have to split the arrays until they are of size 1. Instead, we can start off with n sorted arrays of length n and start merging from there. This halves the number of layers we have to merge, and gives us a final runtime of O(n^2 log_2(n)).

Conclusion

In practice, this additional information allows some speedups for comparison sorts, allowing us to achieve O(n^2 log_2(n)) run times.

But in order to achieve a linear time sort that runs in O(n^2) time, we have to rely on algorithms such as counting or radix sort.

Body:
Given the following 2d array:

6   8   11  17
9   11  14  20
18  20  23  29
24  26  29  35

Each row and column is sorted as well as the diagonals are sorted too (top left to bottom right). Assuming we have n² elements in the array (n = 4 in this case), it is trivial to use quicksort which takes O(n² log(n²)) = O(n² log(n)) to sort the 2d array. My question is can we sort this in O(n²)?

The goal is to use the given semi-sorted 2d array and come-up with a clever solution.

The target output is:

6   8   9   11
11  14  17  18
20  20  23  24
26  29  29  35


问:
Filtering empty partitions in RDD
Is there a way to filter empty partitions in RDD? I have some empty partitions after partitioning and I can't use them in action method.

I use Apache Spark in Scala

答:
If you dont know the distinct values within the column, and wish to avoid having empty partitions, you can use countApproxDistinct() as:

```<code>df.repartition(df.rdd.countApproxDistinct().toInt)
</code>```

If you wish to filter the existing empty partitions and repartition, you can use as solution suggeste by Sasa

OR:

```<code>df.repartition(df.mapPartitions(part => List(part.length).iterator).collect().count(_ != 0)).df.getNumPartitions)
</code>```

However, in later case the partitions may or may not contain records by value.

Title: Filtering empty partitions in RDD

Body:
If you dont know the distinct values within the column, and wish to avoid having empty partitions, you can use countApproxDistinct() as:

df.repartition(df.rdd.countApproxDistinct().toInt)

If you wish to filter the existing empty partitions and repartition, you can use as solution suggeste by Sasa

OR:

df.repartition(df.mapPartitions(part => List(part.length).iterator).collect().count(_ != 0)).df.getNumPartitions)

However, in later case the partitions may or may not contain records by value.


问:
LINQ to JSON in .net 4.0 Client Profile
How would I go about about using LINQ to JSON in the .net 4 Client Profile in C#. I'd like to query certain json responses as shown in msdn blog post without having to write out a contract (datacontract, servicecontract, etc). I really only need to query(read) the response, I don't need to modify the json response. (Also would a datacontract be faster than LINQ to JSON?)

Alternatively I could use XML or the full .net 4 framework, but I'm hoping that this can be avoided. I can use external libraries if it's better than installing the whole framework.

答: JSON.net is quite popular and seems to be what you're after.</p>

Title: LINQ to JSON in .net 4.0 Client Profile


问:
Powershell - Detect if Drive Letter is Mounted on a SSD Solid State Disk
I'm writing a Hyper-V VM build script and wanted to add a feature to select a SSD where possible to prioritise smaller and most frequently used VMs.  I first found the way in from the Scripting Guys here: http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/17/powertip-use-powershell-to-identify-ssd.aspx but I couldn't find anything that took me all of the way so I used WBEMTEST to find the classes I needed to query to make the connection between the SSD disk and the drive letter in question.

Click Start --> Run --> type WBEMTEST --> Check that the namespace is set to root\cimv2 and click Connect --> Enum Classes --> Recursive --> OK.  About 5 seconds later the list will be fully populated allowing you to click on a list item.  Click on a list item and then press the letter W to jump to Win32 and find one to look at then click Add. The properties and methods available are then shown.

The function IsSSDDrive below returns $True or $False depending on whether the given drive letter (including colon - e.g. C:) is mounted on a Solid State Disk (SSD) - assuming that the manufacturer inserted the letters SSD into the device name.  This assumption ultimately makes this method unreliable so it would be wise to include some code to cross check using something like:

```<code>$DiskScore = (Get-WmiObject -Class Win32_WinSAT).DiskScore
If ($DiskScore -gt 6.9) { $SystemHasSSDDrive=$True } Else { $SystemHasSSDDrive=$False }
Write-Host "System Has SSD Drive: $SystemHasSSDDrive"
</code>```

...if your environment uses such drives.

```<code>Function IsSSDDrive($Drive)
# Returns $True or $False depending on whether the given drive letter (including colon - e.g. C:) is mounted on a Solid State Disk (SSD) - assuming that the manufacturer inserted the letters SSD into the device name - which ultimately makes this method unreliable so beware to cross check using something like $DiskScore = (Get-WmiObject -Class Win32_WinSAT).DiskScore # Thanks to Rens Hollanders for this! http://renshollanders.nl/2013/01/sccm-mdt-identifying-ssds-from-your-task-sequence-by-windows-performance-index/
{
    [array] $SSDDeviceIDList = $Null
    [array] $SSDDeviceIDListF = $Null
    [array] $DDListF = $Null
    [array] $SSDDriveLetters = $Null

    # Build a list of DeviceIDs of disk drives that contain the string SSD.  Example output: \\.\PHYSICALDRIVE0, \\.\PHYSICALDRIVE1 etc
    $SSDDeviceIDList = Get-WmiObject Win32_DiskDrive | where { $_.model -match 'SSD'} | Select 'DeviceID'
    #$SSDDeviceIDList

    # Fix the list by removing the \\.\ from each of the obtained \\.\PHYSICALDRIVEx values
    ForEach ($SSDDeviceID in $SSDDeviceIDList) {
        $SSDDeviceIDListF += $SSDDeviceID.DeviceID.ToString().Replace("\\.\","")
    }
    #$SSDDeviceIDListF

    # Obtain disk drive to disk partition mapping information.  Section of sample output for a single partition:
        #Antecedent       : \\MyComputerName\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE1"
        #Dependent        : \\MyComputerName\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #2"
    $DDList1 = $null ; $DDList1 = Get-WmiObject Win32_DiskDriveToDiskPartition
    # Look at each partition
    ForEach ($Disk in $DDList1) {
        # Iterate through the previously collected list of filtered (SSD in the name) hard drives
        ForEach ($SSDDeviceID in $SSDDeviceIDListF) {
            # If the partition is found with a property that matches the deviceID of the known-SSD list, then add the partition dependent information to the filtered (SSD) list of disk drives (DDListF)
            If ($Disk.Antecedent.Contains($SSDDeviceID)) { $DDListF += $Disk.Dependent.Split([Char]34)[1] }
        }
    }
    #$DDListF

    # Obtain disk drive to disk partition mapping information.  We need to do this because the drive letter attribute is not present in Win32_DiskDriveToDiskPartition and the physical disk is not present in Win32_LogicalDiskToPartition.
    # Section of sample output for a single partition:
    #    Antecedent       : \\MyComputerName\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #2"
    #    Dependent        : \\MyComputerName\root\cimv2:Win32_LogicalDisk.DeviceID="I:"
    $LDPList = Get-WmiObject Win32_LogicalDiskToPartition
    # Look at each existing partition (on all drives)
    ForEach ($Partition in $LDPList) {
        # Iterate through the list of filtered SSD partitions
        ForEach ($DDL in $DDListF) {
            # If the disk-partition information from the SSD filtered list is found in the current partition then add the current partition's drive letter to the list of SSD drive letters
            If ($Partition.Antecedent.Contains($DDL)) { $SSDDriveLetters += $Partition.Dependent.Split([Char]34)[1] }
        }
    }
    $IsSSD = $False
    If (!($SSDDriveLetters -eq $Null)) {
        ForEach ($Item in $SSDDriveLetters) {
            If ($Drive.ToUpper() -eq $Item.ToUpper()) {
                $IsSSD = $True
                break
            }
        }
    }
    Return $IsSSD
}

$d = IsSSDDrive "D:" # Returns True if the given drive letter resides on a disk with a name containing the letters SSD.
$d

$c = IsSSDDrive "C:"
$c
</code>```

答:
```<code>#return letters of disks and if SSD or HDD or Unspec..:
Get-PhysicalDisk | ForEach-Object {
    $physicalDisk = $_
    $physicalDisk | Get-Disk | Get-Partition |
    Where-Object DriveLetter |Select-Object DriveLetter, @{n='MediaType';e={
    $physicalDisk.MediaType }}
    }
# | ft -HideTableHeaders if you don't want the table's headers.
</code>```

Body:
I'm writing a Hyper-V VM build script and wanted to add a feature to select a SSD where possible to prioritise smaller and most frequently used VMs.  I first found the way in from the Scripting Guys here: http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/17/powertip-use-powershell-to-identify-ssd.aspx but I couldn't find anything that took me all of the way so I used WBEMTEST to find the classes I needed to query to make the connection between the SSD disk and the drive letter in question.

Click Start --> Run --> type WBEMTEST --> Check that the namespace is set to root\cimv2 and click Connect --> Enum Classes --> Recursive --> OK.  About 5 seconds later the list will be fully populated allowing you to click on a list item.  Click on a list item and then press the letter W to jump to Win32 and find one to look at then click Add. The properties and methods available are then shown.

The function IsSSDDrive below returns $True or $False depending on whether the given drive letter (including colon - e.g. C:) is mounted on a Solid State Disk (SSD) - assuming that the manufacturer inserted the letters SSD into the device name.  This assumption ultimately makes this method unreliable so it would be wise to include some code to cross check using something like:

$DiskScore = (Get-WmiObject -Class Win32_WinSAT).DiskScore
If ($DiskScore -gt 6.9) { $SystemHasSSDDrive=$True } Else { $SystemHasSSDDrive=$False }
Write-Host "System Has SSD Drive: $SystemHasSSDDrive"

...if your environment uses such drives.

Function IsSSDDrive($Drive)
# Returns $True or $False depending on whether the given drive letter (including colon - e.g. C:) is mounted on a Solid State Disk (SSD) - assuming that the manufacturer inserted the letters SSD into the device name - which ultimately makes this method unreliable so beware to cross check using something like $DiskScore = (Get-WmiObject -Class Win32_WinSAT).DiskScore # Thanks to Rens Hollanders for this! http://renshollanders.nl/2013/01/sccm-mdt-identifying-ssds-from-your-task-sequence-by-windows-performance-index/
{
    [array] $SSDDeviceIDList = $Null
    [array] $SSDDeviceIDListF = $Null
    [array] $DDListF = $Null
    [array] $SSDDriveLetters = $Null

    # Build a list of DeviceIDs of disk drives that contain the string SSD.  Example output: \\.\PHYSICALDRIVE0, \\.\PHYSICALDRIVE1 etc
    $SSDDeviceIDList = Get-WmiObject Win32_DiskDrive | where { $_.model -match 'SSD'} | Select 'DeviceID'
    #$SSDDeviceIDList

    # Fix the list by removing the \\.\ from each of the obtained \\.\PHYSICALDRIVEx values
    ForEach ($SSDDeviceID in $SSDDeviceIDList) {
        $SSDDeviceIDListF += $SSDDeviceID.DeviceID.ToString().Replace("\\.\","")
    }
    #$SSDDeviceIDListF

    # Obtain disk drive to disk partition mapping information.  Section of sample output for a single partition:
        #Antecedent       : \\MyComputerName\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE1"
        #Dependent        : \\MyComputerName\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #2"
    $DDList1 = $null ; $DDList1 = Get-WmiObject Win32_DiskDriveToDiskPartition
    # Look at each partition
    ForEach ($Disk in $DDList1) {
        # Iterate through the previously collected list of filtered (SSD in the name) hard drives
        ForEach ($SSDDeviceID in $SSDDeviceIDListF) {
            # If the partition is found with a property that matches the deviceID of the known-SSD list, then add the partition dependent information to the filtered (SSD) list of disk drives (DDListF)
            If ($Disk.Antecedent.Contains($SSDDeviceID)) { $DDListF += $Disk.Dependent.Split([Char]34)[1] }
        }
    }
    #$DDListF

    # Obtain disk drive to disk partition mapping information.  We need to do this because the drive letter attribute is not present in Win32_DiskDriveToDiskPartition and the physical disk is not present in Win32_LogicalDiskToPartition.
    # Section of sample output for a single partition:
    #    Antecedent       : \\MyComputerName\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #2"
    #    Dependent        : \\MyComputerName\root\cimv2:Win32_LogicalDisk.DeviceID="I:"
    $LDPList = Get-WmiObject Win32_LogicalDiskToPartition
    # Look at each existing partition (on all drives)
    ForEach ($Partition in $LDPList) {
        # Iterate through the list of filtered SSD partitions
        ForEach ($DDL in $DDListF) {
            # If the disk-partition information from the SSD filtered list is found in the current partition then add the current partition's drive letter to the list of SSD drive letters
            If ($Partition.Antecedent.Contains($DDL)) { $SSDDriveLetters += $Partition.Dependent.Split([Char]34)[1] }
        }
    }
    $IsSSD = $False
    If (!($SSDDriveLetters -eq $Null)) {
        ForEach ($Item in $SSDDriveLetters) {
            If ($Drive.ToUpper() -eq $Item.ToUpper()) {
                $IsSSD = $True
                break
            }
        }
    }
    Return $IsSSD
}

$d = IsSSDDrive "D:" # Returns True if the given drive letter resides on a disk with a name containing the letters SSD.
$d

$c = IsSSDDrive "C:"
$c