问:
Visual Studio: "This document is opened by another project"
I spend most of my time developing controls for both WPF and Silverlight using the same codebase. To do this I add existing files from one project (say Silverlight) "as links" to the other (say WPF). For minor differences I use preprocessor directives like

```<code>#if SILVERLIGHT
...
#else
...
#endif
</code>```

The code in these blocks is grayed out depending on the type of project you've opened the file from. So if you open your file from Silverlight project (where SILVERLIGHT is defined) the else part is gray and Intellisense doesn't work in it.

In order for WPF part to be processed by IDE (with coloring and Intellisense support) you need to open the file from the WPF project. When you try to do that you get a message box saying that "This document is opened by another project" and when you click OK it displays that file in the context of the Silverlight project (not what I wanted to see). So I have to close the file, navigate to WPF project again and open the file again. This is very, very annoying.

So the question is this: is there some sort of setting or add-on that would make Visual Studio reopen the file from the project where I double-clicked on it instead of showing that stupid message box and showing me that file from the "wrong" project?

答:
You could make this a little easier to work with by using partial classes and multiple files: shared code that is the same for both WPF and Silverlight in a shared linked file, and a separate file for each containing the code specific to one or the other (with identical method/property signatures), each of which is only in one of the projects. Doing this allows both the WPF and Silverlight versions to be opened at once (since they're separate files) at the cost of adding a bunch of extra file management overhead.

Beyond that, get some extra memory and use separate solutions.

Body:
I spend most of my time developing controls for both WPF and Silverlight using the same codebase. To do this I add existing files from one project (say Silverlight) "as links" to the other (say WPF). For minor differences I use preprocessor directives like

#if SILVERLIGHT
...
#else
...
#endif

The code in these blocks is grayed out depending on the type of project you've opened the file from. So if you open your file from Silverlight project (where SILVERLIGHT is defined) the else part is gray and Intellisense doesn't work in it.

In order for WPF part to be processed by IDE (with coloring and Intellisense support) you need to open the file from the WPF project. When you try to do that you get a message box saying that "This document is opened by another project" and when you click OK it displays that file in the context of the Silverlight project (not what I wanted to see). So I have to close the file, navigate to WPF project again and open the file again. This is very, very annoying.

So the question is this: is there some sort of setting or add-on that would make Visual Studio reopen the file from the project where I double-clicked on it instead of showing that stupid message box and showing me that file from the "wrong" project?


来源: stackexchange

问:
Scaffolding a Read Action in MVC "No parameterless constructor defined for this object."
I'm working on a basic MVC5/EF6 application and am running into the following error when I try to scaffold a Read Action in MVC:

```<code>Error

There was an error running the selected code generator:
'No Parameterless constructor defined for this object'
</code>```

It should not need it anyway because I am calling a read not a delete or an update however the model in question does have a parameterless constructor (as do the models below it).

```<code>public class Article
{
    public int ArticleID { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime PublishDate { get; set; }

    public virtual Author Author { get; set; }

    public Article()
    {
    }
}
</code>```

My controller is below and it also has a parameterless constructor:

```<code>public ArticleController()
{
    connection = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    context = new TRNContext(connection);
}

// GET: Article
public ActionResult Index(int id)
{
    return View(context.Articles.SingleOrDefault(a => a.ArticleID == id));
}
</code>```

答: This error may be due to the situation. You have a class and this class inherits from the DbContext class. If you are generating this instead of writing the constructor method of this class, the constructor access modifier may be protected. if you edit it public, the problem will be fixed.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a basic MVC5/EF6 application and am running into the following error when I try to scaffold a Read Action in MVC:

Error

There was an error running the selected code generator:
'No Parameterless constructor defined for this object'

It should not need it anyway because I am calling a read not a delete or an update however the model in question does have a parameterless constructor (as do the models below it).

public class Article
{
    public int ArticleID { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime PublishDate { get; set; }

    public virtual Author Author { get; set; }

    public Article()
    {
    }
}

My controller is below and it also has a parameterless constructor:

public ArticleController()
{
    connection = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    context = new TRNContext(connection);
}

// GET: Article
public ActionResult Index(int id)
{
    return View(context.Articles.SingleOrDefault(a => a.ArticleID == id));
}


问:
Cant draw a shape to a specific panel in a NetBeans GUI
I'm trying to make a simple application to draw shapes to a panel in a jFrame. The GUI is a NetBeans generated jFrame. The application has three panels. the first two hold button groups to select the shape and a color. There's a button to draw the shape to the third panel once the selections are made.

What the GUI looks like

Unfortunately I'm having no love and can't make it work. For now I just want to get the button to draw a shape then I'll add the button functionality. Here's the code I have so far.

```<code>private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    Draw shape = new Draw();

    pnlDrawPad.add(shape); //pnlDrawPad is the name of the jPanel

    shape.drawing();

}

import javax.swing.*;
import java.awt.*;

public class Draw extends JPanel{

public Draw(){
    super();
}

public void drawing(){
    repaint();
}

//@Override <-- gives error "method does not override or implement a method from a supertype"
public void paintCompnent(Graphics g){

    super.paintComponent(g);

    g.setColor(Color.RED);
    g.drawString("Hello World!",40,30);
}
</code>```

}

When I click the "Draw Shape" button nothing happens. I've been searching for a couple days now and am not finding the answer. Actually, its making me more confused as to what to do.

How to deal with this?

答:
Don't keep creating new panels for each shape.

Instead you need a single panel with an ArrayList of objects you want to paint. Then you customize the paintComponent(...) method of the panel to iterate through all the objects in the panel and paint them.

So you button will just add another object to the ArrayList and then invoke repaint() on the panel.

Check out Custom Painting Approaches. The DrawOnComponent example shows how to paint a Rectangle objects from an ArrayList to get you started.

Body:
I'm trying to make a simple application to draw shapes to a panel in a jFrame. The GUI is a NetBeans generated jFrame. The application has three panels. the first two hold button groups to select the shape and a color. There's a button to draw the shape to the third panel once the selections are made.

What the GUI looks like

Unfortunately I'm having no love and can't make it work. For now I just want to get the button to draw a shape then I'll add the button functionality. Here's the code I have so far.

private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    Draw shape = new Draw();

    pnlDrawPad.add(shape); //pnlDrawPad is the name of the jPanel

    shape.drawing();

}

import javax.swing.*;
import java.awt.*;

public class Draw extends JPanel{

public Draw(){
    super();
}

public void drawing(){
    repaint();
}

//@Override <-- gives error "method does not override or implement a method from a supertype"
public void paintCompnent(Graphics g){

    super.paintComponent(g);

    g.setColor(Color.RED);
    g.drawString("Hello World!",40,30);
}

}

When I click the "Draw Shape" button nothing happens. I've been searching for a couple days now and am not finding the answer. Actually, its making me more confused as to what to do.

How to deal with this?


问:
mp4 content won't play in webpages served to Samsung Internet browser
I have a website which is able to play mp4 media (via the <video> tag and via DASH) in every browser except the Samsung Internet browser, which comes as default on Samsung Galaxy phones and probably a lot of other Samsung devices.

On a desktop, iPad, or even an ancient HP TouchPad tablet, it works fine.  Using other browsers on the same Samsung device (e.g. Chrome), the mp4 media plays fine, so it's not a limitation of Android or the device hardware.

I can detect the Samsung browser with JavaScript and disable video content on those devices, but I'd really like to not have to do that.  Surely there is a workaround.

Here's a quick test, if you'd like to try it on your device.  It tries to play 3 slightly different types of mp4 media on one page:

http://2pic.me/dashtest.html

On my Samsung Galaxy S6, none of them play in the Samsung Internet browser.

I tried using video.js, but that did not change the behavior.

Update:

In the year since I posted this, Samsung has finally updated their browser, and mp4 content now plays correctly, including auto-play.

答:
I experienced the same issue on Samsung Browser (current latest: v6.2.01.12), on a Samsung Galaxy 7 device. In my case I was using video.js, and playing HLS.
The problem I found was that autoplay was not working.
My solution was to try to play the video programatically and if failure detected (promise rejection), then display a PLAY button, and play the video in the user click. That worked for me.
It would be something like:

```<code>const video = document.getElementById('my-video');
video.play()
  .catch((err) => {
    if (err.name === 'NotAllowedError') {
      // Display PLAY button with a click event listener and play the video there.
    }
  });
</code>```

This is a simplified code, I do specific checks to see if my-video is an actual <video> element, and if video.play() returns a promise and all the basic safe checks (since this is supported in many other browsers).
But, it shows the idea to handle this autoplay not working scenario.

I hope it helps!

ContentLicense: CC BY-SA 4.0

Body:
I experienced the same issue on Samsung Browser (current latest: v6.2.01.12), on a Samsung Galaxy 7 device. In my case I was using video.js, and playing HLS.
The problem I found was that autoplay was not working.
My solution was to try to play the video programatically and if failure detected (promise rejection), then display a PLAY button, and play the video in the user click. That worked for me.
It would be something like:

const video = document.getElementById('my-video');
video.play()
  .catch((err) => {
    if (err.name === 'NotAllowedError') {
      // Display PLAY button with a click event listener and play the video there.
    }
  });

This is a simplified code, I do specific checks to see if my-video is an actual <video> element, and if video.play() returns a promise and all the basic safe checks (since this is supported in many other browsers).
But, it shows the idea to handle this autoplay not working scenario.

I hope it helps!


问:
Incorrect FrameLayout's childs order on android 5.0 and above
Here is my XML layout code:

```<code><FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" >

        <Button
            android:id="@+id/btn_test"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:background="@android:color/black"
            android:minHeight="0dp"
            android:minWidth="0dp" />

        <TextView
            android:id="@+id/tv_test"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:background="@android:color/white"
            android:gravity="center"
            android:text="12"
            android:textColor="@android:color/black"
            android:textStyle="bold" />
    </FrameLayout>
</code>```

As I expected the TextView will overlay on the Button, but it only working on android < 5.0. I research for all API changes about FrameLayout from developer site but still not getting exactly information. Did anyone find that? How to overlay TextView on Button via XML?

答:
Add stateListAnimator="@null" to your Button XML:

```<code><FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" >

    <Button
        android:id="@+id/btn_test"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@android:color/black"
        android:minHeight="0dp"
        android:minWidth="0dp"
        android:stateListAnimator="@null" />

        ...

</FrameLayout>
</code>```

This will make the Button respect its Z-index and position it under the TextView.

Source

Body:
Here is my XML layout code:

<FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" >

        <Button
            android:id="@+id/btn_test"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:background="@android:color/black"
            android:minHeight="0dp"
            android:minWidth="0dp" />

        <TextView
            android:id="@+id/tv_test"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:background="@android:color/white"
            android:gravity="center"
            android:text="12"
            android:textColor="@android:color/black"
            android:textStyle="bold" />
    </FrameLayout>

As I expected the TextView will overlay on the Button, but it only working on android < 5.0. I research for all API changes about FrameLayout from developer site but still not getting exactly information. Did anyone find that? How to overlay TextView on Button via XML?

Body:
Add stateListAnimator="@null" to your Button XML:

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" >

    <Button
        android:id="@+id/btn_test"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@android:color/black"
        android:minHeight="0dp"
        android:minWidth="0dp"
        android:stateListAnimator="@null" />

        ...

</FrameLayout>

This will make the Button respect its Z-index and position it under the TextView.

Source


问:
how to do a substring in qlikview?
Currently , I have a field which brings in date from the database in this format: Fri, Jun 12 09:21:46 CDT 2017.
I am new to qlikview. How can I do a substring or subfield so I can get Jun 12 2017. Even better if I can get in this format: 12-Jun-2017.
I would really appreciate the help. Thanks</p>

答:
There is the subfield function or you can use the mid function.

I'd recommend getting it out as a date so you can mess with the format wherever you want. That would look something like this:

```<code>=date(date#(
    subfield(YourDateString,' ',6) & '/' &
    subfield(YourDateString,' ',2) & '/' &
    subfield(YourDateString,' ',3),
    'YYYY/MMM/DD'
))
</code>```

That picks the year, month and date from the string using subfield and then turns it into a usable string which is fed into the date# function (which reads strings and converts to numbers) and then finally into the date function (which makes nice human-readable dates from numbers)

or this:

```<code>=date(date#(
    mid(YourDateString,6,6) & ' ' &
    right(YourDateString,4),
    'MMM DD YYYY'
))
</code>```

Similar to the one before, that gets the month and day, using mid, first, adds on the year, using right, and then does the same with date# and date

Both should work in script or charts and both are, of course, dependent on your having a consistently-formatted string to work reliably...

Title: how to do a substring in qlikview?

Body:
There is the subfield function or you can use the mid function.

I'd recommend getting it out as a date so you can mess with the format wherever you want. That would look something like this:

=date(date#(
    subfield(YourDateString,' ',6) & '/' &
    subfield(YourDateString,' ',2) & '/' &
    subfield(YourDateString,' ',3),
    'YYYY/MMM/DD'
))

That picks the year, month and date from the string using subfield and then turns it into a usable string which is fed into the date# function (which reads strings and converts to numbers) and then finally into the date function (which makes nice human-readable dates from numbers)

or this:

=date(date#(
    mid(YourDateString,6,6) & ' ' &
    right(YourDateString,4),
    'MMM DD YYYY'
))

Similar to the one before, that gets the month and day, using mid, first, adds on the year, using right, and then does the same with date# and date

Both should work in script or charts and both are, of course, dependent on your having a consistently-formatted string to work reliably...


问:
Testing product import to Magento 1.9, "Product Type is invalid or not supported" NO MATTER WHAT?
So I'm new to Magento but from what I gather Product Type is a required field for importing. My csv reads as follows:

```<code>store,websites,attribute_set,type,sku,has_options,name,image,small_image,thumbnail,url_key,url_path,options_container,gift_message_available,page_layout,country_of_manufacture,msrp_enabled,msrp_display_actual_price_type,price,special_price,weight,status,tax_class_id,visibility,is_recurring,linen_type,enable_tabs,description,short_description,special_from_date,qty,min_qty,use_config_min_qty,is_qty_decimal,backorders,use_config_backorders,min_sale_qty,use_config_min_sale_qty,max_sale_qty,use_config_max_sale_qty,is_in_stock,low_stock_date,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,stock_status_changed_auto,use_config_qty_increments,qty_increments,use_config_enable_qty_inc,enable_qty_increments,is_decimal_divided,stock_status_changed_automatically,use_config_enable_qty_increments,product_name,store_id,type_id,categories,gallery,img_label,has_color_picked,additional_catoverride,meta_title,meta_description
admin,base,Default,simple,111-1-BK-GG,0,HERCULES,Imperial,Series,Black,Leather,Chair,,,,,,Block,after,Info,Column,No,No,layout,updates,China,Use,config,Use,config,583,185.75,54,Disabled,Taxable,Goods,"Catalog, Search",No,UNKNOWN,No,"<ul class=""disc"">Your lobby or reception area is the forefront of your business and providing distinguished and comfortable seating is the first step towards making a great impression. The modern appeal of this chair will make a lasting impression with your visitors. Reception chairs are perfect for the office and as waiting room seating. The contemporary design of this furniture adapts in several different settings. This chair features streamlined stitching and elevated, curved hardwood feet. Not only will this chair fit in a professional environment, but will add a modern look to your home.<li>Contemporary Design<li>Office or Home Office Seating<li>Sloping Arms<li>Slightly Curved Seat and Back<li>Fixed Seat Cushion<li>1.8 High Density Foam<li>Sturdy Hardwood Construction<li>Cherry Stained Wood Feet<li>Black LeatherSoft Upholstery<li>LeatherSoft is leather and polyurethane for added Softness and Durability<li>CA117 Fire Retardant Foam</ul>","<ul class=""disc""><b>Black Leather Chair</b><li>Overall Dimensions: 33.50""W x 31""D x 29""H<li>Availability: In Stock. Usually ships within 24 business hours.</ul>",,0,0,1,0,0,1,1,1,0,1,0,,1,0,1,1,1,0,1,0
</code>```

This was provided by a separate entity, originally with a number of columns per product more than there are headers. With those, Check Data returned "Column names have duplicates". That content deleted returned

```<code>Product Type is invalid or not supported in rows: 1

File is totally invalid. Please fix errors and re-upload file
Checked rows: 1, checked entities: 1, invalid rows: 1, total errors: 1
</code>```

totally invalid.

Originally the type_id column read instead product_type, with the same value in the product row as there is now, 1. Note that there is also a type column, with the value "simple". Before even realizing that, I tried values "Simple Product", "Simple", and "simple" for product_type. I also tried combining those values with variations on the column header, such as the current type_id, and _type, both of which I came across while researching this issue online.

I have also tried removing that column altogether. Nothing makes any difference. What can I do, short of writing my own tedious import script?

UPDATE: that error has given way to another now, who would've thought... (type_id=1 ok)

Now it tells me

```<code>Can not find required columns: sku
Please fix errors and re-upload file
</code>```

when said column does very much exist verbatim. I tried moving the column. I tried changing the [albeit valid] value. I even tried setting the field sku to not be required in Catalog > Attributes > Manage Attributes. Still I get the same sad result.

I am hating Magento, but that still does me nor anyone else any good. How can I resolve to import ONE SIMPLE PRODUCT into this stupid system?

I even tried via the MageBees module and it's giving Error: Product SKU field "sku" is empty. No it's not empty; it's 111-1-BK-GG. Goddamn.

答:
type_id or _type - this field should contain the information that
  specifies to which type the product belongs, in other words if it is
  one component or complex. Here should be specified: simple,
  configurable, virtual, downloadable, grouped or bundle value. Note
  that it is case-sensitive and values should not be capitalized.

Your type field should instead be type_id. I'm unsure why you changed the name product_type, but I think you should leave that as it was or delete it.

Here is a nice guide (from which I quoted the text above) that will help you: https://www.mag-manager.com/useful-articles/tipstricks/required-csv-file-values-for-error-free-magento-import-via-admin/

Body:
So I'm new to Magento but from what I gather Product Type is a required field for importing. My csv reads as follows:

store,websites,attribute_set,type,sku,has_options,name,image,small_image,thumbnail,url_key,url_path,options_container,gift_message_available,page_layout,country_of_manufacture,msrp_enabled,msrp_display_actual_price_type,price,special_price,weight,status,tax_class_id,visibility,is_recurring,linen_type,enable_tabs,description,short_description,special_from_date,qty,min_qty,use_config_min_qty,is_qty_decimal,backorders,use_config_backorders,min_sale_qty,use_config_min_sale_qty,max_sale_qty,use_config_max_sale_qty,is_in_stock,low_stock_date,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,stock_status_changed_auto,use_config_qty_increments,qty_increments,use_config_enable_qty_inc,enable_qty_increments,is_decimal_divided,stock_status_changed_automatically,use_config_enable_qty_increments,product_name,store_id,type_id,categories,gallery,img_label,has_color_picked,additional_catoverride,meta_title,meta_description
admin,base,Default,simple,111-1-BK-GG,0,HERCULES,Imperial,Series,Black,Leather,Chair,,,,,,Block,after,Info,Column,No,No,layout,updates,China,Use,config,Use,config,583,185.75,54,Disabled,Taxable,Goods,"Catalog, Search",No,UNKNOWN,No,"
Your lobby or reception area is the forefront of your business and providing distinguished and comfortable seating is the first step towards making a great impression. The modern appeal of this chair will make a lasting impression with your visitors. Reception chairs are perfect for the office and as waiting room seating. The contemporary design of this furniture adapts in several different settings. This chair features streamlined stitching and elevated, curved hardwood feet. Not only will this chair fit in a professional environment, but will add a modern look to your home.
Contemporary Design
Office or Home Office Seating
Sloping Arms
Slightly Curved Seat and Back
Fixed Seat Cushion
1.8 High Density Foam
Sturdy Hardwood Construction
Cherry Stained Wood Feet
Black LeatherSoft Upholstery
LeatherSoft is leather and polyurethane for added Softness and Durability
CA117 Fire Retardant Foam
","
Black Leather Chair
Overall Dimensions: 33.50""W x 31""D x 29""H
Availability: In Stock. Usually ships within 24 business hours.
",,0,0,1,0,0,1,1,1,0,1,0,,1,0,1,1,1,0,1,0

This was provided by a separate entity, originally with a number of columns per product more than there are headers. With those, Check Data returned "Column names have duplicates". That content deleted returned

Product Type is invalid or not supported in rows: 1

File is totally invalid. Please fix errors and re-upload file
Checked rows: 1, checked entities: 1, invalid rows: 1, total errors: 1

totally invalid.

Originally the type_id column read instead product_type, with the same value in the product row as there is now, 1. Note that there is also a type column, with the value "simple". Before even realizing that, I tried values "Simple Product", "Simple", and "simple" for product_type. I also tried combining those values with variations on the column header, such as the current type_id, and _type, both of which I came across while researching this issue online.

I have also tried removing that column altogether. Nothing makes any difference. What can I do, short of writing my own tedious import script?

UPDATE: that error has given way to another now, who would've thought... (type_id=1 ok)

Now it tells me

Can not find required columns: sku
Please fix errors and re-upload file

when said column does very much exist verbatim. I tried moving the column. I tried changing the [albeit valid] value. I even tried setting the field sku to not be required in Catalog > Attributes > Manage Attributes. Still I get the same sad result.

I am hating Magento, but that still does me nor anyone else any good. How can I resolve to import ONE SIMPLE PRODUCT into this stupid system?

I even tried via the MageBees module and it's giving Error: Product SKU field "sku" is empty. No it's not empty; it's 111-1-BK-GG. Goddamn.


问:
WindowsFormsSynchronizationContext from another class
How to call WindowsFormsSynchronizationContext from another class and thread Probably stupid on my part but i've searched everywhere and can't understand.

It does work if I put the worker and code in the body of Form1.

Form1:

```<code>Public Shared UIContext As WindowsFormsSynchronizationContext
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    UIContext = WindowsFormsSynchronizationContext.Current
    Dim StartClock As New SendtoUI
End Sub
Public Sub updatelable(incomingText As String)
    Label1.Text = incomingText
End Sub
</code>```

Test Class :

```<code>Public Class SendtoUI
    Private lastUpdated As DateTime = DateTime.Now
    Private backgroundTimer As System.Timers.Timer
    Public Sub New()
        backgroundTimer = New Timers.Timer(1000)
        AddHandler backgroundTimer.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf backgroundTimer_Elapsed)
        backgroundTimer.Start()
    End Sub

    Private Sub backgroundTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
        lastUpdated = DateTime.Now

        Form1.UIContext.Post(Sub()
                                    Form1.updatelable(lastUpdated.ToLongTimeString())
                                End Sub, Nothing)
    End Sub
End Class
</code>```

Based on above,

Label1.Text = incomingText

The line does get executed but the Label isn't updated. Probably so simple but i'm stumped.

Thanks for any help!

-TD

OK, I figured it out thanks to Jimi, I'm updating with what I ended up with and hopefully it can help someone else!

Simple form1 as follows:

```<code>    Imports System.Threading

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim TestTHreadUI As New ThreadedBackground(SynchronizationContext.Current, New SendOrPostCallback(AddressOf UpdateUI))
        End Sub
        Public Sub UpdateUI(incomingText As Object)
            Label1.Text = incomingText.ToString
        End Sub
    End Class
</code>```

ThreadedBackground Class:

```<code>Imports System.Threading

    Public Class ThreadedBackground
        Private backgroundTimer As System.Timers.Timer
        Public Sub New(UIContext As SynchronizationContext, UpdateAddress As SendOrPostCallback)
            SyncContext = UIContext
            SyncCallback = UpdateAddress
            backgroundTimer = New Timers.Timer(1000)
            AddHandler backgroundTimer.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf backgroundTimer_Elapsed)
            backgroundTimer.Start()
        End Sub

        'SynchronizationContext used for Posting
        Public Property SyncContext As System.Threading.SynchronizationContext
        'The Object Callback address to call
        Public Property SyncCallback As System.Threading.SendOrPostCallback

        Private Sub backgroundTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)

            'SyncContext.Post(SyncCallback, CType(DateTime.Now.ToLongTimeString, Object))   ' using passed in SendOrPostCallback(SyncCallback)
            SyncContext.Post(New SendOrPostCallback(Sub() Form1.UpdateUI(DateTime.Now.ToLongTimeString)), Nothing) ' Not using SendOrPostCallback(SyncCallback), Direct call to form1 Sub using lambda
            'SyncContext.Post(New SendOrPostCallback(Sub() Form1.Label1.Text = DateTime.Now.ToLongTimeString), Nothing) ' Not using SendOrPostCallback(SyncCallback), Direct call to form1 Control using lambda

        End Sub
    End Class
</code>```

答:
I'ld consider avoiding a static reference to a specific Object (Form in this case) in your class.

A way is to add some  properties to your class that can hold that reference.

Your code can be edited as:

```<code>Imports System.Threading

Public Class Form1

   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click

      Dim StartClock As New SendtoUI
      StartClock.SyncContext = System.Windows.Forms.WindowsFormsSynchronizationContext.Current
      StartClock.SyncCallback = New System.Threading.SendOrPostCallback(AddressOf Me.updatelable)
   End Sub

   'Delegate signature
   'Public Delegate Sub SendOrPostCallback(state As Object)

   Public Sub updatelable(incomingText As Object)
      Label1.Text = incomingText.ToString
   End Sub
End Class
</code>```

Your class with new Properties:

```<code>Public Class SendtoUI
   Private backgroundTimer As System.Timers.Timer
   Public Sub New()
      backgroundTimer = New Timers.Timer(1000)
      AddHandler backgroundTimer.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf backgroundTimer_Elapsed)
      backgroundTimer.Start()
   End Sub

   'SynchronizationContext used for Posting
   Public Property SyncContext As System.Threading.SynchronizationContext
   'The Object Callback address to call
   Public Property SyncCallback As System.Threading.SendOrPostCallback

   Private Sub backgroundTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)

      SyncContext.Post(SyncCallback, CType(DateTime.Now.ToLongTimeString, Object))

   End Sub
End Class
</code>```

Body:
How to call WindowsFormsSynchronizationContext from another class and thread Probably stupid on my part but i've searched everywhere and can't understand.

It does work if I put the worker and code in the body of Form1.

Form1:

Public Shared UIContext As WindowsFormsSynchronizationContext
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    UIContext = WindowsFormsSynchronizationContext.Current
    Dim StartClock As New SendtoUI
End Sub
Public Sub updatelable(incomingText As String)
    Label1.Text = incomingText
End Sub

Test Class :

Public Class SendtoUI
    Private lastUpdated As DateTime = DateTime.Now
    Private backgroundTimer As System.Timers.Timer
    Public Sub New()
        backgroundTimer = New Timers.Timer(1000)
        AddHandler backgroundTimer.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf backgroundTimer_Elapsed)
        backgroundTimer.Start()
    End Sub

    Private Sub backgroundTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
        lastUpdated = DateTime.Now

        Form1.UIContext.Post(Sub()
                                    Form1.updatelable(lastUpdated.ToLongTimeString())
                                End Sub, Nothing)
    End Sub
End Class

Based on above,

Label1.Text = incomingText

The line does get executed but the Label isn't updated. Probably so simple but i'm stumped.

Thanks for any help!

-TD

OK, I figured it out thanks to Jimi, I'm updating with what I ended up with and hopefully it can help someone else!

Simple form1 as follows:

    Imports System.Threading

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim TestTHreadUI As New ThreadedBackground(SynchronizationContext.Current, New SendOrPostCallback(AddressOf UpdateUI))
        End Sub
        Public Sub UpdateUI(incomingText As Object)
            Label1.Text = incomingText.ToString
        End Sub
    End Class

ThreadedBackground Class:

Imports System.Threading

    Public Class ThreadedBackground
        Private backgroundTimer As System.Timers.Timer
        Public Sub New(UIContext As SynchronizationContext, UpdateAddress As SendOrPostCallback)
            SyncContext = UIContext
            SyncCallback = UpdateAddress
            backgroundTimer = New Timers.Timer(1000)
            AddHandler backgroundTimer.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf backgroundTimer_Elapsed)
            backgroundTimer.Start()
        End Sub

        'SynchronizationContext used for Posting
        Public Property SyncContext As System.Threading.SynchronizationContext
        'The Object Callback address to call
        Public Property SyncCallback As System.Threading.SendOrPostCallback

        Private Sub backgroundTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)

            'SyncContext.Post(SyncCallback, CType(DateTime.Now.ToLongTimeString, Object))   ' using passed in SendOrPostCallback(SyncCallback)
            SyncContext.Post(New SendOrPostCallback(Sub() Form1.UpdateUI(DateTime.Now.ToLongTimeString)), Nothing) ' Not using SendOrPostCallback(SyncCallback), Direct call to form1 Sub using lambda
            'SyncContext.Post(New SendOrPostCallback(Sub() Form1.Label1.Text = DateTime.Now.ToLongTimeString), Nothing) ' Not using SendOrPostCallback(SyncCallback), Direct call to form1 Control using lambda

        End Sub
    End Class

Body:
I'ld consider avoiding a static reference to a specific Object (Form in this case) in your class.

A way is to add some  properties to your class that can hold that reference.

Your code can be edited as:

Imports System.Threading

Public Class Form1

   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click

      Dim StartClock As New SendtoUI
      StartClock.SyncContext = System.Windows.Forms.WindowsFormsSynchronizationContext.Current
      StartClock.SyncCallback = New System.Threading.SendOrPostCallback(AddressOf Me.updatelable)
   End Sub

   'Delegate signature
   'Public Delegate Sub SendOrPostCallback(state As Object)

   Public Sub updatelable(incomingText As Object)
      Label1.Text = incomingText.ToString
   End Sub
End Class

Your class with new Properties:

Public Class SendtoUI
   Private backgroundTimer As System.Timers.Timer
   Public Sub New()
      backgroundTimer = New Timers.Timer(1000)
      AddHandler backgroundTimer.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf backgroundTimer_Elapsed)
      backgroundTimer.Start()
   End Sub

   'SynchronizationContext used for Posting
   Public Property SyncContext As System.Threading.SynchronizationContext
   'The Object Callback address to call
   Public Property SyncCallback As System.Threading.SendOrPostCallback

   Private Sub backgroundTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)

      SyncContext.Post(SyncCallback, CType(DateTime.Now.ToLongTimeString, Object))

   End Sub
End Class


问:
Sed replace hyphen with underscore
new to regex and have a problem. I want to replace hyphens with underscores in certain places in a file. To simplify things, let's say I want to replace the first hyphen. Here's an example "file":

```<code>dont-touch-these-hyphens
leaf replace-these-hyphens
</code>```

I want to replace hyphens in all lines found by

```<code>grep -P "leaf \w+-" file
</code>```

I tried

```<code>sed -i 's/leaf \(\w+\)-/leaf \1_/g' file
</code>```

but nothing happens (wrong replacement would have been better than nothing). I've tried a few tweaks but still nothing. Again, I'm new to this so I figure the above "should basically work". What's wrong with it, and how do I get what I want? Thanks.

答:
Just use awk:

```<code>$ awk '$1=="leaf"{ sub(/-/,"_",$2) } 1' file
dont-touch-these-hyphens
leaf replace_these-hyphens
</code>```

It gives you much more precise control over what you're matching (e.g. the above is doing a string instead of regexp comparison on "leaf" and so would work even if that string contained regexp metacharacters like . or *) and what you're replacing (e.g. the above only does the replacement in the text AFTER leaf and so would continue to work even if leaf itself contained -s):

```<code>$ cat file
dont-touch-these-hyphens
leaf-foo.*bar replace-these-hyphens
leaf-foobar dont-replace-these-hyphens
</code>```

Correct output:

```<code>$ awk '$1=="leaf-foo.*bar"{ sub(/-/,"_",$2) } 1' file
dont-touch-these-hyphens
leaf-foo.*bar replace_these-hyphens
leaf-foobar dont-replace-these-hyphens
</code>```

Wrong output:

```<code>$ sed '/^leaf-foo.*bar/ s/-/_/' file
dont-touch-these-hyphens
leaf_foo.*bar replace-these-hyphens
leaf_foobar dont-replace-these-hyphens
</code>```

(note the "-" in leaf-foo being replaced by "_" in each of the last 2 lines, including the one that does not start with the string "leaf-foo.*bar").

That awk script will work as-is using any awk on any UNIX box.

Title: Sed replace hyphen with underscore

Body:
new to regex and have a problem. I want to replace hyphens with underscores in certain places in a file. To simplify things, let's say I want to replace the first hyphen. Here's an example "file":

dont-touch-these-hyphens
leaf replace-these-hyphens

I want to replace hyphens in all lines found by

grep -P "leaf \w+-" file

I tried

sed -i 's/leaf \(\w+\)-/leaf \1_/g' file

but nothing happens (wrong replacement would have been better than nothing). I've tried a few tweaks but still nothing. Again, I'm new to this so I figure the above "should basically work". What's wrong with it, and how do I get what I want? Thanks.

Body:
Just use awk:

$ awk '$1=="leaf"{ sub(/-/,"_",$2) } 1' file
dont-touch-these-hyphens
leaf replace_these-hyphens

It gives you much more precise control over what you're matching (e.g. the above is doing a string instead of regexp comparison on "leaf" and so would work even if that string contained regexp metacharacters like . or *) and what you're replacing (e.g. the above only does the replacement in the text AFTER leaf and so would continue to work even if leaf itself contained -s):

$ cat file
dont-touch-these-hyphens
leaf-foo.*bar replace-these-hyphens
leaf-foobar dont-replace-these-hyphens

Correct output:

$ awk '$1=="leaf-foo.*bar"{ sub(/-/,"_",$2) } 1' file
dont-touch-these-hyphens
leaf-foo.*bar replace_these-hyphens
leaf-foobar dont-replace-these-hyphens

Wrong output:

$ sed '/^leaf-foo.*bar/ s/-/_/' file
dont-touch-these-hyphens
leaf_foo.*bar replace-these-hyphens
leaf_foobar dont-replace-these-hyphens

(note the "-" in leaf-foo being replaced by "_" in each of the last 2 lines, including the one that does not start with the string "leaf-foo.*bar").

That awk script will work as-is using any awk on any UNIX box.


问:
How to monkeypatch sqlite database for tests purposes?
In ORM.py file:

```<code>from peewee import *
db = SqliteDatabase('database.db')

class Device(Model):
    uid = CharField(unique=True, max_length=17)

    class Meta:
        database = db
</code>```

now in the test.py I would like to monkeypatch orginal database database.db with test.db

```<code>from _pytest.monkeypatch import MonkeyPatch

@pytest.fixture(scope="session")
def monkeysession(request):
    mp = MonkeyPatch()
    yield mp
    mp.undo()

@pytest.fixture(scope='session', autouse=True)
def create_db(monkeysession, request):
    monkeysession.setattr(ORM, 'db', SqliteDatabase('test.db'))
</code>```

But my error (peewee.OperationalError: table "device" already exists) suggest that monkeypatch failed

答:
http://docs.peewee-orm.com/en/latest/peewee/database.html#testing-peewee-applications</p>
```<code># tests.py
import unittest
from my_app.models import EventLog, Relationship, Tweet, User

MODELS = [User, Tweet, EventLog, Relationship]

# use an in-memory SQLite for tests.
test_db = SqliteDatabase(':memory:')

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        # Bind model classes to test db. Since we have a complete list of
        # all models, we do not need to recursively bind dependencies.
        test_db.bind(MODELS, bind_refs=False, bind_backrefs=False)

        test_db.connect()
        test_db.create_tables(MODELS)

    def tearDown(self):
        # Not strictly necessary since SQLite in-memory databases only live
        # for the duration of the connection, and in the next step we close
        # the connection...but a good practice all the same.
        test_db.drop_tables(MODELS)

        # Close connection to db.
        test_db.close()

        # If we wanted, we could re-bind the models to their original
        # database here. But for tests this is probably not necessary.
</code>```

Body:
In ORM.py file:

from peewee import *
db = SqliteDatabase('database.db')

class Device(Model):
    uid = CharField(unique=True, max_length=17)

    class Meta:
        database = db

now in the test.py I would like to monkeypatch orginal database database.db with test.db

from _pytest.monkeypatch import MonkeyPatch

@pytest.fixture(scope="session")
def monkeysession(request):
    mp = MonkeyPatch()
    yield mp
    mp.undo()

@pytest.fixture(scope='session', autouse=True)
def create_db(monkeysession, request):
    monkeysession.setattr(ORM, 'db', SqliteDatabase('test.db'))

But my error (peewee.OperationalError: table "device" already exists) suggest that monkeypatch failed

Body:
http://docs.peewee-orm.com/en/latest/peewee/database.html#testing-peewee-applications

# tests.py
import unittest
from my_app.models import EventLog, Relationship, Tweet, User

MODELS = [User, Tweet, EventLog, Relationship]

# use an in-memory SQLite for tests.
test_db = SqliteDatabase(':memory:')

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        # Bind model classes to test db. Since we have a complete list of
        # all models, we do not need to recursively bind dependencies.
        test_db.bind(MODELS, bind_refs=False, bind_backrefs=False)

        test_db.connect()
        test_db.create_tables(MODELS)

    def tearDown(self):
        # Not strictly necessary since SQLite in-memory databases only live
        # for the duration of the connection, and in the next step we close
        # the connection...but a good practice all the same.
        test_db.drop_tables(MODELS)

        # Close connection to db.
        test_db.close()

        # If we wanted, we could re-bind the models to their original
        # database here. But for tests this is probably not necessary.


问:
Change dll output in a project using visual studio 2010 express
In VS 2010 express there are a few library projects (dlls) attached to the application project. When building the solution the dlls output to bin/Release/. Is there a way to have the .exe output to bin/Release and the dlls to bin/Release/dll?</p>

答:
This requires either a .config file with the <probing> element or implementing AppDomain.AssemblyResolve so that the CLR can find these DLLs.  You'll have a deployment problem too, you have to convince ClickOnce to publish these DLLs.  Realistically should only attempt this with the retail edition of Visual Studio so you can create a Setup project.

Fwiw: your customer won't mind that the DLLs are in the same folder as the EXE.  I think most actually strongly prefer this.  I do.

ContentLicense: CC BY-SA 2.5


问:
How can I get a program working with missing references?
I've got the code for project written with a vb.net, .net Framework 2.0, Windows Form Application.  I'm trying to get it working in Visual Studio 2015.  When I open it up, I'm missing several references.  I try to compile (Clean/Rebuild) it, and get multiple errors.  I've looked up the files online, but all I can find are sites saying I need to reinstall them.  I don't have the dll's and don't have any idea what these do (except that they vaguely are Microsoft related).  Can someone tell me how to get the program working or how to find the files?

Here are the missing references:

AxInterop.MSDataGridLib

AxMSDataGridLib

DAO

Interop.MSDataGridLib

Microsoft.ReportVeiwer.WinForms

Microsoft.Vbe.Interop

MSDataGridLib

MSDataReportLib

MSDATASRC

Here is the error I get when I rebuild the solution:

1>------ Rebuild All started: Project: RTS, Configuration: Release Any CPU ------
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "AxInterop.MSDataGridLib". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "Interop.MSDataGridLib". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "cde57a40-8b86-11d0-b3c6-00a0c90aea82" version 1.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "00025e01-0000-0000-c000-000000000046" version 4.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "cde57a40-8b86-11d0-b3c6-00a0c90aea82" version 1.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3284: Cannot get the file path for type library "642ac760-aab4-11d0-8494-00a0c90dc8a9" version 1.0. Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2398,5): warning MSB3283: Cannot find wrapper assembly for type library "MSDATASRC". Verify that (1) the COM component is registered correctly and (2) your target platform is the same as the bitness of the COM component. For example, if the COM component is 32-bit, your target platform must not be 64-bit.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Here is the image showing broken references:

答:
Probably this old project resulted from poorly converting a yet older (non-.NET) Visual Basic or VBA application to .NET. E.g. DAO is a database access technology used in these old languages. You should replace it by ADO.NET which is integrated into the .NET Framework.

The same is probably true for most of the other referenced DLLs. To be able to do this, you must understand what the old components did.

However, my estimation is that the whole application needs to be rewritten from scratch.


问:
Percentage values in background-position; how to change its behavior?

Problem definition

I have to render a image as if it were cropped inside a container. The only data I have is the img URL and its bounds in percentages values, expressed as numeric values (left: 86, top: 72, right: 99, bottom: 12, etc...). As you could imagine, the image is bigger than its container.

Code Snippet

Javascript

```<code>get pictureProperties() {
    const pic = this.discovery.img;
    const x = this.discovery.crop_percentages.left + '%';
    const y = (100 - this.discovery.crop_percentages.top) + '%';
    return `background-image: url(${pic}); background-position: ${x} ${y}`;
}
</code>```

Pug

```<code>.photo-wrapper(style="{{::$ctrl.pictureProperties}}"
</code>```

Issues

I tried to position the image as a background inside the container without any luck, because percentage values work as follows with background-images:

While I need something like the absolute values positioning but using this percentages values.

Any idea of how can I work around this issue?

答:
Instead of setting the background-image of the element itself, you could set it to one of the :before/:after pseudo elements and set it to be positioned absolutely. The top/left/right/bottom properties set the top left position of the absolutely positioned element. Live example here: https://jsfiddle.net/1oyewhuo/

#xyz{
  position: relative;
  height: 200px;
  width: 400px;
  background-color: red;
}

#xyz:after{
  background-image: url("http://lorempixel.com/400/200/sports/2/");
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  content: '';
  top: 50% /* this.discovery.crop_percentages.top */;
  left: 25% /* this.discovery.crop_percentages.left */;
  right: 25% /* this.discovery.crop_percentages.right */;
  bottom: 25% /* this.discovery.crop_percentages.bottom */;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="xyz"></div></code>```

Body:
Problem definition

I have to render a image as if it were cropped inside a container. The only data I have is the img URL and its bounds in percentages values, expressed as numeric values (left: 86, top: 72, right: 99, bottom: 12, etc...). As you could imagine, the image is bigger than its container.

Code Snippet

Javascript

get pictureProperties() {
    const pic = this.discovery.img;
    const x = this.discovery.crop_percentages.left + '%';
    const y = (100 - this.discovery.crop_percentages.top) + '%';
    return `background-image: url(${pic}); background-position: ${x} ${y}`;
}

Pug

.photo-wrapper(style="{{::$ctrl.pictureProperties}}"

Issues

I tried to position the image as a background inside the container without any luck, because percentage values work as follows with background-images:

While I need something like the absolute values positioning but using this percentages values.

Any idea of how can I work around this issue?

Body:
Instead of setting the background-image of the element itself, you could set it to one of the :before/:after pseudo elements and set it to be positioned absolutely. The top/left/right/bottom properties set the top left position of the absolutely positioned element. Live example here: https://jsfiddle.net/1oyewhuo/

#xyz{
  position: relative;
  height: 200px;
  width: 400px;
  background-color: red;
}

#xyz:after{
  background-image: url("http://lorempixel.com/400/200/sports/2/");
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  content: '';
  top: 50% /* this.discovery.crop_percentages.top */;
  left: 25% /* this.discovery.crop_percentages.left */;
  right: 25% /* this.discovery.crop_percentages.right */;
  bottom: 25% /* this.discovery.crop_percentages.bottom */;
}

<div id="xyz"></div>


问:
elisp implementation of the "uniq -c" Unix command to count unique lines
If there is a data in region:

```
flower
park
flower
stone
flower
stone
stone
flower
```

M-x some-command should give me in different buffer:

```
4 flower
2 stone
1 park
```

This data can then be sorted by frequency or item.

答:
It is similar to uniq -c in bash.

Then why not use uniq -c?

With the region highlighted, M-| "sort | uniq -c", will run that command on the current region.  The results will show in the minibuffer and will be listed in *Messages* buffer.  Adding a prefix arg will insert the results into the current buffer.

Body:
If there is a data in region:

flower
park
flower
stone
flower
stone
stone
flower

M-x some-command should give me in different buffer:

4 flower
2 stone
1 park

This data can then be sorted by frequency or item.


问:
Extracting merged cells properties when reading an excel file into pandas
I am reading an unstructured excel file(with lot of merged cells of no particular size) into pandas data frame and the content in merged cells is getting read into top left cell position in pandas and it fills the other cells with null values. Now there are many null values already present in the excel file and i want to find a way to specifically track the locations of cells with null values that were created after unmerging when read into pandas. I don't find any way in python that could do this thing. Could anyone guide me how to approach this problem?</p>

答:
I guess you use pandas.read_excel() to get data from Excel into the data frame?

Given the merged cells in the Excel sheet, I believe you will need to read the data yourself using one of the libraries listed on http://www.python-excel.org/ (I recommend openpyxl).

You can then control the excel-to-dataframe conversion yourself.


问:
Are all the classes containing business logic, domain objects?
So I have few doubts regarding calling something as domain object (and eventually placing the class under domain package) or not.

I have a micro-service whose responsibility is to do some calculations (without getting into actual business requirements, all it does is calculate some return of intereset based on given request). Now to achieve the calculations there are certain sub-calculations which need to take place and hence are composed in different classes respectively. But yes, these calculation do not need to be persisted in DB , and neither they have an ID (so definitely not an Entity or Aggregate). However these individual calculator classes (for the lack of terminology) do contain some complex business logic. Now, my question is, do these individual classes still qualify/classify as domain objects or should they be referred to as services ?

Feel free to ask for more clarifications around use case if need be.

Cheers !

答:
A simple test could be asking below questions  -

Does your “calculator” (as you refer it) hold the calculation result as an immutable state? — if the answer is yes then it is a Value Object.

Is the “Calculator” stateless and only exposes a “calculate” behaviour which accepts a request & returns a calculation result? — if the answer is yes then it is a Service, however, the “result” returned by this service may be classified as Value Object.


问:
MVC Core 2.0 EF Core SqlException: New transaction is not allowed because there are other threads running in the session
There are a lot of threads for this issue but most seem to come up in the context of someone trying to loop and save on an IQueryable instead of an IList, which is not what I'm doing.

I am having an issue with a context being passed between my controller and my Repository. I am having this issue elsewhere in my app, but an easy way to illustrate and recreate this is below.

First, I'm setting up my DbContext in Startup.cs as a service.

```<code>services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
</code>```

Then, I have a controller that it gets injected to. The first two saves work fine when I use the context straight from the controller, but when I use it from the repo, it errors out with the exception in the title. Note that it only errors if I save a record in the controller before I try to save it in my repo.

```<code> private ApplicationDbContext _context;
 private UserManager<ApplicationUser> _userManager;

 private ApplicationUser _user
    {
        get
        {
            return _userManager.GetUserAsync(User).Result;
        }
    }

 public InitiativesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    // GET: Initiatives
    public IActionResult Index()
    {

        Initiative i2 = new Initiative();
        i2.Id = 2;
        i2.InitiativeName = "testname";
        _context.Update(i2);
        _context.SaveChanges(); // Works fine

        var i4 = _context.Initiatives.SingleOrDefault(init => init.Id == 2);
        i4.InitiativeName = "blep";
        _context.Update(i4);
        _context.SaveChanges(); // Works fine

        InitiativeRepository initiativeRepository = new InitiativeRepository(_context, _user);

        var i= initiativeRepository.Get(2);
        i.InitiativeName = "blah";
        initiativeRepository.Update(i); //Throws exception

        var initiatives = initiativeRepository.GetAll();
        return View(initiatives);
    }
</code>```

Here is the repository class:

```<code>public class InitiativeRepository
{
    private ApplicationDbContext _context;
    private ApplicationUser _user;

    public InitiativeRepository(ApplicationDbContext context, ApplicationUser user)
    {
        _context = context;
        _user = user;
    }

    public Initiative Get(int id, bool eagerLoad = false)
    {
        if (!eagerLoad)
        {
            return _context.Initiatives.SingleOrDefault(i => i.Id == id);
        }
        else
        {
            return _context.Initiatives.Include(i => i.Tasks).ThenInclude(t => t.ActionItems).
                SingleOrDefault(i => i.Id == id);
        }
    }

    public List<Initiative> GetAll()
    {
        return _context.Initiatives.ToList();
    }

    public Initiative Update(Initiative Entity)
    {
        _context.Update(Entity);
        _context.SaveChanges(); // This line causes the exception.
        return Entity;
    }

}
</code>```

This should be the entry point for any DB writing, however, I am using ASP.NET identity and am autologged in for this session, so I'm not sure if it might be impacting this as well.

答:
I don't believe in dependency injection at all times do to something like this happening.  While it is annoying you may be better served either doing everything in your repo or else closing and disposing of your context via:

```<code>using(var context = new context("yourContext"))
{
   //dowork
   context.SaveChanges();
}
</code>```

What may be happening even though it should not be, and this is just a guess.  Is that the injection is catching the wrong state of the context when it is passed in.  You could just do a dependency injection in your constructor of the repo instead and then just do everything with CRUD operations directly in the repo.

```<code>private InitiativeRepository _initiativeRepository;

public InitiativesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
    _context = context;
    _userManager = userManager;
    _initiativeRepository = new InitiativeRepository(_context, _user);

}
</code>```

I do a pattern like above currently with .NET Core 2 Web Api with controllers.  I know any time I have kept a context and not closed it and then mixed that context with another state that uses it, I get in trouble.  I also had it beat into me not to use dependency injection for contexts so it is interesting with the new .NET Core stuff they are making that the default.  It probably will work great till larger databases and multi user apps have a lot of work being done.

Body:
There are a lot of threads for this issue but most seem to come up in the context of someone trying to loop and save on an IQueryable instead of an IList, which is not what I'm doing.

I am having an issue with a context being passed between my controller and my Repository. I am having this issue elsewhere in my app, but an easy way to illustrate and recreate this is below.

First, I'm setting up my DbContext in Startup.cs as a service.

services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Then, I have a controller that it gets injected to. The first two saves work fine when I use the context straight from the controller, but when I use it from the repo, it errors out with the exception in the title. Note that it only errors if I save a record in the controller before I try to save it in my repo.

 private ApplicationDbContext _context;
 private UserManager<ApplicationUser> _userManager;

 private ApplicationUser _user
    {
        get
        {
            return _userManager.GetUserAsync(User).Result;
        }
    }

 public InitiativesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    // GET: Initiatives
    public IActionResult Index()
    {

        Initiative i2 = new Initiative();
        i2.Id = 2;
        i2.InitiativeName = "testname";
        _context.Update(i2);
        _context.SaveChanges(); // Works fine

        var i4 = _context.Initiatives.SingleOrDefault(init => init.Id == 2);
        i4.InitiativeName = "blep";
        _context.Update(i4);
        _context.SaveChanges(); // Works fine

        InitiativeRepository initiativeRepository = new InitiativeRepository(_context, _user);

        var i= initiativeRepository.Get(2);
        i.InitiativeName = "blah";
        initiativeRepository.Update(i); //Throws exception

        var initiatives = initiativeRepository.GetAll();
        return View(initiatives);
    }

Here is the repository class:

public class InitiativeRepository
{
    private ApplicationDbContext _context;
    private ApplicationUser _user;

    public InitiativeRepository(ApplicationDbContext context, ApplicationUser user)
    {
        _context = context;
        _user = user;
    }

    public Initiative Get(int id, bool eagerLoad = false)
    {
        if (!eagerLoad)
        {
            return _context.Initiatives.SingleOrDefault(i => i.Id == id);
        }
        else
        {
            return _context.Initiatives.Include(i => i.Tasks).ThenInclude(t => t.ActionItems).
                SingleOrDefault(i => i.Id == id);
        }
    }

    public List<Initiative> GetAll()
    {
        return _context.Initiatives.ToList();
    }

    public Initiative Update(Initiative Entity)
    {
        _context.Update(Entity);
        _context.SaveChanges(); // This line causes the exception.
        return Entity;
    }

}

This should be the entry point for any DB writing, however, I am using ASP.NET identity and am autologged in for this session, so I'm not sure if it might be impacting this as well.

Body:
I don't believe in dependency injection at all times do to something like this happening.  While it is annoying you may be better served either doing everything in your repo or else closing and disposing of your context via:

using(var context = new context("yourContext"))
{
   //dowork
   context.SaveChanges();
}

What may be happening even though it should not be, and this is just a guess.  Is that the injection is catching the wrong state of the context when it is passed in.  You could just do a dependency injection in your constructor of the repo instead and then just do everything with CRUD operations directly in the repo.

private InitiativeRepository _initiativeRepository;

public InitiativesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
    _context = context;
    _userManager = userManager;
    _initiativeRepository = new InitiativeRepository(_context, _user);

}

I do a pattern like above currently with .NET Core 2 Web Api with controllers.  I know any time I have kept a context and not closed it and then mixed that context with another state that uses it, I get in trouble.  I also had it beat into me not to use dependency injection for contexts so it is interesting with the new .NET Core stuff they are making that the default.  It probably will work great till larger databases and multi user apps have a lot of work being done.


问:
What are the advantages of installing programs in AppData like Google Chrome?
I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?</p>

答:
The Chrome installer really ought to allow global installation (with elevation) in addition to per-user.  I don't want to have to maintain an installation for every user; I want to be able to centrally manage upgrades and so on.  Chrome doesn't allow that.

That said, the option to install per-user is quite nice, as it means no permissions issues.

OwnerDisplayName: Ravi Chhabra

LastEditorDisplayName: charlesroper

OwnerDisplayName: DrPizza


问:
Can I dynamically create onClick routines for X num of objects in Android
Here is what I'm trying to dot hard coded.  It doesn't allow me to access the iterator within the onClick function if I stick it in a loop.  Is it possible to do this dynamically?</p>

```<code>    cardBtns[0].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[1].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[2].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[3].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[4].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
</code>```

答:
To be used inside an interface a variable needs to be declared with the final keyword. However the iterator can't be final because its value has to change so you have to use a second variable.

```<code>for (int i = 0; i < 4; i++) {
    final int j = i;
    cardBtns[i].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.setText("Button " + String.valueOf(j));
        }
    });
}
</code>```

Body:
Here is what I'm trying to dot hard coded.  It doesn't allow me to access the iterator within the onClick function if I stick it in a loop.  Is it possible to do this dynamically?

    cardBtns[0].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[1].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[2].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[3].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    cardBtns[4].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

Body:
To be used inside an interface a variable needs to be declared with the final keyword. However the iterator can't be final because its value has to change so you have to use a second variable.

for (int i = 0; i < 4; i++) {
    final int j = i;
    cardBtns[i].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.setText("Button " + String.valueOf(j));
        }
    });
}


问:
"Fixed leading and trailing constraints may cause clipping" bug?
There's this other question here that addresses a similar issue, but in that case Xcode's behavior is correct, just annoying.

In my case, however, I think it's actually a bug:

That label can have an unlimited number of lines, so it'll never be clipped, the text will just break.

It works fine with every localization:

I want the label to be centered and I want the text to be at least 20 pixels away from the margins, so I set fixed constraints for the leading and trailing. Xcode wants me to change one of them to a "greater than or equal" constraint, but in that case the text won't be perfectly centered (I tried).

All I want is centered text that won't be too close to the margins, but now I can't accomplish that without triggering that warning.

Any ideas on how to fix this? Is it really a bug, or am I doing something wrong?

Edit: Here's a screenshot showing the error. The constraints aren't directly in a view controller, but in a subview that I use as the backgroun for a table view. If I remove those constraints the warning goes away; if I add them back it shows up again. I tried this in a new project and couldn't reproduce it, I have no idea why it's happening here.

Edit:

Here's another example. When the right constraint is set to "greater than or equal" all's well:

As soon as I set it to "equal", boom:

答:
If you're still looking for an answer, in your particular case, try setting a proportional width on your label and center horizontally in the view controller's view.

Clear all your constraints on the label, right-click drag from the label to the Background View and select Equal Widths, Center Horizontally in Container, and Center Vertically in Container from the popup menu.

Now since you said you wanted 20px margin both to the left and right of your label, edit the Multiplier on the equal width constraint and set it to widthOfBackgroundView - 40)/widthOfBackgroundView.

So let's say the width of your background view is 414, the multiplier is supposed to be 374/414.

The reason for the width minus 40 multiplier is it covers 20px on either sides of the label. This should make your warning go away and layout the label the way you're expecting it to be.

I had the same issue and was able to fix the warnings this way. Hope this helps!


问:
PHP array_search not working when deleting entries
This sample code is giving me a headache. I'm trying to get 2 random values from the array. Delete the 2 entries that was chosen, and then continue until all elements is chosen. My problem is that the first 1-2 picks works fine, but then is chosen values that's not in the array, some times the same value is chosen 2 times...when removing the 2 unset-lines the code is ok...
I belive it's about the reindexing of the array after deleting, but the line "$number=array_values($number)" should do the job...</p>

```<code>    <?php

$number=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);

//var_dump($number)." - ";//

for ($p = 1; $p <= 5; $p++) {
    echo "Nr. :".$p."</br>";
    echo implode(",",$number)."</br></br>";

    $udtrak = array_rand($number,2); // udvælger 2
    $pos[0] = array_search($udtrak[0], $number);
    $pos[1] = array_search($udtrak[1], $number);
    echo "Number: ".$number[$pos[0]]." Found at: " . $pos[0]."</br>";
    echo "Number: ".$number[$pos[1]]." Found at: " . $pos[1]."</br>";

    //unset($number[$pos[0]]);
    //unset($number[$pos[1]]);
    //var_dump($pos);

$number=array_values($number);

echo implode(",",$number)."</br></br>";
} // for $p

?>
</code>```

答:
array_rand() returns an array of keys.
array_search() searches by value and returns the key, if the value is found in the input.

So your code snippets selects random keys of $number and then searches values that equal that key. Thats not what you want.

Theres no need for array_search, simply use the keys that array_rand() selects:

```<code>$number=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);
for ($p = 1; $p <= 5; $p++) {
    echo "Nr. :".$p."</br>";
    echo implode(",",$number)."</br></br>";

    $pos = array_rand($number,2);
    echo "Number: ".$number[$pos[0]]." Found at: " . $pos[0]."</br>";
    echo "Number: ".$number[$pos[1]]." Found at: " . $pos[1]."</br>";

    unset($number[$pos[0]]);
    unset($number[$pos[1]]);

    $number=array_values($number);

    echo implode(",",$number)."</br></br>";
} // for $p
</code>```

Body:
This sample code is giving me a headache. I'm trying to get 2 random values from the array. Delete the 2 entries that was chosen, and then continue until all elements is chosen. My problem is that the first 1-2 picks works fine, but then is chosen values that's not in the array, some times the same value is chosen 2 times...when removing the 2 unset-lines the code is ok...
I belive it's about the reindexing of the array after deleting, but the line "$number=array_values($number)" should do the job...

    <?php

$number=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);

//var_dump($number)." - ";//

for ($p = 1; $p <= 5; $p++) {
    echo "Nr. :".$p."
";
    echo implode(",",$number)."

";

    $udtrak = array_rand($number,2); // udvælger 2
    $pos[0] = array_search($udtrak[0], $number);
    $pos[1] = array_search($udtrak[1], $number);
    echo "Number: ".$number[$pos[0]]." Found at: " . $pos[0]."
";
    echo "Number: ".$number[$pos[1]]." Found at: " . $pos[1]."
";

    //unset($number[$pos[0]]);
    //unset($number[$pos[1]]);
    //var_dump($pos);

$number=array_values($number);

echo implode(",",$number)."

";
} // for $p

?>

Body:
array_rand() returns an array of keys.
array_search() searches by value and returns the key, if the value is found in the input.

So your code snippets selects random keys of $number and then searches values that equal that key. Thats not what you want.

Theres no need for array_search, simply use the keys that array_rand() selects:

$number=array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);//range(1,10);
for ($p = 1; $p <= 5; $p++) {
    echo "Nr. :".$p."</br>";
    echo implode(",",$number)."</br></br>";

    $pos = array_rand($number,2);
    echo "Number: ".$number[$pos[0]]." Found at: " . $pos[0]."</br>";
    echo "Number: ".$number[$pos[1]]." Found at: " . $pos[1]."</br>";

    unset($number[$pos[0]]);
    unset($number[$pos[1]]);

    $number=array_values($number);

    echo implode(",",$number)."</br></br>";
} // for $p


问:
Drop Down List with class array on jsp
I need know, how to show in Drop Down list on a jsp, only one attribute of a arraylist of a class,i mean.

I have this class:

public class Estacionamientos {
    private String nombreEstacionamiento;
    private int numeroTicket;
    private int precioEstacionamiento;

    public Estacionamientos() {
    }

    public Estacionamientos(String nombreEstacionamiento, int numeroTicket, int precioEstacionamiento) {
        this.nombreEstacionamiento = nombreEstacionamiento;
        this.numeroTicket = numeroTicket;
        this.precioEstacionamiento = precioEstacionamiento;
    }

    public String getNombreEstacionamiento() {
        return nombreEstacionamiento;
    }

    public void setNombreEstacionamiento(String nombreEstacionamiento) {
        this.nombreEstacionamiento = nombreEstacionamiento;
    }

    public int getNumeroTicket() {
        return numeroTicket;
    }

    public void setNumeroTicket(int numeroTicket) {
        this.numeroTicket = (int) (Math.random() * (1000 - 1) + 1);
    }

    public int getPrecioEstacionamiento() {
        return precioEstacionamiento;
    }

    public void setPrecioEstacionamiento(int precioEstacionamiento) {
        this.precioEstacionamiento = precioEstacionamiento;
    }

    @Override
    public String toString() {
        return "Estacionamientos{" + "nombreEstacionamiento=" + nombreEstacionamiento + ", numeroTicket=" + numeroTicket + ", precioEstacionamiento=" + precioEstacionamiento + '}';
    }
    ```
</div>
</div>
</p>

<p>this array </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-js lang-js prettyprint-override"><code>public class ListarEstacionamientos {

    Estacionamientos est = new Estacionamientos();
    ArrayList<Estacionamientos> list = new ArrayList<Estacionamientos>() {
        {
            add(new Estacionamientos("Estación Central", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Mall Alameda", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Mall Providencia", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Aparcamiento Quinta Normal", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Estacionamiento Parque Arauco Maipú", 2000, est.getNumeroTicket()));
        }
    };

}</code>```

but i dont know how to show only the attibute name of Estacionamientos in a drop down list on a JSP form...

thanks in advance.

答:
Assuming that you know how to pass an array from the java to your jsp, run this code in the dropdown logic.    </p>

```<code>      <c:forEach items="${yourArray}" var="firstArr">
          <c:forEach items="${firstArr}" var="innerArr"> // firstVar will hold your object array
             <c:out value="${innerArr.field1}" /> // on iterating the object array
          </c:forEach>
      </c:forEach>
</code>```

Title: Drop Down List with class array on jsp

Body:
I need know, how to show in Drop Down list on a jsp, only one attribute of a arraylist of a class,i mean.

I have this class:

public class Estacionamientos {
    private String nombreEstacionamiento;
    private int numeroTicket;
    private int precioEstacionamiento;

    public Estacionamientos() {
    }

    public Estacionamientos(String nombreEstacionamiento, int numeroTicket, int precioEstacionamiento) {
        this.nombreEstacionamiento = nombreEstacionamiento;
        this.numeroTicket = numeroTicket;
        this.precioEstacionamiento = precioEstacionamiento;
    }

    public String getNombreEstacionamiento() {
        return nombreEstacionamiento;
    }

    public void setNombreEstacionamiento(String nombreEstacionamiento) {
        this.nombreEstacionamiento = nombreEstacionamiento;
    }

    public int getNumeroTicket() {
        return numeroTicket;
    }

    public void setNumeroTicket(int numeroTicket) {
        this.numeroTicket = (int) (Math.random() * (1000 - 1) + 1);
    }

    public int getPrecioEstacionamiento() {
        return precioEstacionamiento;
    }

    public void setPrecioEstacionamiento(int precioEstacionamiento) {
        this.precioEstacionamiento = precioEstacionamiento;
    }

    @Override
    public String toString() {
        return "Estacionamientos{" + "nombreEstacionamiento=" + nombreEstacionamiento + ", numeroTicket=" + numeroTicket + ", precioEstacionamiento=" + precioEstacionamiento + '}';
    }

this array

public class ListarEstacionamientos {

    Estacionamientos est = new Estacionamientos();
    ArrayList<Estacionamientos> list = new ArrayList<Estacionamientos>() {
        {
            add(new Estacionamientos("Estación Central", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Mall Alameda", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Mall Providencia", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Aparcamiento Quinta Normal", 2000, est.getNumeroTicket()));
            add(new Estacionamientos("Estacionamiento Parque Arauco Maipú", 2000, est.getNumeroTicket()));
        }
    };

}

but i dont know how to show only the attibute name of Estacionamientos in a drop down list on a JSP form...

thanks in advance.

Body:
Assuming that you know how to pass an array from the java to your jsp, run this code in the dropdown logic.

      <c:forEach items="${yourArray}" var="firstArr">
          <c:forEach items="${firstArr}" var="innerArr"> // firstVar will hold your object array
             <c:out value="${innerArr.field1}" /> // on iterating the object array
          </c:forEach>
      </c:forEach>


问:
django rest framework installation fails
How do I install the REST framework in django?

The following command throws an error on Mac OS X:

```<code>pip install djangorestframework-jsonapi
</code>```

Error:

Could not find a version that satisfies the
  requirement djangorestframework-jsonapi (from versions) No matching
  distribution found for djangorestframework-jsonapi

答:
It's not best practice to sudo install like Yogesh suggested. This is because: 1. Isolation is important and 2. It's always good to know exactly what your dependencies are for your application.

With that being said, it's best to install your package in either a virtualenv or docker environment.

virtualenv env
source env/bin/activate
pip install djangorestframework-jsonapi

Body:
How do I install the REST framework in django?

The following command throws an error on Mac OS X:

pip install djangorestframework-jsonapi

Error:

Could not find a version that satisfies the
  requirement djangorestframework-jsonapi (from versions) No matching
  distribution found for djangorestframework-jsonapi


问:
Efficiently selecting latest charge per patient
I've got three tables in SQL Server 2005 (relevant rows included):

```<code>Patient (560K rows, has many Appts)
    ID (PK, Clustered)
Appt (5.8M rows, has many ApptCPTs)
    ID (PK, Unique, Non-clustered)
    PatientID (Indexed, Non-unique, Non-clustered)
ApptCPT (13.4M rows)
    ID (PK, Clustered)
    ApptID (Indexed, Non-unique, Non-clustered)
    CPTID (Indexed, Non-unique, Non-clustered)
</code>```

I want to get the latest ApptCPT for each CPT code, for each patient, but the query I've got so far takes about a minute to return ~7M rows.

My current query:

```<code>SELECT
    p.ID AS PatientID,
    MAX(ac.ID) AS ApptCPTID,
    ac.CPTID
FROM
    Patient p
INNER JOIN Appt a ON a.PatientID = p.ID
INNER JOIN ApptCPT ac ON ac.ApptID = a.ID
GROUP BY
    p.ID, ac.CPTID
ORDER BY
    p.ID, ac.CPTID
</code>```

Example output:

```<code>PatientID    ApptCPTID    CPTID
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258166      77080
123456789    18627813     80053
123456789    18627814     80061
</code>```

If I take the MAX out and put ac.ID in the GROUP BY clause, I can see that I'm getting the correct data with my original query, because it's getting the last ApptCPT containing that CPTID for that patient, but it's horribly slow. For reference, here's the same output not using the MAX clause:

```<code>PatientID    ApptCPTID    CPTID
123456789    18126508     3088
123456789    4596004      3088
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    4595928      3551
123456789    9989218      3551
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258050      77057
123456789    5258166      77080
123456789    4595932      80053
123456789    18126505     80053
123456789    9989223      80053
123456789    18627813     80053
123456789    18627814     80061
</code>```

Anyone have any ideas for making it (hopefully) much, much faster?

答:
Have you tried using ROW_NUMBER() instead of the GROUP BY to find the first row?  Sometimes I find it gives me a faster result, especially if the table has the right indexes.</p>

```<code>SELECT *
  FROM
    (
      SELECT p.ID AS PatientID,
            ApptCPTID
          , ac.CPTID
          , RowId = ROW_NUMBER() OVER (PARTITION BY PatientId, CptId, ORDER BY PatientId, CptId, ApptCptId desc  )
       FROM Patient p
      INNER JOIN Appt a
         ON a.PatientID = p.ID
      INNER JOIN ApptCPT ac
         ON ac.ApptID = a.ID
    ) qq
 WHERE qq.RowId = 1
 ORDER BY Id, CPTId
</code>```

Body:
I've got three tables in SQL Server 2005 (relevant rows included):

Patient (560K rows, has many Appts)
    ID (PK, Clustered)
Appt (5.8M rows, has many ApptCPTs)
    ID (PK, Unique, Non-clustered)
    PatientID (Indexed, Non-unique, Non-clustered)
ApptCPT (13.4M rows)
    ID (PK, Clustered)
    ApptID (Indexed, Non-unique, Non-clustered)
    CPTID (Indexed, Non-unique, Non-clustered)

I want to get the latest ApptCPT for each CPT code, for each patient, but the query I've got so far takes about a minute to return ~7M rows.

My current query:

SELECT
    p.ID AS PatientID,
    MAX(ac.ID) AS ApptCPTID,
    ac.CPTID
FROM
    Patient p
INNER JOIN Appt a ON a.PatientID = p.ID
INNER JOIN ApptCPT ac ON ac.ApptID = a.ID
GROUP BY
    p.ID, ac.CPTID
ORDER BY
    p.ID, ac.CPTID

Example output:

PatientID    ApptCPTID    CPTID
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258166      77080
123456789    18627813     80053
123456789    18627814     80061

If I take the MAX out and put ac.ID in the GROUP BY clause, I can see that I'm getting the correct data with my original query, because it's getting the last ApptCPT containing that CPTID for that patient, but it's horribly slow. For reference, here's the same output not using the MAX clause:

PatientID    ApptCPTID    CPTID
123456789    18126508     3088
123456789    4596004      3088
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    4595928      3551
123456789    9989218      3551
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258050      77057
123456789    5258166      77080
123456789    4595932      80053
123456789    18126505     80053
123456789    9989223      80053
123456789    18627813     80053
123456789    18627814     80061

Anyone have any ideas for making it (hopefully) much, much faster?

Body:
Have you tried using ROW_NUMBER() instead of the GROUP BY to find the first row?  Sometimes I find it gives me a faster result, especially if the table has the right indexes.

SELECT *
  FROM
    (
      SELECT p.ID AS PatientID,
            ApptCPTID
          , ac.CPTID
          , RowId = ROW_NUMBER() OVER (PARTITION BY PatientId, CptId, ORDER BY PatientId, CptId, ApptCptId desc  )
       FROM Patient p
      INNER JOIN Appt a
         ON a.PatientID = p.ID
      INNER JOIN ApptCPT ac
         ON ac.ApptID = a.ID
    ) qq
 WHERE qq.RowId = 1
 ORDER BY Id, CPTId


问:
Why cant i create a foreign key here? ERROR 1215 (HY000): Cannot add foreign key constraint
Im not sure what im doing wrong here i have read the spec but still cant figure it out.I want to add user id as a forign key to my store table but i keep getting error 1215.

My sql code:

```<code>CREATE TABLE Store (
id int,
storePersistentId varchar(255),
storename varchar(255),
user_id int,
PRIMARY KEY (id),
FOREIGN KEY (user_id)
    REFERENCES user(id)
);
</code>```

Store.java

```<code>@Entity
public class Store {

//every entity requires an id, and we can make it auto generated
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String storePersistentId;
private String storename;

@ManyToOne
public User user;

public Store(User user,String storePersistentId){

}

public Store(){

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getStorename() {
    return storename;
}

public void setStorename(String storename) {
    this.storename = storename;
}

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

public String getStorePersistentId() {
    return storePersistentId;
}

public void setStorePersistentId(String storePersistentId) {
    this.storePersistentId = storePersistentId;
}

}
</code>```

User.java

```<code>@Entity
public class User {

@Id
@Column
private int id;

private String username;
private String password;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}

public User() {
}
}
</code>```

Any help would be great.
its probally some small mistake but i need another set of eyes to check it out please.

答:
```<code>mysql> create table store(id int primary key NOT NULL AUTO_INCREMENT,
username varchar(255),
password varchar(255),
user_id int, foreign key(user_id)
references user(id));
</code>```

Got it eventually.

Body:
Im not sure what im doing wrong here i have read the spec but still cant figure it out.I want to add user id as a forign key to my store table but i keep getting error 1215.

My sql code:

CREATE TABLE Store (
id int,
storePersistentId varchar(255),
storename varchar(255),
user_id int,
PRIMARY KEY (id),
FOREIGN KEY (user_id)
    REFERENCES user(id)
);

Store.java

@Entity
public class Store {

//every entity requires an id, and we can make it auto generated
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String storePersistentId;
private String storename;

@ManyToOne
public User user;

public Store(User user,String storePersistentId){

}

public Store(){

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getStorename() {
    return storename;
}

public void setStorename(String storename) {
    this.storename = storename;
}

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

public String getStorePersistentId() {
    return storePersistentId;
}

public void setStorePersistentId(String storePersistentId) {
    this.storePersistentId = storePersistentId;
}

}

User.java

@Entity
public class User {

@Id
@Column
private int id;

private String username;
private String password;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}

public User() {
}
}

Any help would be great.
its probally some small mistake but i need another set of eyes to check it out please.

Body:
mysql> create table store(id int primary key NOT NULL AUTO_INCREMENT,
username varchar(255),
password varchar(255),
user_id int, foreign key(user_id)
references user(id));

Got it eventually.


问:
Exclude code from the cart page in Woocommerce
In my Woocommerce Shop, I have added a quantity box next to the add to cart button on archive pages using this code:

```<code>add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {

        $html = '<a rel="nofollow" data-product_id="'. $product->id .'" onclick="addToCartLink(this,' . $product->id .')" class="add_to_cart_button product_type_simple button primary is-flat mb-0 is-small">הוסף לסל</a>';
        // $html = '<a onclick="addToCartLink(this,'. $product->id .')">הוסף לסל</a>';

        $html .= '<div class="quantity buttons_added">';
        $html .= '<input type="button"  value="-"  class="minus button is-form">';
        $html .= '<input type="number" id="quantity_'. $product->id .'" class="input-text qty text" step="1" min="0" max="9999" name="quantity" value="1" title="כמות" size="4" pattern="[0-9]*" inputmode="numeric" >';
        $html .= '<input type="button" value="+" class="plus button is-form">';
        $html .= '</div>';
    }
    return $html;
}
</code>```

In cart page, I have created a custom Cross-Sells products carousel. So I need to avoid this code working in the cart page and so the Cross-Sells products add to cart buttons will be the default woocommerce ones.

How can I exclude the cart page in my code?

答:
You just need to add in the existing if statement this condition: ! is_cart()

So your code will be:

```<code>add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() && ! is_cart() ) {

        $html = '<a rel="nofollow" data-product_id="'. $product->id .'" onclick="addToCartLink(this,' . $product->id .')" class="add_to_cart_button product_type_simple button primary is-flat mb-0 is-small">הוסף לסל</a>';
        //$html = '<a onclick="addToCartLink(this,'. $product->id .')">הוסף לסל</a>';

        $html .= '<div class="quantity buttons_added">';
        $html .= '<input type="button"  value="-"  class="minus button is-form">';
        $html .= '<input type="number" id="quantity_'. $product->id .'" class="input-text qty text" step="1" min="0" max="9999" name="quantity" value="1" title="כמות" size="4" pattern="[0-9]*" inputmode="numeric" >';
        $html .= '<input type="button" value="+" class="plus button is-form">';
        $html .= '</div>';

    }
    return $html;
}
</code>```

This should solve your problem.

Related official documentation: WooCommerce Conditional tags | is_cart()

Body:
In my Woocommerce Shop, I have added a quantity box next to the add to cart button on archive pages using this code:

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {

        $html = 'id .'" onclick="addToCartLink(this,' . $product->id .')" class="add_to_cart_button product_type_simple button primary is-flat mb-0 is-small">הוסף לסל';
        // $html = 'id .')">הוסף לסל';

        $html .= '
';
        $html .= '<input type="button"  value="-"  class="minus button is-form">';
        $html .= '<input type="number" id="quantity_'. $product->id .'" class="input-text qty text" step="1" min="0" max="9999" name="quantity" value="1" title="כמות" size="4" pattern="[0-9]*" inputmode="numeric" >';
        $html .= '<input type="button" value="+" class="plus button is-form">';
        $html .= '
';
    }
    return $html;
}

In cart page, I have created a custom Cross-Sells products carousel. So I need to avoid this code working in the cart page and so the Cross-Sells products add to cart buttons will be the default woocommerce ones.

How can I exclude the cart page in my code?

Body:
You just need to add in the existing if statement this condition: ! is_cart()

So your code will be:

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() && ! is_cart() ) {

        $html = '<a rel="nofollow" data-product_id="'. $product->id .'" onclick="addToCartLink(this,' . $product->id .')" class="add_to_cart_button product_type_simple button primary is-flat mb-0 is-small">הוסף לסל</a>';
        //$html = '<a onclick="addToCartLink(this,'. $product->id .')">הוסף לסל</a>';

        $html .= '<div class="quantity buttons_added">';
        $html .= '<input type="button"  value="-"  class="minus button is-form">';
        $html .= '<input type="number" id="quantity_'. $product->id .'" class="input-text qty text" step="1" min="0" max="9999" name="quantity" value="1" title="כמות" size="4" pattern="[0-9]*" inputmode="numeric" >';
        $html .= '<input type="button" value="+" class="plus button is-form">';
        $html .= '</div>';

    }
    return $html;
}

This should solve your problem.

Related official documentation: WooCommerce Conditional tags | is_cart()