问:
Problem in c# windows service using linq
I am having a bit of a problem in a windows service I have developed, I seem to be having a DB conflict using linq, I think i understand why the problem is happening but would like to get some advice in resolving it.

I have a database with a table that holds messages that need to be sent every at certain intervals from the service here is my code snippet.

```<code>protected override void OnStart(string[] args)
    {
        timer = new Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(TimeElapsed);
        timer.Interval = 10000;
        timer.Start();
        EventLogger.LogEvent("Timer started succesfuly", EventLogEntryType.Information);

    }

    protected override void OnStop()
    {
        if (timer != null)
            timer.Stop();
        EventLogger.LogEvent("Timer stopped.", EventLogEntryType.Information);
    }

    private void TimeElapsed(object source, ElapsedEventArgs e)
    {
        try
        {
            EventLogger.LogEvent("Checking for reversals", EventLogEntryType.Information);
            //We now need to check for reversals that are waiting to be sent
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);

            if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
        }
        catch (Exception ex)
        {
            EventLogger.LogEvent(ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
        }
    }
</code>```

The error I get now is

Row not found or changed.
   at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges()
   at EftcObReversalService.EftcObReversalService.TimeElapsed(Object source, ElapsedEventArgs e)

From what I can see is this is caused from the following code,

```<code>if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
</code>```

What happens here is, I read in from the table what is marked with a "WAITING_TO_SEND", once I have that I decide to mark the entries with a "PENDING" status. I do this as i do not want the entries to be read in again when the timer swings through and this thread has not completed yet.

Once I have marked all the entires I then handle each one in the SendReversal method, where I also mark the status as "COMPLETED" when it was completed OK or change the status back to "WAITING_TO_SEND".

I think this error is being cause from the 2 db.SubmitChanges, as the entry has changes and been written by the first submit and is different from the second submit?

If anyone has any thoughts or solutions please let me know.

答:
Just a hunch, but I think you are on the right track. Try removing the first call to db.SaveChanges().

```<code>if (reversals.Any())
{
    foreach (var rev in reversals)
    {
        MarkReversal(rev);
    }

    //We now need to send the reversal
    foreach (var rev in reversals)
    {
        SendReversal(rev);
    }

    db.SubmitChanges();
}
</code>```

EDIT:
Could you not do this:

```<code>if (reversals.Any())
{
    foreach (var rev in reversals)
    {
        MarkReversal(rev);
        SendReversal(rev);
    }

    db.SubmitChanges();
}
</code>```

Do the two calls in the same context for each object.

Body:
I am having a bit of a problem in a windows service I have developed, I seem to be having a DB conflict using linq, I think i understand why the problem is happening but would like to get some advice in resolving it.

I have a database with a table that holds messages that need to be sent every at certain intervals from the service here is my code snippet.

protected override void OnStart(string[] args)
    {
        timer = new Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(TimeElapsed);
        timer.Interval = 10000;
        timer.Start();
        EventLogger.LogEvent("Timer started succesfuly", EventLogEntryType.Information);

    }

    protected override void OnStop()
    {
        if (timer != null)
            timer.Stop();
        EventLogger.LogEvent("Timer stopped.", EventLogEntryType.Information);
    }

    private void TimeElapsed(object source, ElapsedEventArgs e)
    {
        try
        {
            EventLogger.LogEvent("Checking for reversals", EventLogEntryType.Information);
            //We now need to check for reversals that are waiting to be sent
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);

            if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
        }
        catch (Exception ex)
        {
            EventLogger.LogEvent(ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
        }
    }

The error I get now is

Row not found or changed.
   at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges()
   at EftcObReversalService.EftcObReversalService.TimeElapsed(Object source, ElapsedEventArgs e)

From what I can see is this is caused from the following code,

if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }

What happens here is, I read in from the table what is marked with a "WAITING_TO_SEND", once I have that I decide to mark the entries with a "PENDING" status. I do this as i do not want the entries to be read in again when the timer swings through and this thread has not completed yet.

Once I have marked all the entires I then handle each one in the SendReversal method, where I also mark the status as "COMPLETED" when it was completed OK or change the status back to "WAITING_TO_SEND".

I think this error is being cause from the 2 db.SubmitChanges, as the entry has changes and been written by the first submit and is different from the second submit?

If anyone has any thoughts or solutions please let me know.

Body:
Just a hunch, but I think you are on the right track. Try removing the first call to db.SaveChanges().

if (reversals.Any())
{
    foreach (var rev in reversals)
    {
        MarkReversal(rev);
    }

    //We now need to send the reversal
    foreach (var rev in reversals)
    {
        SendReversal(rev);
    }

    db.SubmitChanges();
}

EDIT:
Could you not do this:

if (reversals.Any())
{
    foreach (var rev in reversals)
    {
        MarkReversal(rev);
        SendReversal(rev);
    }

    db.SubmitChanges();
}

Do the two calls in the same context for each object.


来源: stackexchange

问:
Center UIButton to Superview class programmatically (Swift 3)
I'm trying to center button in the view within a UIStackView subclass.

```<code>//  ButtonsController.swift
//  player

@IBDesignable class ButtonsController: UIStackView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupControls()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        setupControls()
    }

    private func setupControls(){
        //Buttons variables
        let playButton = UIButton()
        playButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        addArrangedSubview(playButton)
}
</code>```

In the Storyboard I've create Horizontal Stack View and set it to custom class ButtonsController. I want Play button to be centered within that view, that's why I use "self.centerXAnchor" as reference to Superview.

But simulator crash with an error:

Terminating app due to uncaught exception 'NSGenericException',
  reason: 'Unable to activate constraint with anchors
  (NSLayoutXAxisAnchor:0x60800026c680 "UIButton:0x7feba5d112f0.centerX")
  and (NSLayoutXAxisAnchor:0x60800026c700
  "player.ButtonsController:0x7feba5c0e390.centerX") because they have
  no common ancestor.  Does the constraint or its anchors reference
  items in different view hierarchies?  That's illegal.'

How I actually can reference to Superview within that class?

答:
First problem is, you are trying to add a constraint (which references other views) before adding your view as subview. You should add it as subview first, then create constraints. That will get rid of the crash.

```<code>addArrangedSubview(playButton)
playButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
</code>```

Also, I don't know what you are trying to achieve here, why you are using a UIStackView as container. Bu that constraint will probably cause trouble for you. You are adding your UIButton as "arranged subview", which means its constraints will be created automatically. You can activate some constraints like width if you configured your UIStackView accordingly (its distribution propery etc.). But centerX is problematic on a horizontal stack view. You can try centering your stack view inside its superview or instead of adding your uibutton as arrangedsubview, adding it as subview:

```<code>addSubview(playButton)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to center button in the view within a UIStackView subclass.

//  ButtonsController.swift
//  player

@IBDesignable class ButtonsController: UIStackView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupControls()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        setupControls()
    }

    private func setupControls(){
        //Buttons variables
        let playButton = UIButton()
        playButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        addArrangedSubview(playButton)
}

In the Storyboard I've create Horizontal Stack View and set it to custom class ButtonsController. I want Play button to be centered within that view, that's why I use "self.centerXAnchor" as reference to Superview.

But simulator crash with an error:

Terminating app due to uncaught exception 'NSGenericException',
  reason: 'Unable to activate constraint with anchors
  (NSLayoutXAxisAnchor:0x60800026c680 "UIButton:0x7feba5d112f0.centerX")
  and (NSLayoutXAxisAnchor:0x60800026c700
  "player.ButtonsController:0x7feba5c0e390.centerX") because they have
  no common ancestor.  Does the constraint or its anchors reference
  items in different view hierarchies?  That's illegal.'

How I actually can reference to Superview within that class?

Body:
First problem is, you are trying to add a constraint (which references other views) before adding your view as subview. You should add it as subview first, then create constraints. That will get rid of the crash.

addArrangedSubview(playButton)
playButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true

Also, I don't know what you are trying to achieve here, why you are using a UIStackView as container. Bu that constraint will probably cause trouble for you. You are adding your UIButton as "arranged subview", which means its constraints will be created automatically. You can activate some constraints like width if you configured your UIStackView accordingly (its distribution propery etc.). But centerX is problematic on a horizontal stack view. You can try centering your stack view inside its superview or instead of adding your uibutton as arrangedsubview, adding it as subview:

addSubview(playButton)


问:
Why should I practice Test Driven Development and how should I start?
Lots of people talk about writing tests for their code before they start writing their code. This practice is generally known as Test Driven Development or TDD for short. What benefits do I gain from writing software this way? How do I get started with this practice?</p>

答:
Benefits

You figure out how to compartmentalize your code

You figure out exactly what you want your code to do

You know how it supposed to act and, down the road, if refactoring breaks anything

Gets you in the habit of making sure your code always knows what it is supposed to do

Getting Started

Just do it. Write a test case for what you want to do, and then write code that should pass the test. If you pass your test, great, you can move on to writing cases where your code will always fail (2+2 should not equal 5, for example).

Once all of your tests pass, write your actual business logic to do whatever you want to do.

If you are starting from scratch make sure you find a good testing suite that is easy to use. I like PHP so PHPUnit or SimpleTest work well. Almost all of the popular languages have some xUnit testing suite available to help build and automate testing.

ContentLicense: CC BY-SA 2.5


问:
How can I run an external program from C and parse its output?
I've got a utility that outputs a list of files required by a game.  How can I run that utility within a C program and grab its output so I can act on it within the same program?

UPDATE: Good call on the lack of information.  The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux.  Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).

答:
For simple problems in Unix-ish environments try popen().

From the man page:

The popen() function opens a process by creating a pipe, forking and invoking the shell.

If you use the read mode this is exactly what you asked for. I don't know if it is implemented in Windows.

For more complicated problems you want to look up inter-process communication.

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: dmckee

LastEditorDisplayName: dmckee


问:
Visual Studio Text Box Wrap Function
How can I make my text wrap automatically to the next line when I am writing text in a textbox rather than keeps on typing in one line?</p>

答: Make your text box multi-line in the property settings.</p>

OwnerDisplayName: David Bonnici

Title: Visual Studio Text Box Wrap Function

LastEditorDisplayName: DanHerbert

OwnerDisplayName: TheTXI


问:
Ajax Post returning "Object XMLHttpReqest" error
Can someone offer some help with my problem please?

I have the following code:

```<code>        function InsertNewMeeting(tripID, contact1ID, contact2ID) {
        $.ajax({
            type: "POST",
            url: "RetrieveSites.aspx/InsertNewMeeting",
            data: "{'tripID': '" + tripID + "','contact1ID: '" + contact1ID + "','contact2ID', '" + contact2ID + "'}",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (msg) { alert('ok'); },
            error: function (msg) {alert(msg);}
        });
    }
</code>```

This is meant to call a WebService to post 3 integer values.  The WebService works 100%.

However, when I'm calling the function from the web page, all I get is a "Object XMLHttpRequest" error.

I've examined all parameters that are passed, they are 100% ok.

Is there anything obvious that I'm missing or should be doing?

答:
Your single quotes in your string are all over the place.

The data you send will be this:

```<code>{'tripID': '[tripID]','contact1ID: '[contact1ID]','contact2ID', '[contact2ID]'}
</code>```

Whereas it appears it should be this:

```<code>{'tripID': '[tripID]','contact1ID': '[contact1ID]','contact2ID': '[contact2ID]'}
</code>```

Body:
Can someone offer some help with my problem please?

I have the following code:

        function InsertNewMeeting(tripID, contact1ID, contact2ID) {
        $.ajax({
            type: "POST",
            url: "RetrieveSites.aspx/InsertNewMeeting",
            data: "{'tripID': '" + tripID + "','contact1ID: '" + contact1ID + "','contact2ID', '" + contact2ID + "'}",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (msg) { alert('ok'); },
            error: function (msg) {alert(msg);}
        });
    }

This is meant to call a WebService to post 3 integer values.  The WebService works 100%.

However, when I'm calling the function from the web page, all I get is a "Object XMLHttpRequest" error.

I've examined all parameters that are passed, they are 100% ok.

Is there anything obvious that I'm missing or should be doing?

Body:
Your single quotes in your string are all over the place.

The data you send will be this:

{'tripID': '[tripID]','contact1ID: '[contact1ID]','contact2ID', '[contact2ID]'}

Whereas it appears it should be this:

{'tripID': '[tripID]','contact1ID': '[contact1ID]','contact2ID': '[contact2ID]'}


问:
Determining Roles VB.NET
So firstly I have no code to show as I'm trying to get my head around how to do this first.

So I have a website that has 3 account pages (Patient, Doctor, Admin) that have 3 different pages for these. There is 3 tables named Patient, Doctor and Admin with account/log in and registered details in them. There is also a field in each of these tables called Role and for Patient table I have the word Patient in the field for each record and the same for Doctor and Admin.

In my login page I need to grab these to determine their login. So if patient is logged in then in the masterpage the patient accountlink will turn visible and so on.

How do i grab all 3 of these roles and determine an if, store in session, and use the session in the masterpage to show whichever link.

Sorry if this is confusing.

答:
What you need to do is have one main table where all the login details go. In this table, have a column called Role and when a new account is made, make it also input into the table, the role of the person.
If you need the other tables for other things, then use an if else statement to also make the information be input into the table that matches its role. (so that means, info input into two tables). This makes it a lot easier.

Then, on the page where the user is redirected after they log in, this is where you write the code to check for the user's role.

```<code>sql = "SELECT Role From tablename WHERE username = '"& textbox.text &"'"
</code>```

Search the main table using the username of the user to find the role and then use an if statement to make the specific links show.

```<code>If sql = Patient then
    <code here>
Else if sql = Admin then
    <code here>
Else if sql = Doctor then
    <code here>
End if
</code>```

Title: Determining Roles VB.NET

Body:
What you need to do is have one main table where all the login details go. In this table, have a column called Role and when a new account is made, make it also input into the table, the role of the person.
If you need the other tables for other things, then use an if else statement to also make the information be input into the table that matches its role. (so that means, info input into two tables). This makes it a lot easier.

Then, on the page where the user is redirected after they log in, this is where you write the code to check for the user's role.

sql = "SELECT Role From tablename WHERE username = '"& textbox.text &"'"

Search the main table using the username of the user to find the role and then use an if statement to make the specific links show.

If sql = Patient then
    <code here>
Else if sql = Admin then
    <code here>
Else if sql = Doctor then
    <code here>
End if


问:
replace sed command text inline
I have this file

file.txt

```<code>unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4
</code>```

How can I use the sed command to obtain this:

```<code>unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|
</code>```

答:
This might work for you (GNU sed):

```<code>sed ':a;N;/\n[^|\n]*$/!ba;s/||\([^|]*\)||\(\n.*\)*\n\(.*\)$/|\3|\1|\3|\2/;P;D' file
</code>```

Slurp the first part of the file into pattern space and one of the replacements, substitute, print and delete the first line and then repeat.

Title: replace sed command text inline

Body:
I have this file

file.txt

unknown@mail.com||unknown@mail.com||
unknown@mail2.com||unknown@mail2.com||
unknown@mail3.com||unknown@mail3.com||
unknown@mail4.com||unknown@mail4.com||
unknownpass
unknownpass2
unknownpass3
unknownpass4

How can I use the sed command to obtain this:

unknown@mail.com|unknownpass|unknown@mail.com|unknownpass|
unknown@mail2.com|unknownpass2|unknown@mail2.com|unknownpass2|
unknown@mail3.com|unknownpass3|unknown@mail3.com|unknownpass3|
unknown@mail4.com|unknownpass4|unknown@mail4.com|unknownpass4|

Body:
This might work for you (GNU sed):

sed ':a;N;/\n[^|\n]*$/!ba;s/||\([^|]*\)||\(\n.*\)*\n\(.*\)$/|\3|\1|\3|\2/;P;D' file

Slurp the first part of the file into pattern space and one of the replacements, substitute, print and delete the first line and then repeat.


问:
Cannot Get Route Symfony
As the title say explecitly, I don't manage to get some specific route I recently added.
My symfony version : 2.8.18.
So here are the details :

Route I try to match :
 - /platform/cat
 - /platform/cat/{id}

File - app/config/routing.yml :

```<code>gb_platform:
resource: "@GBPlatformBundle/Resources/config/routing.yml"
prefix:   /platform
</code>```

File - GB\PlatformBundle\Resources\config\routing.yml :

```<code>    gb_platform_home_:
    path :   /
      defaults: { _controller: GBPlatformBundle:Advert:index }

gb_platform_home:
    path :   /{page}
    defaults:
        _controller : GBPlatformBundle:Advert:index
        page: 1
    requirements:
        page: \d*

gb_platform_view:
    path :   /advert/{id}
    defaults: { _controller : GBPlatformBundle:Advert:view }
    requirements:
        id: \d+

gb_platform_add:
    path :   /add
    defaults: { _controller : GBPlatformBundle:Advert:add }

gb_platform_edit:
    path :   /edit/{id}
    defaults: { _controller : GBPlatformBundle:Advert:edit }
    requirements:
        id: \d+

gb_platform_delete:
    path :   /delete/{id}
    defaults: { _controller : GBPlatformBundle:Advert:delete }
    requirements:
        id: \d+

gb_platform_cat:
    path :   /cat
    defaults: { _controller : GBPlatformBundle:Category:index }

gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: \d+
</code>```

File - GB\PlatformBundle\Resources\controller\CategoryController.php :

```<code>    <?php

namespace GB\PlatformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;

use GB\PlatformBundle\Entity\Advert;
use GB\PlatformBundle\Entity\Category;

class CategoryController extends Controller
{
    public function indexAction(Request $request)
    {

    }

    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $catRepo = $em
            ->getRepository('GBPlatformBundle:Category');
        $cat = $catRepo
            ->find($id);

        if($cat === null)
        {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        return $this->render('GBPlatformBundle:Category:view.html.twig', array(
            'category' => $cat,
            ));
    }
}
</code>```

At the origin, the routing.yml of the bundle was invalid. Once it's fixed, I try to get the both command :

php app/console debug:router

php app/console debug:router gb_platform_cat

php app/console debug:router gb_platform_add

Each command were successfull and I saw no difference between /cat and /add while one match and the other don't.
I tried also many times to clear cache with :

php app/console cache:clear --env prod

Still don't work. I'm confused ...
The error is basic : No route found for "GET /platform/cat/7

答:
You have defined /cat/7 not /platform/cat/7

anyway is better with annotation in controller instead of routing file:

```<code>/**
 * @Route("/platform/cat/{id}", name="gb_platform_cat_view")
 */
public function viewAction($id)
{

    $em = $this->getDoctrine()->getManager();
    $catRepo = $em
        ->getRepository('GBPlatformBundle:Category');
    $cat = $catRepo
        ->find($id);

    if($cat === null)
    {
        throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
    }

    return $this->render('GBPlatformBundle:Category:view.html.twig', array(
        'category' => $cat,
        ));
}
</code>```

Title: Cannot Get Route Symfony

Body:
As the title say explecitly, I don't manage to get some specific route I recently added.
My symfony version : 2.8.18.
So here are the details :

Route I try to match :
 - /platform/cat
 - /platform/cat/{id}

File - app/config/routing.yml :

gb_platform:
resource: "@GBPlatformBundle/Resources/config/routing.yml"
prefix:   /platform

File - GB\PlatformBundle\Resources\config\routing.yml :

    gb_platform_home_:
    path :   /
      defaults: { _controller: GBPlatformBundle:Advert:index }

gb_platform_home:
    path :   /{page}
    defaults:
        _controller : GBPlatformBundle:Advert:index
        page: 1
    requirements:
        page: \d*

gb_platform_view:
    path :   /advert/{id}
    defaults: { _controller : GBPlatformBundle:Advert:view }
    requirements:
        id: \d+

gb_platform_add:
    path :   /add
    defaults: { _controller : GBPlatformBundle:Advert:add }

gb_platform_edit:
    path :   /edit/{id}
    defaults: { _controller : GBPlatformBundle:Advert:edit }
    requirements:
        id: \d+

gb_platform_delete:
    path :   /delete/{id}
    defaults: { _controller : GBPlatformBundle:Advert:delete }
    requirements:
        id: \d+

gb_platform_cat:
    path :   /cat
    defaults: { _controller : GBPlatformBundle:Category:index }

gb_platform_cat_view:
    path : /cat/{id}
    defaults: { _controller : GBPlatformBundle:Category:view }
    requirements:
        id: \d+

File - GB\PlatformBundle\Resources\controller\CategoryController.php :

    <?php

namespace GB\PlatformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;

use GB\PlatformBundle\Entity\Advert;
use GB\PlatformBundle\Entity\Category;

class CategoryController extends Controller
{
    public function indexAction(Request $request)
    {

    }

    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $catRepo = $em
            ->getRepository('GBPlatformBundle:Category');
        $cat = $catRepo
            ->find($id);

        if($cat === null)
        {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        return $this->render('GBPlatformBundle:Category:view.html.twig', array(
            'category' => $cat,
            ));
    }
}

At the origin, the routing.yml of the bundle was invalid. Once it's fixed, I try to get the both command :

php app/console debug:router

php app/console debug:router gb_platform_cat

php app/console debug:router gb_platform_add

Each command were successfull and I saw no difference between /cat and /add while one match and the other don't.
I tried also many times to clear cache with :

php app/console cache:clear --env prod

Still don't work. I'm confused ...
The error is basic : No route found for "GET /platform/cat/7

Body:
You have defined /cat/7 not /platform/cat/7

anyway is better with annotation in controller instead of routing file:

/**
 * @Route("/platform/cat/{id}", name="gb_platform_cat_view")
 */
public function viewAction($id)
{

    $em = $this->getDoctrine()->getManager();
    $catRepo = $em
        ->getRepository('GBPlatformBundle:Category');
    $cat = $catRepo
        ->find($id);

    if($cat === null)
    {
        throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
    }

    return $this->render('GBPlatformBundle:Category:view.html.twig', array(
        'category' => $cat,
        ));
}


问:
Camel Test - how to skip Endpoint used in ConsumerTemplate within a processor
I implemented a service that uses a polling consumer. The pattern is very similar to the one here (see "Timer Based Polling Consumer").

This is my variant:

```<code>@Override
public void configure() throws Exception {
    from("quartz2://" + SCHEDULE + "?cron=" + checkNotNull(cron)).routeId(IN_ROUTE)
            .process(fetchMessages)
    ;
}
</code>```

FetchMessages Processor:

```<code>@Override
public void process(Exchange exchange) throws Exception {
    while (true) {
        exchange = consumerTemplate.receive(MainRoute.ACTIVE_MQ + ":queue:" + "source", TIMEOUT);
        //no more messages within timeout
        if (exchange == null){
            break;
        }
        producerTemplate.send(MidRoute.MID_PLUG, exchange);
    }
}
</code>```

My Problem is: How to skip the activemq endpoint within test?

So far i tried to skip it by means of camels test support:

```<code>@Override
public String isMockEndpointsAndSkip() {
    return "(" + MainRoute.ACTIVE_MQ + ".*)|" + MidRoute.MID_PLUG;
}
</code>```

and with intercept:

```<code>@Before
public void prepare() throws Exception {
    context.getRouteDefinition(InRoute.IN_ROUTE).adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            replaceFromWith(in);
            interceptSendToEndpoint(MainRoute.ACTIVE_MQ + ":queue:" + "source")
                .skipSendToOriginalEndpoint()
                .to(amqMockSource);
        }
    });
}
</code>```

Both with no avail. ActiveMq endpoint is still called resulting in connection refused exception.

So how to skip endpoints used within beans?

答:
You can do that using the weave mechanism in Camel.

Start by giving your route an id using .routeId(") and then same goes for your .process("") an id. So write .process("fetchMessages").id("myId")

We then need to use the weave component to remove the processor.

Something like this in your test.

```<code>   @Override
   public boolean isUseAdviceWith() {
        return true;
    }

 @Before
  public void setUp() throws Exception {
    super.setUp();

    context.getRouteDefinition("YourRouteId").adviceWith(context, new AdviceWithRouteBuilder()  {
      @Override
      public void configure() throws Exception {
        weaveById("myId").replace().setBody().constant("Some response"));
      }
    });
}
</code>```

Basically we are saying that we want to use AdviceWith and then we look in the route with a given routeId for a given method with a given id and replace it with some response body. This is the response you expect to receive from your activemq.

Body:
I implemented a service that uses a polling consumer. The pattern is very similar to the one here (see "Timer Based Polling Consumer").

This is my variant:

@Override
public void configure() throws Exception {
    from("quartz2://" + SCHEDULE + "?cron=" + checkNotNull(cron)).routeId(IN_ROUTE)
            .process(fetchMessages)
    ;
}

FetchMessages Processor:

@Override
public void process(Exchange exchange) throws Exception {
    while (true) {
        exchange = consumerTemplate.receive(MainRoute.ACTIVE_MQ + ":queue:" + "source", TIMEOUT);
        //no more messages within timeout
        if (exchange == null){
            break;
        }
        producerTemplate.send(MidRoute.MID_PLUG, exchange);
    }
}

My Problem is: How to skip the activemq endpoint within test?

So far i tried to skip it by means of camels test support:

@Override
public String isMockEndpointsAndSkip() {
    return "(" + MainRoute.ACTIVE_MQ + ".*)|" + MidRoute.MID_PLUG;
}

and with intercept:

@Before
public void prepare() throws Exception {
    context.getRouteDefinition(InRoute.IN_ROUTE).adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            replaceFromWith(in);
            interceptSendToEndpoint(MainRoute.ACTIVE_MQ + ":queue:" + "source")
                .skipSendToOriginalEndpoint()
                .to(amqMockSource);
        }
    });
}

Both with no avail. ActiveMq endpoint is still called resulting in connection refused exception.

So how to skip endpoints used within beans?

Body:
You can do that using the weave mechanism in Camel.

Start by giving your route an id using .routeId(") and then same goes for your .process("") an id. So write .process("fetchMessages").id("myId")

We then need to use the weave component to remove the processor.

Something like this in your test.

   @Override
   public boolean isUseAdviceWith() {
        return true;
    }

 @Before
  public void setUp() throws Exception {
    super.setUp();

    context.getRouteDefinition("YourRouteId").adviceWith(context, new AdviceWithRouteBuilder()  {
      @Override
      public void configure() throws Exception {
        weaveById("myId").replace().setBody().constant("Some response"));
      }
    });
}

Basically we are saying that we want to use AdviceWith and then we look in the route with a given routeId for a given method with a given id and replace it with some response body. This is the response you expect to receive from your activemq.


问:
Use Django pyodbc SQLSERVER issue
I'm trying to connect django with sqlserver . I already installed python odbc and django-odbc.

My data dabase configuration (settings.py)

```<code>DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'EDAS',                      # Or path to database file if using sqlite3.
        'USER': 'sa',                      # Not used with sqlite3.
        'PASSWORD': '1324',                  # Not used with sqlite3.
        'HOST': 'DBIO01-HP',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '1433'                      # Set to empty string for default. Not used with sqlite3.
    }
}
</code>```

However, I'm getting this error when I try to run the server:

C:\edas>python manage.py runserver

```<code>Validating models...

Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.comma
nds.runserver.Command object at 0x02EC2E70>>
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 91, in inner_run
    self.validate(display_num_errors=True)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 266, in validate
    num_errors = get_validation_errors(s, app)
  File "C:\Python27\lib\site-packages\django\core\management\validation.py", line 23, in get_validation_errors
    from django.db import models, connection
  File "C:\Python27\lib\site-packages\django\db\__init__.py", line 40, in <module>
    backend = load_backend(connection.settings_dict['ENGINE'])
  File "C:\Python27\lib\site-packages\django\db\__init__.py", line 34, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 92, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 24, in load_backend
    return import_module('.base', backend_name)
  File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module
    __import__(name)
  File "C:\Python27\lib\site-packages\sql_server\pyodbc\base.py", line 56, in <module>
    elif 'collation' in settings.DATABASE_OPTIONS:
  File "C:\Python27\lib\site-packages\django\utils\functional.py", line 185, in inner
    return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'DATABASE_OPTIONS'
</code>```

Can someone help me to figure out how to fix it?

答:
This worked for me, specifically the driver_supports_utf8 line:</p>

```<code>'dbconn': {
            'CREATE_DB': False,
            'CREATE_USER': False,
            'CREATE_TBLSPACE': False,
            'ENGINE': 'django_pyodbc',
            'NAME': 'DBNAME',
            'USER': 'user',
            'PASSWORD': 'password',
            'HOST': 'HOST',
            'OPTIONS': {
                'host_is_server': True,
                'driver_supports_utf8': True,
            }
        }
</code>```

Title: Use Django pyodbc SQLSERVER issue

Body:
I'm trying to connect django with sqlserver . I already installed python odbc and django-odbc.

My data dabase configuration (settings.py)

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'EDAS',                      # Or path to database file if using sqlite3.
        'USER': 'sa',                      # Not used with sqlite3.
        'PASSWORD': '1324',                  # Not used with sqlite3.
        'HOST': 'DBIO01-HP',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '1433'                      # Set to empty string for default. Not used with sqlite3.
    }
}

However, I'm getting this error when I try to run the server:

C:\edas>python manage.py runserver

Validating models...

Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.comma
nds.runserver.Command object at 0x02EC2E70>>
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 91, in inner_run
    self.validate(display_num_errors=True)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 266, in validate
    num_errors = get_validation_errors(s, app)
  File "C:\Python27\lib\site-packages\django\core\management\validation.py", line 23, in get_validation_errors
    from django.db import models, connection
  File "C:\Python27\lib\site-packages\django\db\__init__.py", line 40, in <module>
    backend = load_backend(connection.settings_dict['ENGINE'])
  File "C:\Python27\lib\site-packages\django\db\__init__.py", line 34, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 92, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 24, in load_backend
    return import_module('.base', backend_name)
  File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module
    __import__(name)
  File "C:\Python27\lib\site-packages\sql_server\pyodbc\base.py", line 56, in <module>
    elif 'collation' in settings.DATABASE_OPTIONS:
  File "C:\Python27\lib\site-packages\django\utils\functional.py", line 185, in inner
    return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'DATABASE_OPTIONS'

Can someone help me to figure out how to fix it?

Body:
This worked for me, specifically the driver_supports_utf8 line:

'dbconn': {
            'CREATE_DB': False,
            'CREATE_USER': False,
            'CREATE_TBLSPACE': False,
            'ENGINE': 'django_pyodbc',
            'NAME': 'DBNAME',
            'USER': 'user',
            'PASSWORD': 'password',
            'HOST': 'HOST',
            'OPTIONS': {
                'host_is_server': True,
                'driver_supports_utf8': True,
            }
        }


问:
other queries are executing if native query is called in jpa
I have a entity called Test.java with 70 fields, some of the fields are related to other entities also(through join one to many, many to one, etc assosiations).

I need to have an object of this type but I don't need all the fields just 3 fields out of them one field has foreign key relation relation with other entity.

So, I wrote a native query while executing the query jpa executing other queries also causes taking so much time to complete.

Here is my entity class:

```<code>    public Class Test implements Serializable{

    @Id
    private int id;

    @ManyToOne
    @JoinColumn(name = "STATUSID")
    private xxxxx  xxxxx;

   /// other fields, getters and setters

    }
</code>```

Here is my native query

```<code>  public List<Order> getAllOpenOrders() {

    final String query = "SELECT t.* from T_TEST";

     Query createNativeQuery = em.createNativeQuery(query, Test.class);

    List<Order> resultList = createNativeQuery.getResultList();

    return resultList;
}
</code>```

How can I get the Order entity object with selected fields, I don't need other fields means I am using only these three fields for my functionlity.

How can I stop other queries execution?

Thank you.

答:
You can select only those columns you need using Projections. You do not have to resort to Native Queries for this.

As far as I remember (I had debugged a long time ago), hibernate does a flush before executing a native query. This results in executing all pending queries as well, right before executing the native query. This might be the case in your situation where you are seeing some other queries.

You can use Projections, which are a bit cleaner way to select only required columns.

As answered here : https://stackoverflow.com/a/11626877/564503

Body:
I have a entity called Test.java with 70 fields, some of the fields are related to other entities also(through join one to many, many to one, etc assosiations).

I need to have an object of this type but I don't need all the fields just 3 fields out of them one field has foreign key relation relation with other entity.

So, I wrote a native query while executing the query jpa executing other queries also causes taking so much time to complete.

Here is my entity class:

    public Class Test implements Serializable{

    @Id
    private int id;

    @ManyToOne
    @JoinColumn(name = "STATUSID")
    private xxxxx  xxxxx;

   /// other fields, getters and setters

    }

Here is my native query

  public List<Order> getAllOpenOrders() {

    final String query = "SELECT t.* from T_TEST";

     Query createNativeQuery = em.createNativeQuery(query, Test.class);

    List<Order> resultList = createNativeQuery.getResultList();

    return resultList;
}

How can I get the Order entity object with selected fields, I don't need other fields means I am using only these three fields for my functionlity.

How can I stop other queries execution?

Thank you.


问:
i want to sort my List view with price but my price object i get with My Web Service ? also this object value similar like "$49.55" same as "$39.55"
Then how can i compare both value?
Which Datatype is used for them?
I get string type data.
How to Parse the data for compare value?

This is my spinner click event. how can i sort upper value with my "JSON" Service Object.

```<code>        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             final TextView selectedText = (TextView) parent.getChildAt(0);
            if (selectedText != null) {
                selectedText.setTextColor(Color.WHITE);
                if (id == 1) {
                    selectedText.setTextColor(Color.WHITE);
                    Collections.sort(mlistElectricity, new Comparator<RetailerPlanBean>(){
                        @Override
                        public int compare(RetailerPlanBean emp1, RetailerPlanBean emp2) {
                            return emp1.getmPRICE().compareToIgnoreCase(emp2.getmPRICE());
                        }
                    });
                    mRateLv = (ListView) rootview.findViewById(R.id.find_enery);
                    mRateLv.setAdapter(new FindRateAdapter(getActivity(), mlistElectricity));
                    mAllListCountTv.setText(""+mlistElectricity.size()+" LIST");
                    adapter.notifyDataSetChanged();
                }else if (id == 2){
                    selectedText.setTextColor(Color.WHITE);
                    Collections.sort(mlistElectricity, new Comparator<RetailerPlanBean>(){
                        @Override
                        public int compare(RetailerPlanBean emp1, RetailerPlanBean emp2) {
                            return emp2.getmPRICE().compareToIgnoreCase(emp1.getmPRICE());
                        }
                    });
                    mRateLv = (ListView) rootview.findViewById(R.id.find_enery);
                    mRateLv.setAdapter(new FindRateAdapter(getActivity(), mlistElectricity));
                    mAllListCountTv.setText(""+mlistElectricity.size()+" LIST");
                    adapter.notifyDataSetChanged();
                }else {
                    selectedText.setTextColor(Color.WHITE);
                }

            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
</code>```

答:
As Bradley mentioned you have to extract the price from String

```<code>Collections.sort(mlistElectricity, new Comparator<RetailerPlanBean>(){
    @Override
    public int compare(RetailerPlanBean emp1, RetailerPlanBean emp2) {

        double emp2Price = Double.parseDouble(emp2.getmPRICE().replace("$",");
        double emp1Price = Double.parseDouble(emp1.getmPRICE().replace("$",");

        if (emp2Price == emp1Price )
            return 0;
        else if (emp1Price > emp2Price )
            return 1;
        else
            return -1;
    }
});
</code>```

Above will work only for '$'

And you can use subString method as well and remove first character.

Using subString method

```<code>double emp2Price = Double.parseDouble(emp2.getmPRICE().substring(1, emp2.getmPRICE().length());
double emp1Price = Double.parseDouble(emp1.getmPRICE().substring(1, emp1.getmPRICE().length());
</code>```

Body:
Then how can i compare both value?
Which Datatype is used for them?
I get string type data.
How to Parse the data for compare value?

This is my spinner click event. how can i sort upper value with my "JSON" Service Object.

        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             final TextView selectedText = (TextView) parent.getChildAt(0);
            if (selectedText != null) {
                selectedText.setTextColor(Color.WHITE);
                if (id == 1) {
                    selectedText.setTextColor(Color.WHITE);
                    Collections.sort(mlistElectricity, new Comparator<RetailerPlanBean>(){
                        @Override
                        public int compare(RetailerPlanBean emp1, RetailerPlanBean emp2) {
                            return emp1.getmPRICE().compareToIgnoreCase(emp2.getmPRICE());
                        }
                    });
                    mRateLv = (ListView) rootview.findViewById(R.id.find_enery);
                    mRateLv.setAdapter(new FindRateAdapter(getActivity(), mlistElectricity));
                    mAllListCountTv.setText(""+mlistElectricity.size()+" LIST");
                    adapter.notifyDataSetChanged();
                }else if (id == 2){
                    selectedText.setTextColor(Color.WHITE);
                    Collections.sort(mlistElectricity, new Comparator<RetailerPlanBean>(){
                        @Override
                        public int compare(RetailerPlanBean emp1, RetailerPlanBean emp2) {
                            return emp2.getmPRICE().compareToIgnoreCase(emp1.getmPRICE());
                        }
                    });
                    mRateLv = (ListView) rootview.findViewById(R.id.find_enery);
                    mRateLv.setAdapter(new FindRateAdapter(getActivity(), mlistElectricity));
                    mAllListCountTv.setText(""+mlistElectricity.size()+" LIST");
                    adapter.notifyDataSetChanged();
                }else {
                    selectedText.setTextColor(Color.WHITE);
                }

            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Body:
As Bradley mentioned you have to extract the price from String

Collections.sort(mlistElectricity, new Comparator<RetailerPlanBean>(){
    @Override
    public int compare(RetailerPlanBean emp1, RetailerPlanBean emp2) {

        double emp2Price = Double.parseDouble(emp2.getmPRICE().replace("$",");
        double emp1Price = Double.parseDouble(emp1.getmPRICE().replace("$",");

        if (emp2Price == emp1Price )
            return 0;
        else if (emp1Price > emp2Price )
            return 1;
        else
            return -1;
    }
});

Above will work only for '$'

And you can use subString method as well and remove first character.

Using subString method

double emp2Price = Double.parseDouble(emp2.getmPRICE().substring(1, emp2.getmPRICE().length());
double emp1Price = Double.parseDouble(emp1.getmPRICE().substring(1, emp1.getmPRICE().length());


问:
Passing parameters to public void run() from the parent
I'm 50% hopeless :P. I tried (at the beginning) to update the GUI from the code of a Thread, and got NullException. After reading for a while, I understood that the Thread flooded the JavaFX application window and in order for me to update the GUI from a Thread, I need to use the following code:

```<code>Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });
</code>```

So I did use this code, and it indeed allow me to edit the GUI of my main class. However, my question is simple. => this code, which I'm running from a thread, is a code which sits inside a public void run()  (of the thread I run the code from). It looks something like this:

```<code>@Override
    public void run() {

    String tmpVar;

    ... (Some code)
    ... (Some code)
    ... (Some code)

        Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

    ... (Some code)
    ... (Some code)
    ... (Some code)
}
</code>```

How can I pass parameters from the parent's public void run() into this one?.
For example, the String tmpString (I want to pass it on).

Do note that if I declare it outside the public void run() as a static (for example) => I run a lot of threads, so updating a static var might not always be accurate (cause lots of threads will update it simultaneity)

Thank you!.

答:
Basically, you need to think in terms of passing the parameter to the Runnable object, not to the run() method.

If you make the anonymous class an inner class, it becomes pretty clear:

```<code>@Override
public void run() {

    String tmpVar;

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)

        Platform.runLater(new Updater(tmpVar));

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)
}

// ...

public static class Updater implements Runnable {

    private final String var ;

    public Updater(String var) {
        this.var = var ;
    }

    @Override
    public void run() {

        // Access var here

        for (int i=0; i<2000;i++){
            MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
        }

    }
}
</code>```

Now, if tmpVar is final, or "effectively final1", then it will work with your anonymous inner class, and is basically translated to exactly the same thing as the inner class above (in other words, the anonymous inner class gets an implicit field which is populated with the value of the final variable):

```<code>@Override
public void run() {

    final String tmpVar = ...;

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)

    Platform.runLater(new Runnable() {
        @Override public void run() {

        // access tmpVar here:

        for (int i=0; i<2000;i++)
            {
             MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
            }

        }
    });

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)
}
</code>```

The language designers could actually have made this work with non-final variables, but decided that the results would have been too confusing. What would happen would be that it would have been translated to the same inner class seen above: in other words the current value of tmpVar would have been implicitly passed to a field in the anonymous inner class. This would be a completely new variable, with a different scope, to the one it appears you are accessing, and its value would be a "snapshot" of the value of tmpVar at the time the anonymous inner class is created. Having what appears to be one variable that is actually referring to two different variables potentially with different values was deemed too confusing and bug-prone.

However, if tmpVar is not final (or effectively final): i.e. you are going to assign it values multiple times, you can explicitly "snapshot" the value of the variable:

```<code>@Override
public void run() {

    String tmpVar ;

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)

    final String varCopy = tmpVar ;

    Platform.runLater(new Runnable() {
        @Override public void run() {

        // access varCopy here:

        for (int i=0; i<2000;i++)
            {
             MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
            }

        }
    });

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)
}
</code>```

(1) "Effectively final" means that the variable is assigned a value exactly once. Equivalently, it means you could declare it final without creating any compilation errors.

Body:
I'm 50% hopeless :P. I tried (at the beginning) to update the GUI from the code of a Thread, and got NullException. After reading for a while, I understood that the Thread flooded the JavaFX application window and in order for me to update the GUI from a Thread, I need to use the following code:

Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

So I did use this code, and it indeed allow me to edit the GUI of my main class. However, my question is simple. => this code, which I'm running from a thread, is a code which sits inside a public void run()  (of the thread I run the code from). It looks something like this:

@Override
    public void run() {

    String tmpVar;

    ... (Some code)
    ... (Some code)
    ... (Some code)

        Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

    ... (Some code)
    ... (Some code)
    ... (Some code)
}

How can I pass parameters from the parent's public void run() into this one?.
For example, the String tmpString (I want to pass it on).

Do note that if I declare it outside the public void run() as a static (for example) => I run a lot of threads, so updating a static var might not always be accurate (cause lots of threads will update it simultaneity)

Thank you!.

Body:
Basically, you need to think in terms of passing the parameter to the Runnable object, not to the run() method.

If you make the anonymous class an inner class, it becomes pretty clear:

@Override
public void run() {

    String tmpVar;

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)

        Platform.runLater(new Updater(tmpVar));

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)
}

// ...

public static class Updater implements Runnable {

    private final String var ;

    public Updater(String var) {
        this.var = var ;
    }

    @Override
    public void run() {

        // Access var here

        for (int i=0; i<2000;i++){
            MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
        }

    }
}

Now, if tmpVar is final, or "effectively final1", then it will work with your anonymous inner class, and is basically translated to exactly the same thing as the inner class above (in other words, the anonymous inner class gets an implicit field which is populated with the value of the final variable):

@Override
public void run() {

    final String tmpVar = ...;

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)

    Platform.runLater(new Runnable() {
        @Override public void run() {

        // access tmpVar here:

        for (int i=0; i<2000;i++)
            {
             MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
            }

        }
    });

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)
}

The language designers could actually have made this work with non-final variables, but decided that the results would have been too confusing. What would happen would be that it would have been translated to the same inner class seen above: in other words the current value of tmpVar would have been implicitly passed to a field in the anonymous inner class. This would be a completely new variable, with a different scope, to the one it appears you are accessing, and its value would be a "snapshot" of the value of tmpVar at the time the anonymous inner class is created. Having what appears to be one variable that is actually referring to two different variables potentially with different values was deemed too confusing and bug-prone.

However, if tmpVar is not final (or effectively final): i.e. you are going to assign it values multiple times, you can explicitly "snapshot" the value of the variable:

@Override
public void run() {

    String tmpVar ;

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)

    final String varCopy = tmpVar ;

    Platform.runLater(new Runnable() {
        @Override public void run() {

        // access varCopy here:

        for (int i=0; i<2000;i++)
            {
             MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
            }

        }
    });

    // ... (Some code)
    // ... (Some code)
    // ... (Some code)
}

(1) "Effectively final" means that the variable is assigned a value exactly once. Equivalently, it means you could declare it final without creating any compilation errors.


问:
Angular2: update table view after retrieving data
I have a simple table like

```<code><table class="table table-bordered table-condensed table-hover table-striped ">
<thead>
    <tr>
        <th>Benutzer</th>
        <th>Vorname</th>
        <th>Nachname</th>
    </tr>
</thead>
<tbody>
  <tr *ngFor="let empl of employers">
        <td>{{empl.name}}</td>
        <td>{{empl.firstName}}</td>
        <td>{{empl.lastName}}</td>
  </tr>
</tbody>
</table>
</code>```

to display data. While it is first displayed I fetch data for employers with a Promise which takes quite some time. The display works quite well with empty data.

My problem starts when I encapsulate the whole table with something like

```<code><div class="panel-heading">{{title}}</div>
<div class="panel-body">
  .... table ....
</div>
</code>```

This paints a border around the table - which is OK as long as no data is included. But when I have data which has loooooooooooooooong content the table stretches - and the border is not redrawn/refreshed.

How to achieve that the border of panel-body is evaluted again after  *ngFor has finished?

答:
The question is more about CSS than Angular. If you have a long TABLE element in a DIV element with a fixed width, then the table will overflow the div (get wider).

To get around it, you can either set "overflow: auto" on the div or limit the length of the table cells (by setting "table-layout: fixed", setting its width and wrapping contents of its cells in DIVs with overflow: hidden). Or you can use some responsive structure instead of the TABLE. Such as a flex layout.

Body:
I have a simple table like

        Benutzer
        Vorname
        Nachname

        {{empl.name}}
        {{empl.firstName}}
        {{empl.lastName}}

to display data. While it is first displayed I fetch data for employers with a Promise which takes quite some time. The display works quite well with empty data.

My problem starts when I encapsulate the whole table with something like

{{title}}

  .... table ....

This paints a border around the table - which is OK as long as no data is included. But when I have data which has loooooooooooooooong content the table stretches - and the border is not redrawn/refreshed.

How to achieve that the border of panel-body is evaluted again after  *ngFor has finished?


问:
bug-tracker and wiki for project specifications

SHORT QUESTION

If you want to skip the details below, here's the short question:

I want to know if you keep your app's specifications similarly, in a bugtracker + a wiki and how do you split the information for good management. I look for a simple solution or just a point to start.

DETAILS

I need to keep track of the features for a web app that I want to build. So, I've used MediaWiki to gather a list of features.

For each feature, I have a wiki page where I include functional specs, technical specs and various related brainstormings in FreeMind format or plain text. Also, I include a series of open-questions related to it as TODOs and lots of images for various use cases. I found the wiki to be an excellent place where to keep all these.

I have a page in the wiki with all features transcluded manually so I can see them all in one page, in a specific format.
I also have a page in the wiki where I state what's the goal for v1.0, and a manually transcluded list of features for this version.

In the bug tracker(I use ClockingIT), I want to keep track of the tasks, bugs, etc. in order to build version 1.0 of the product.

ISSUE

Since I keep all features(well, the major features at least) in the wiki, I now feel the need to duplicate them in the bug tracker. Also, after brainstorming on V1.0, I realized there are many smaller features(that are too small to include in the wiki) that I'll need to keep track of in the bug tracker.

The problem is that I end up with 2 systems that will keep and manage the set of features and lots of duplicates will appear, like:

which features get in V1.0 -> this exists in the wiki as a page and the bugtracker keeps a milestone for this; moving a feature from v1.0 to another version, will mean to update both the bugtracker and the wiki

in the bugtracker I add comments as logs for what I do while working on the feature, so the wiki will get deprecated because some part of the brainstorming moves into the bugtracker

the wiki will tend to contain the major features while the bugtracker will contain minor features(like add a button to show/hide a section or something)...but the limit between major and minor features is very subjective and will tend to get messy so I'll have a hard time searching for a feature - I'll have to search in both wiki and bugtracker or I'll have to remember if it was a major or a minor feature

QUESTION

Since I need to keep the features in the wiki because it is an excellent tool for brainstorming, information keeping, etc. what should I include in the bugtracker? How can I efficiently separate these two tools' functionality so they integrate well with each-other and I don't get to duplicate any(or small amount of) data?

Thank you!

答:
You will need to customize for your needs but have you seen trac : http://trac.edgewall.org/.

This will serve many of your purpose. It combines bug tracker with wiki and other aspects.

Trac is an enhanced wiki and issue tracking system for software development projects. It provides an interface to  Subversion (or other version control systems), an integrated Wiki and convenient reporting facilities.


问:
Can foreign keys act as a primary key?
If a table has a composite primary key made of attribute A, B and this composite primary key is referenced in another table, can that other table have attribute A as a primary key and NOT attribute b? And maybe, Attribute A with some other attribute in the same table as another composite primary key?</p>

答: If the second table has both attributes A and B, then an FK constraint can reference those same attributes in the first table (since they're uniquely constrained as the PK), regardless of whether A and/or B are part of the PK of the second table or not.</p>

Title: Can foreign keys act as a primary key?


问:
Set up Azure Service Fabric cluster on managed disks
Does anybody know how to set up Service Fabric cluster with VMs on managed disks(both OS and Data)?  I would be very interested to know how to do this using template config.</p>

答:
You need to change VMSS api version to 2016-04-30-preview and storageProfile to this:

```<code>"storageProfile": {
    "imageReference": {
        "publisher": "[parameters('vmImagePublisher')]",
        "offer": "[parameters('vmImageOffer')]",
        "sku": "[parameters('vmImageSku')]",
        "version": "[parameters('vmImageVersion')]"
    },
    "osDisk": {
        "createOption": "FromImage"
        "managedDisk": {
            "storageAccountType": "Standard_LRS"
   # defauls to Standard_LRS,
   # you can choose to pick Premium_LRS if your VM size supports premium storage
   # or you can omit this node completely if you need standard storage
        }
    }
}
</code>```

Storage Accounts are redundant when using managed disks (you don't need them, Azure handles that for you).

Body:
You need to change VMSS api version to 2016-04-30-preview and storageProfile to this:

"storageProfile": {
    "imageReference": {
        "publisher": "[parameters('vmImagePublisher')]",
        "offer": "[parameters('vmImageOffer')]",
        "sku": "[parameters('vmImageSku')]",
        "version": "[parameters('vmImageVersion')]"
    },
    "osDisk": {
        "createOption": "FromImage"
        "managedDisk": {
            "storageAccountType": "Standard_LRS"
   # defauls to Standard_LRS,
   # you can choose to pick Premium_LRS if your VM size supports premium storage
   # or you can omit this node completely if you need standard storage
        }
    }
}

Storage Accounts are redundant when using managed disks (you don't need them, Azure handles that for you).


问:
is there a way hide elements in IFRAME src page?
I have a very simple code. I like to hide some DIV's in my IFRAMe. So my index.html page looks like this, so the whole idea is hide the top and the leftpanel of from the Calendar.aspx page.

any idea what's wrong with my code or how should I do this?

```<code><script src="https://code.jquery.com/jquery-1.11.1.min.js"></<script>

<script type="text/javascript">
$( document ).ready(function() {
$("#leftpanel").hide();
$("#toppanel").hide
});
();
</script>
<iframe height="800px" width="800px"  src="https://domain/Calendar/Calendar%20Color%20Overview.aspx" >
</iframe>
</code>```

答:
I achieved this by creating a hidden form that posts data to the iframe src then deletes itself onpageload. Left with a iframe with src(unknown). </p>

<p>I used post to send data to url. Need full control of target domain to receive request. Have not tried code with a GET request. </p>

```<code>//html
<div id='deleteForm'>
<form style='display: none;' class='fakeForm' id='fakeForm' target="target_iframe" action="(iframe url)" method="post">
    //(optional) can send data to iframe src as a post request
    <input type="hidden" name='data' value="data you may want to send"/>
    <input type="submit" style='display: none;'>
</form>
</div>

<iframe id='target_iframe' src=''></iframe>

//js
window.onload = function () {
  var form = document.getElementById("fakeForm");
  form.submit();
  var deleteParent = document.getElementById("deleteForm");
  deleteParent.remove();
}
</code>```

Body:
I achieved this by creating a hidden form that posts data to the iframe src then deletes itself onpageload. Left with a iframe with src(unknown).

I used post to send data to url. Need full control of target domain to receive request. Have not tried code with a GET request.

//html
<div id='deleteForm'>
<form style='display: none;' class='fakeForm' id='fakeForm' target="target_iframe" action="(iframe url)" method="post">
    //(optional) can send data to iframe src as a post request
    <input type="hidden" name='data' value="data you may want to send"/>
    <input type="submit" style='display: none;'>
</form>
</div>

<iframe id='target_iframe' src=''></iframe>

//js
window.onload = function () {
  var form = document.getElementById("fakeForm");
  form.submit();
  var deleteParent = document.getElementById("deleteForm");
  deleteParent.remove();
}


问:
Modify/Read/Write existing Excel/PDF document with .NET libraries
The issue consists of two parts:

What are the best .NET libraries to modify (read/write) existing excel document (should be work with Excel 2003)?

What are the best .NET libraries to modify (read/write) existing pdf document?

They should be able to create new document too.
It's better if they are free (open source) or not too expensive.

Thanks in advance :)

答: I decided to use FlexCel for .net - not free but not expensive too. API is not very comfortable so my advice to use the documentation of this library and support pretty good. All features this library can do except charts (but flexcel team promise to add this in the nearest release).</p>


问:
Custom partitioner in SPARK (pyspark)
I am trying to create a custom partitioner in a spark job using PySpark, say, I have of list of some integers [10,20,30,40,50,10,20,35]. Now I want a scenario where I have two partitions say p1 and p2. p1 contains all the list elements < 30 and p2 contains all the elements above 30.

```<code>elements = sc.parallelize([10,20,30,40,50,10,20,35]).map(lambda x : (float(x)/10,x)).partitionBy(2).glom().collect()
</code>```

The above code partitions the list according to the hash of the arbitrary key I am passing. Is there anyway of partitioning the list according to a particular scenario ? Like the value is less than x or anything like that ?

答:
Piggybacking off of FaigB's answer, you want to partition on if the value is above a threshold, not the value itself. Here's how it'd look in python

```<code>rdd = sc.parallelize([10,20,30,40,50,10,20,35]).map(lambda x : (float(x)/10, float(x)/10))
elements = rdd.partitionBy(2,lambda x: int(x > 3)).map(lambda x: x[0]).glom().collect()
elements
</code>```

Which results in

```<code>[[1.0, 2.0, 3.0, 1.0, 2.0], [4.0, 5.0, 3.5]]
</code>```

Title: Custom partitioner in SPARK (pyspark)

Body:
I am trying to create a custom partitioner in a spark job using PySpark, say, I have of list of some integers [10,20,30,40,50,10,20,35]. Now I want a scenario where I have two partitions say p1 and p2. p1 contains all the list elements < 30 and p2 contains all the elements above 30.

elements = sc.parallelize([10,20,30,40,50,10,20,35]).map(lambda x : (float(x)/10,x)).partitionBy(2).glom().collect()

The above code partitions the list according to the hash of the arbitrary key I am passing. Is there anyway of partitioning the list according to a particular scenario ? Like the value is less than x or anything like that ?

Body:
Piggybacking off of FaigB's answer, you want to partition on if the value is above a threshold, not the value itself. Here's how it'd look in python

rdd = sc.parallelize([10,20,30,40,50,10,20,35]).map(lambda x : (float(x)/10, float(x)/10))
elements = rdd.partitionBy(2,lambda x: int(x > 3)).map(lambda x: x[0]).glom().collect()
elements

Which results in

[[1.0, 2.0, 3.0, 1.0, 2.0], [4.0, 5.0, 3.5]]


问:
Run eslint integration only if there are changed js files
I use code-climate integration in GitHub for a project and one of the engines in code climate is eslint. As of now, whenever a pull request is raised, eslint engine runs and checks for any issues and this is consuming a lot of time. The engines runs even if the changed files list does not contain a .js file.

Is there any way to run eslist only if there are changed .js files in the pull request? I know that eslint can be configured to check js files only. But what I need is to stop running eslint engine altogether if there are no js files in the changed files list.

答:
Disclaimer: I work at Codacy

Codacy is a free for open source service that runs static analysis checks on your code. What we do is actually only run the tools (ESLint included) for the changed files, at least after the first analysis. Give it a try and let us know if you have any feedback.


问:
Add a 'Count' Column in a DataGridView for Grouped Values
I'm populating a DataGridView from a SharePoint List which works fine.

I need a new column in the DataGridView that displays the count of each grouped list item.

So far I have:

```<code>if (collListItem.Count != 0)
{
    var dtCoaching = new DataTable();

    dtCoaching.Columns.AddRange(new[]
    {
       new DataColumn("Call Type"),  new DataColumn("Count")
    });

    foreach (var oListItem in collListItem)
    {
        dtCoaching.Rows.Add(oListItem["Call_x0020_Type"]);
    }

    dtCoaching = dtCoaching.AsEnumerable()
    .GroupBy(r => new { Col1 = r["Call Type"]})
    .Select(g => g.OrderBy(r => r["Call Type"]).First())
    .CopyToDataTable();

    if (dataGridViewCallType!= null)
    {
        dataGridViewCallType.DataSource = dtCoaching;
    }
}
</code>```

I've seen plenty of solutions that output to Console, which is great, but I need the DataTable to bind to the DataGridView, not output to console.

This is the output so far:

Click for Screenshot

I just need the count column to work!

Thanks

Davie

答:
Found an answer, need to clone the DataTable and build a new one with the Count column.</p>

```<code>            if (collListItem.Count != 0)
            {
                var dtCoaching = new DataTable();

                dtCoaching.Columns.AddRange(new[]
                {
                    new DataColumn("Call Type"),  new DataColumn("Count")
                });

                foreach (var oListItem in collListItem)
                {
                    dtCoaching.Rows.Add(oListItem["Call_x0020_Type"]);
                }

                var result = from row in dtCoaching.AsEnumerable()
                             group row by row.Field<string>("Call Type") into grp
                             select new
                             {
                                 CallType = grp.Key,
                                 CallCount = grp.Count()
                             };

                DataTable dtCoachingClone = new DataTable();
                dtCoachingClone = dtCoaching.Clone();

                foreach (var item in result)
                {
                    DataRow newRow = dtCoachingClone.NewRow();
                    newRow["Call Type"] = item.CallType;
                    newRow["Count"] = item.CallCount;
                    dtCoachingClone.Rows.Add(newRow);
                }

                if (dataGridViewCallType != null)
                {
                    dataGridViewCallType.DataSource = dtCoachingClone;
                }

                return;
            }
</code>```

Body:
I'm populating a DataGridView from a SharePoint List which works fine.

I need a new column in the DataGridView that displays the count of each grouped list item.

So far I have:

if (collListItem.Count != 0)
{
    var dtCoaching = new DataTable();

    dtCoaching.Columns.AddRange(new[]
    {
       new DataColumn("Call Type"),  new DataColumn("Count")
    });

    foreach (var oListItem in collListItem)
    {
        dtCoaching.Rows.Add(oListItem["Call_x0020_Type"]);
    }

    dtCoaching = dtCoaching.AsEnumerable()
    .GroupBy(r => new { Col1 = r["Call Type"]})
    .Select(g => g.OrderBy(r => r["Call Type"]).First())
    .CopyToDataTable();

    if (dataGridViewCallType!= null)
    {
        dataGridViewCallType.DataSource = dtCoaching;
    }
}

I've seen plenty of solutions that output to Console, which is great, but I need the DataTable to bind to the DataGridView, not output to console.

This is the output so far:

Click for Screenshot

I just need the count column to work!

Thanks

Davie

Body:
Found an answer, need to clone the DataTable and build a new one with the Count column.

            if (collListItem.Count != 0)
            {
                var dtCoaching = new DataTable();

                dtCoaching.Columns.AddRange(new[]
                {
                    new DataColumn("Call Type"),  new DataColumn("Count")
                });

                foreach (var oListItem in collListItem)
                {
                    dtCoaching.Rows.Add(oListItem["Call_x0020_Type"]);
                }

                var result = from row in dtCoaching.AsEnumerable()
                             group row by row.Field<string>("Call Type") into grp
                             select new
                             {
                                 CallType = grp.Key,
                                 CallCount = grp.Count()
                             };

                DataTable dtCoachingClone = new DataTable();
                dtCoachingClone = dtCoaching.Clone();

                foreach (var item in result)
                {
                    DataRow newRow = dtCoachingClone.NewRow();
                    newRow["Call Type"] = item.CallType;
                    newRow["Count"] = item.CallCount;
                    dtCoachingClone.Rows.Add(newRow);
                }

                if (dataGridViewCallType != null)
                {
                    dataGridViewCallType.DataSource = dtCoachingClone;
                }

                return;
            }


问:
How to use for loop in class for user inputs?
I have created employee details using class by giving pre defined inputs. I'm not able to store the results into a dict. I need to write it as a csv.   I would be thankful if you could help me, as I'm a novice in python

Here are my codes:

Is it correct way to use for loop in classes?

```<code>class Employee():
    def main(self,name,idno,position,salary):

        self.name=name
        self.idno=idno
        self.position=position
        self.salary = salary

    def input(self):
        n=int(raw_input("Enter the number of employees:"))
        for i in range(n):
            self.name=raw_input("Name:")
            self.idno=raw_input("Idno:")
            self.position=raw_input("position:")
            self.salary=raw_input("salary:")

            print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
                  "salary:", self.salary)

if __name__=='__main__':
        result=Employee()
        result.input()
</code>```

答:
This illustrates what I was saying in my comment about using a for loop outside of the class:

```<code>class Employee(object):
    def __init__(self, name, idno, position, salary):
        self.name=name
        self.idno=idno
        self.position=position
        self.salary = salary

    def print_data(self):
        print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
              "salary:", self.salary)

if __name__=='__main__':

    def input_employee_data():
        print('Enter data for an employee')
        name = raw_input("Name:")
        idno = raw_input("Idno:")
        position = raw_input("position:")
        salary = raw_input("salary:")
        print('')
        return name, idno, position, salary

    employees = list()
    n = int(raw_input("Enter the number of employees:"))
    for i in range(n):
        name, idno, position, salary = input_employee_data()
        employee = Employee(name, idno, position, salary)
        employees.append(employee)

    print('List of employess')
    for employee in employees:
        employee.print_data()
</code>```

Body:
I have created employee details using class by giving pre defined inputs. I'm not able to store the results into a dict. I need to write it as a csv.   I would be thankful if you could help me, as I'm a novice in python

Here are my codes:

Is it correct way to use for loop in classes?

class Employee():
    def main(self,name,idno,position,salary):

        self.name=name
        self.idno=idno
        self.position=position
        self.salary = salary

    def input(self):
        n=int(raw_input("Enter the number of employees:"))
        for i in range(n):
            self.name=raw_input("Name:")
            self.idno=raw_input("Idno:")
            self.position=raw_input("position:")
            self.salary=raw_input("salary:")

            print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
                  "salary:", self.salary)

if __name__=='__main__':
        result=Employee()
        result.input()

Body:
This illustrates what I was saying in my comment about using a for loop outside of the class:

class Employee(object):
    def __init__(self, name, idno, position, salary):
        self.name=name
        self.idno=idno
        self.position=position
        self.salary = salary

    def print_data(self):
        print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
              "salary:", self.salary)

if __name__=='__main__':

    def input_employee_data():
        print('Enter data for an employee')
        name = raw_input("Name:")
        idno = raw_input("Idno:")
        position = raw_input("position:")
        salary = raw_input("salary:")
        print('')
        return name, idno, position, salary

    employees = list()
    n = int(raw_input("Enter the number of employees:"))
    for i in range(n):
        name, idno, position, salary = input_employee_data()
        employee = Employee(name, idno, position, salary)
        employees.append(employee)

    print('List of employess')
    for employee in employees:
        employee.print_data()


问:
didSelectItemAt not working from SCLAlertView
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

```<code>    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}
</code>```

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.

答: You need to add collectionview delegate in protocol section. And be sure that you have make outlets of your object.</p>

Body:
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.


问:
How can I copy a file and update SQL database as a single transaction?
My application needs to monitor a folder to incoming files and when it notices a new file has arrived, I need to copy it to another location and insert a record into a SQL database.

The problem is that these two actions are independent and do not succeed or fail together as a transaction.

Are there any options to solve this?

One option is to update SQL first and then copy the file and then update SQL and if it fails delete the file, but that delete operation can also fail causing both actions to become out of sync.

There is a system called Transactional NTFS but Microsoft recommends against using it.

答:
You should

Create a database transaction

Create the file system transaction

Do the database operations, without commiting the transaction

Do the file system operations

Commit the database transaction and the file system transaction if all ok, rollback both if something went wrong (r).

I would suggest checking this or something similar for the file system transaction http://transactionalfilemgr.codeplex.com/.


问:
NSStrikethroughStyleAttributeName , How to strike out the string in iOS 10.3?
I have used this line of code before release of iOS 10.3 ,and worked fine.

```<code>NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",strMRP,strOffer]];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0, strMRP.length)];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(strMRP.length, strOffer.length+1)];

[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:[NSNumber numberWithInteger: NSUnderlineStyleDouble]
                        range:NSMakeRange(0,strMRP.length)];
</code>```

But now it is stopped working ,is there any alternate way to do the strike out ?

答:
As mentioned above, this is an iOS 10.3 bug.

We needed an immediate workaround, so just in case anyone is looking for hints:
Our Label had attributes set through both NSMutableAttributedString as well as NSMutableParagraphStyle. The bug did not occur when using no / an "empty" paragraph style (instance without any properties set).

So in this scenario, omitting the paragraph style and working around the then missing paragraph properties resolved the issue for us.

Body:
I have used this line of code before release of iOS 10.3 ,and worked fine.

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",strMRP,strOffer]];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0, strMRP.length)];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(strMRP.length, strOffer.length+1)];

[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:[NSNumber numberWithInteger: NSUnderlineStyleDouble]
                        range:NSMakeRange(0,strMRP.length)];

But now it is stopped working ,is there any alternate way to do the strike out ?


问:
Xamarin Forms Signature Pad
Can someone please guide me on how to use a signature pad on xamarin FORMS.

I have tried resources available online, but the dont work in my project.

```<code> <?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:acr="clr-namespace:Acr.XamForms.SignaturePad;assembly=Acr.XamForms.SignaturePad" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Checkin.Signature">
<ContentPage.Content>
<ScrollView>
    <StackLayout>
        <acr:SignaturePadView
            x:Name="padView"
            HeightRequest="320"
            WidthRequest="240"

            BackgroundColor="White"
            CaptionText="Caption This"
            CaptionTextColor="Black"
            ClearText="Clear Me!"
            ClearTextColor="Red"
            PromptText="Prompt Here"
            PromptTextColor="Red"
            SignatureLineColor="Aqua"
            StrokeColor="Black"
            StrokeWidth="2"
        />
    </StackLayout>
</ScrollView>
</ContentPage.Content>
</code>```

Above is one of the codes I have used. A signature pad appears but doesent display anything when I draw on top of it.

This is how the Red Signature pad appears

答:
In the AppDelegate, paste the following code:

```<code>public static Type dummyt = typeof(SignaturePad.Forms.iOS.SignaturePadRenderer);
</code>```

As shown below:

```<code>public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public static Type dummyt = typeof(SignaturePad.Forms.iOS.SignaturePadRenderer);
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
</code>```

The problem apparently is that some DLLs are not

Title: Xamarin Forms Signature Pad

Body:
Can someone please guide me on how to use a signature pad on xamarin FORMS.

I have tried resources available online, but the dont work in my project.

 <?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:acr="clr-namespace:Acr.XamForms.SignaturePad;assembly=Acr.XamForms.SignaturePad" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Checkin.Signature">
<ContentPage.Content>
<ScrollView>
    <StackLayout>
        <acr:SignaturePadView
            x:Name="padView"
            HeightRequest="320"
            WidthRequest="240"

            BackgroundColor="White"
            CaptionText="Caption This"
            CaptionTextColor="Black"
            ClearText="Clear Me!"
            ClearTextColor="Red"
            PromptText="Prompt Here"
            PromptTextColor="Red"
            SignatureLineColor="Aqua"
            StrokeColor="Black"
            StrokeWidth="2"
        />
    </StackLayout>
</ScrollView>
</ContentPage.Content>

Above is one of the codes I have used. A signature pad appears but doesent display anything when I draw on top of it.

This is how the Red Signature pad appears

Body:
In the AppDelegate, paste the following code:

public static Type dummyt = typeof(SignaturePad.Forms.iOS.SignaturePadRenderer);

As shown below:

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public static Type dummyt = typeof(SignaturePad.Forms.iOS.SignaturePadRenderer);
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {

The problem apparently is that some DLLs are not