问:
Typescript Code is not returning any output, but is running
I am trying to get a string with a number where, if there is a match between the former and later number add it to a sum total, so 55412 will be 5 and 112332 will be 1 + 3 so 4. This is coded in typescript, the problem is my code doesn't output anything.

```<code>function uipath(e, arg)
{
  let stringToInt = new StringToInt("5514133");
  stringToInt.charCompareAndSum();
  stringToInt.stringSplit();
  alert (stringToInt.getSumList.toString);
}

class StringToInt
{
  private argumentString : string ;
  private numberArr : Array<string>;
  private sumList : number;

  constructor( arg: string)
  {
    this.argumentString = arg ;
  }

  stringSplit()
  {
    this.numberArr = this.argumentString.split(/(?=.)/u);
  }

  charCompareAndSum()
  {
    for(var i = 0; i < this.numberArr.length -1; i++ )
    {
      if (this.numberArr[i] == this.numberArr[i+1])
      {
        this.sumList = this.sumList + +this.numberArr[i];
      }
    }
  }

  get getSumList():number
  {
    return this.sumList;
  }
}
</code>```

The output should be 8.

答:
Unless I'm missing something, you need to call your functions:

```<code>stringToInt.getSumList.toString
</code>```

Should be

```<code>stringToInt.getSumList().toString()
</code>```

I'm guessing this prints nothing because

```<code>stringToInt.getSumList
</code>```

Evaluates to the getSumList function itself, then

```<code>getSumList.toString
</code>```

Evaluates to undefined since the function doesn't have a toString property.

Body:
I am trying to get a string with a number where, if there is a match between the former and later number add it to a sum total, so 55412 will be 5 and 112332 will be 1 + 3 so 4. This is coded in typescript, the problem is my code doesn't output anything.

function uipath(e, arg)
{
  let stringToInt = new StringToInt("5514133");
  stringToInt.charCompareAndSum();
  stringToInt.stringSplit();
  alert (stringToInt.getSumList.toString);
}

class StringToInt
{
  private argumentString : string ;
  private numberArr : Array<string>;
  private sumList : number;

  constructor( arg: string)
  {
    this.argumentString = arg ;
  }

  stringSplit()
  {
    this.numberArr = this.argumentString.split(/(?=.)/u);
  }

  charCompareAndSum()
  {
    for(var i = 0; i < this.numberArr.length -1; i++ )
    {
      if (this.numberArr[i] == this.numberArr[i+1])
      {
        this.sumList = this.sumList + +this.numberArr[i];
      }
    }
  }

  get getSumList():number
  {
    return this.sumList;
  }
}

The output should be 8.

Body:
Unless I'm missing something, you need to call your functions:

stringToInt.getSumList.toString

Should be

stringToInt.getSumList().toString()

I'm guessing this prints nothing because

stringToInt.getSumList

Evaluates to the getSumList function itself, then

getSumList.toString

Evaluates to undefined since the function doesn't have a toString property.


来源: stackexchange

问:
Reshape from wide to long in big query (standard SQL)
Unfortunately reshaping in BQ it's not as easy as in R and I can't export my data for this project.

Here is input

```<code>date    country A             B         C      D
20170928    CH  3000.3        121       13     3200
20170929    CH  2800.31       137       23     1614.31
</code>```

Expected output

```<code>date    country Metric  Value
20170928    CH  A       3000.3
20170928    CH  B       121
20170928    CH  C       13
20170928    CH  D       3200
20170929    CH  A       2800.31
20170929    CH  B       137
20170929    CH  C       23
20170929    CH  D       1614.31
</code>```

Also my table has many more columns and rows (but I assume a lot of manual will be required)

答:
Below is for BigQuery Standard SQL and does not require repeating selects depends on number of columns. It will pick as many as you have and transform them into metrics and values

```<code>#standardSQL
SELECT DATE, country,
  metric, SAFE_CAST(value AS FLOAT64) value
FROM (
  SELECT DATE, country,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(0)], r'^"|"$', '') metric,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(1)], r'^"|"$', '') value
  FROM `project.dataset.yourtable` t,
  UNNEST(SPLIT(REGEXP_REPLACE(to_json_string(t), r'{|}', ''))) pair
)
WHERE NOT LOWER(metric) IN ('date', 'country')
</code>```

You can test / play with above using dummy data as in your question

```<code>#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT '20170928' DATE, 'CH' country, 3000.3 A, 121 B, 13 C, 3200 D UNION ALL
  SELECT '20170929', 'CH', 2800.31, 137, 23, 1614.31
)
SELECT DATE, country,
  metric, SAFE_CAST(value AS FLOAT64) value
FROM (
  SELECT DATE, country,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(0)], r'^"|"$', '') metric,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(1)], r'^"|"$', '') value
  FROM `project.dataset.yourtable` t,
  UNNEST(SPLIT(REGEXP_REPLACE(to_json_string(t), r'{|}', ''))) pair
)
WHERE NOT LOWER(metric) IN ('date', 'country')
</code>```

result is as expected

```<code>DATE        country metric  value
20170928    CH      A       3000.3
20170928    CH      B       121.0
20170928    CH      C       13.0
20170928    CH      D       3200.0
20170929    CH      A       2800.31
20170929    CH      B       137.0
20170929    CH      C       23.0
20170929    CH      D       1614.31
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Unfortunately reshaping in BQ it's not as easy as in R and I can't export my data for this project.

Here is input

date    country A             B         C      D
20170928    CH  3000.3        121       13     3200
20170929    CH  2800.31       137       23     1614.31

Expected output

date    country Metric  Value
20170928    CH  A       3000.3
20170928    CH  B       121
20170928    CH  C       13
20170928    CH  D       3200
20170929    CH  A       2800.31
20170929    CH  B       137
20170929    CH  C       23
20170929    CH  D       1614.31

Also my table has many more columns and rows (but I assume a lot of manual will be required)

Body:
Below is for BigQuery Standard SQL and does not require repeating selects depends on number of columns. It will pick as many as you have and transform them into metrics and values

#standardSQL
SELECT DATE, country,
  metric, SAFE_CAST(value AS FLOAT64) value
FROM (
  SELECT DATE, country,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(0)], r'^"|"$', '') metric,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(1)], r'^"|"$', '') value
  FROM `project.dataset.yourtable` t,
  UNNEST(SPLIT(REGEXP_REPLACE(to_json_string(t), r'{|}', ''))) pair
)
WHERE NOT LOWER(metric) IN ('date', 'country')

You can test / play with above using dummy data as in your question

#standardSQL
WITH `project.dataset.yourtable` AS (
  SELECT '20170928' DATE, 'CH' country, 3000.3 A, 121 B, 13 C, 3200 D UNION ALL
  SELECT '20170929', 'CH', 2800.31, 137, 23, 1614.31
)
SELECT DATE, country,
  metric, SAFE_CAST(value AS FLOAT64) value
FROM (
  SELECT DATE, country,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(0)], r'^"|"$', '') metric,
    REGEXP_REPLACE(SPLIT(pair, ':')[OFFSET(1)], r'^"|"$', '') value
  FROM `project.dataset.yourtable` t,
  UNNEST(SPLIT(REGEXP_REPLACE(to_json_string(t), r'{|}', ''))) pair
)
WHERE NOT LOWER(metric) IN ('date', 'country')

result is as expected

DATE        country metric  value
20170928    CH      A       3000.3
20170928    CH      B       121.0
20170928    CH      C       13.0
20170928    CH      D       3200.0
20170929    CH      A       2800.31
20170929    CH      B       137.0
20170929    CH      C       23.0
20170929    CH      D       1614.31


问:
Insert column if it doesn't exist
I am trying to insert a new column in my database if it isn't inserted earlier.
My column looks like this

```<code>ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0
</code>```

I want the column to be inserted only if it is not in the table.

My line of code only inserts it but doesn't check if it exists.

答:
Try this:</p>

```<code>IF (SELECT COUNT(*) FROM syscolumns WHERE name = 'HasAccess24_7'
AND OBJECT_NAME(object_id) = 'tSafeUnit') = 0
BEGIN
    ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0
END
</code>```

ContentLicense: CC BY-SA 4.0

Title: Insert column if it doesn't exist

Body:
I am trying to insert a new column in my database if it isn't inserted earlier.
My column looks like this

ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0

I want the column to be inserted only if it is not in the table.

My line of code only inserts it but doesn't check if it exists.

Body:
Try this:

IF (SELECT COUNT(*) FROM syscolumns WHERE name = 'HasAccess24_7'
AND OBJECT_NAME(object_id) = 'tSafeUnit') = 0
BEGIN
    ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0
END


问:
How to alert on queue size on azure service bus
I have a premium service bus in Azure with a number of Queues. I can set max size for these, but I can't seem to find a way to alert the support team, via any route, but I would prefer email, if these queues exceed 1,000 messages in length, ie our consumers have fallen over or are not processing fast enough.

How can I set up some form of alerting for queue length on Azure service bus?

P.S. we still seem to be waiting for it to be implemented as a first class feature: https://feedback.azure.com/forums/231545-diagnostics-and-monitoring/suggestions/4486464-alerts-based-on-queue-size

答:
I haven't heard of out-of-the-box solution which does not involve custom code or 3rd party service.

IMO, what often happens is that the company has a tool to monitor all operational metrics of their IT landscape, and also do alerts. Depending on the tool, there might be varying levels of Azure Services monitoring support.

If you don't have such tool, or your tool doesn't integrate with Service Bus, one approach is to create an Azure Function (or multiple functions) to retrieve statistics from Service Bus queues, and then integrate it with an alert-enabled tool.

The suggestion forum from your question has a link to such integration to Azure Application Insights. We use PRTG for monitoring and alerting, so we integrated PRTG to Azure Functions.


问:
Xamarin IOS Facebook SDK LoginButton
Im new to Xamarin and IOS development and dont understand why I get this following error:

But first some Information:

Im using this SDK:
https://components.xamarin.com/view/facebookios

and creating my LoginButtin in my ViewController in ViewDidLoad like this:

```<code>loginButton = new LoginButton(new CGRect(48, 0, 218, 46))
            {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };
            View.AddSubview(button);
</code>```

But in my Storyboard I get this error message:

Edit: my ViewController.cs

```<code>using System;
using System.Collections.Generic;
using UIKit;

namespace FacebookLogin
{
    public partial class ViewController : UIViewController
    {
        List<string> readPermissions = new List<string> { "public_profile" };
        LoginButton loginButton;

        public ViewController(IntPtr handle) : base(handle)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            loginButton = new LoginButton(new CGRect(48, 0, 218, 46))
            {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };
            View.AddSubview(button);
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }
}
</code>```

答:
Make sure to follow the instructions found on the getting started page. I see an empty component in your solution explorer but just in case, make sure that you installed Xamarin.Facebook.iOS 4.27.1 with nugget. Of course, you also need to set up your facebook app, login, and configure the iOS portion (like setting the BundleID).

Don't create the button in the controller. What you can do is use the storyBoard designer to drop in a regular button. Then, in the properties window click on Class and it should open a dropdown menu. In the selection you should see FBSDKLoginButton, select that class. Give it a name like btnFacebook.

In the codebehind for your controller it will look like this:

```<code>string[] readPermissions = { "public_profile" };

public override void ViewDidLoad()
{
  base.ViewDidLoad();
  btn.LoginBehavior = LoginBehavior.Native;
  btnFacebook.ReadPermissions = readPermissions;
  // Handle actions once the user is logged in
  btnFacebook.Completed += LoginView_Completed;
  // Handle actions once the user is logged out
  btnFacebook.LoggedOut += LoginView_LoggedOut;
}

private void LoginView_Completed(object sender, LoginButtonCompletedEventArgs e)
{
  if (e.Error != null)
  {
    return;
  }

  if (e.Result.IsCancelled)
  {
    return;
  }
}

private void LoginView_LoggedOut(object sender, EventArgs e)
{

}
</code>```

For good measure, clean solution and recompile. The login button won't appear as a facebook login button in your designer but on runtime it will.

As for your error, I don't see anything in your designer so it's curious that it's giving you an error like that. Open the Document Outline (View -> Other Windows -> Document Outline) and see if there's any invisible garbage (elements that aren't being rendered) that has to be deleted.

Title: Xamarin IOS Facebook SDK LoginButton

Body:
Im new to Xamarin and IOS development and dont understand why I get this following error:

But first some Information:

Im using this SDK:
https://components.xamarin.com/view/facebookios

and creating my LoginButtin in my ViewController in ViewDidLoad like this:

loginButton = new LoginButton(new CGRect(48, 0, 218, 46))
            {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };
            View.AddSubview(button);

But in my Storyboard I get this error message:

Edit: my ViewController.cs

using System;
using System.Collections.Generic;
using UIKit;

namespace FacebookLogin
{
    public partial class ViewController : UIViewController
    {
        List<string> readPermissions = new List<string> { "public_profile" };
        LoginButton loginButton;

        public ViewController(IntPtr handle) : base(handle)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            loginButton = new LoginButton(new CGRect(48, 0, 218, 46))
            {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };
            View.AddSubview(button);
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }
}

Body:
Make sure to follow the instructions found on the getting started page. I see an empty component in your solution explorer but just in case, make sure that you installed Xamarin.Facebook.iOS 4.27.1 with nugget. Of course, you also need to set up your facebook app, login, and configure the iOS portion (like setting the BundleID).

Don't create the button in the controller. What you can do is use the storyBoard designer to drop in a regular button. Then, in the properties window click on Class and it should open a dropdown menu. In the selection you should see FBSDKLoginButton, select that class. Give it a name like btnFacebook.

In the codebehind for your controller it will look like this:

string[] readPermissions = { "public_profile" };

public override void ViewDidLoad()
{
  base.ViewDidLoad();
  btn.LoginBehavior = LoginBehavior.Native;
  btnFacebook.ReadPermissions = readPermissions;
  // Handle actions once the user is logged in
  btnFacebook.Completed += LoginView_Completed;
  // Handle actions once the user is logged out
  btnFacebook.LoggedOut += LoginView_LoggedOut;
}

private void LoginView_Completed(object sender, LoginButtonCompletedEventArgs e)
{
  if (e.Error != null)
  {
    return;
  }

  if (e.Result.IsCancelled)
  {
    return;
  }
}

private void LoginView_LoggedOut(object sender, EventArgs e)
{

}

For good measure, clean solution and recompile. The login button won't appear as a facebook login button in your designer but on runtime it will.

As for your error, I don't see anything in your designer so it's curious that it's giving you an error like that. Open the Document Outline (View -> Other Windows -> Document Outline) and see if there's any invisible garbage (elements that aren't being rendered) that has to be deleted.


问:
Shutting down spring boot application on db table space error
I have the following scheduled piece of code in my Spring Boot Application:

```<code>@Scheduled(fixedDelay = DELAY_SECONDS)
private void processJobQueue() {

    BlockingQueue<ReportDeliverable> jobQueue = JobQueueFactory.getJobQueueInstance();

    while (!jobQueue.isEmpty()) {

        //do stuff
        if (rCount == 0) {

            status = send(reportDeliverable);

            if (status == TransferStatus.FAILURE) {
                populateQueue(reportDeliverable);
            }

            if (status == TransferStatus.SUCCESS) { //write the metadata to database

                int i = dbMetadataWriter.writeMetadata(reportDeliverable);

            }
        } else if (rCount == -1) {
            populateQueue(reportDeliverable);
        } else
            logger.info("Record exists in MetaData for {}. Ignoring the File transfer....", reportDeliverable.getFilePath());
    }

}
</code>```

In my DBMetadataWriter component, the writeMetadataWriter() looks something like this:

```<code>@Component
public class DBMetadataWriter {

    public int writeMetadata(final ReportDeliverable reportDeliverable) {

        int nbInserted = 0;

        try {
            nbInserted = jdbcTemplate.update(PORTAL_METADATA_INSERT, insertDataValues);

        } catch (Exception e) {
            logger.error("Could not insert metadata for {}, Exception: {} ", reportDeliverable.toString(), e.getMessage());
        }

        return nbInserted;
    }
</code>```

In some cases, when writing the insert to the database, I get table space issues with the database at which point I think it would be wise for me to shut down the spring boot application until table space problems are resolved.

What would be the correct way to handle these rare cases? What technique can I use to gracefully shutdown the spring boot application and how can I do it in the above code?

My entry point class where I initially validate all my database connections before processing etc has the following...

```<code>@Component
public class RegisterReportSchedules implements ApplicationListener<ContextRefreshedEvent> {

 @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    }

    private void shutdownApplication() {
       int exitCode = SpringApplication.exit(applicationContext, (ExitCodeGenerator) () -> 0);
       System.exit(exitCode);
    }

    }
</code>```

答:
You have exit() method on  SpringApplication class, which can be used for exiting Spring boot application gracefully.

It requires 2 paramerter:

ApplicationContext

ExitCodeGenerator

For further reading:

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/SpringApplication.html#exit-org.springframework.context.ApplicationContext-org.springframework.boot.ExitCodeGenerator...-

Code Example:

```<code>@Autowired
public void shutDown(ExecutorServiceExitCodeGenerator exitCodeGenerator) {
    SpringApplication.exit(applicationContext, exitCodeGenerator);
}
</code>```

Call this method when you get exception for No Table space

Body:
I have the following scheduled piece of code in my Spring Boot Application:

@Scheduled(fixedDelay = DELAY_SECONDS)
private void processJobQueue() {

    BlockingQueue<ReportDeliverable> jobQueue = JobQueueFactory.getJobQueueInstance();

    while (!jobQueue.isEmpty()) {

        //do stuff
        if (rCount == 0) {

            status = send(reportDeliverable);

            if (status == TransferStatus.FAILURE) {
                populateQueue(reportDeliverable);
            }

            if (status == TransferStatus.SUCCESS) { //write the metadata to database

                int i = dbMetadataWriter.writeMetadata(reportDeliverable);

            }
        } else if (rCount == -1) {
            populateQueue(reportDeliverable);
        } else
            logger.info("Record exists in MetaData for {}. Ignoring the File transfer....", reportDeliverable.getFilePath());
    }

}

In my DBMetadataWriter component, the writeMetadataWriter() looks something like this:

@Component
public class DBMetadataWriter {

    public int writeMetadata(final ReportDeliverable reportDeliverable) {

        int nbInserted = 0;

        try {
            nbInserted = jdbcTemplate.update(PORTAL_METADATA_INSERT, insertDataValues);

        } catch (Exception e) {
            logger.error("Could not insert metadata for {}, Exception: {} ", reportDeliverable.toString(), e.getMessage());
        }

        return nbInserted;
    }

In some cases, when writing the insert to the database, I get table space issues with the database at which point I think it would be wise for me to shut down the spring boot application until table space problems are resolved.

What would be the correct way to handle these rare cases? What technique can I use to gracefully shutdown the spring boot application and how can I do it in the above code?

My entry point class where I initially validate all my database connections before processing etc has the following...

@Component
public class RegisterReportSchedules implements ApplicationListener<ContextRefreshedEvent> {

 @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    }

    private void shutdownApplication() {
       int exitCode = SpringApplication.exit(applicationContext, (ExitCodeGenerator) () -> 0);
       System.exit(exitCode);
    }

    }

Body:
You have exit() method on  SpringApplication class, which can be used for exiting Spring boot application gracefully.

It requires 2 paramerter:

ApplicationContext

ExitCodeGenerator

For further reading:

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/SpringApplication.html#exit-org.springframework.context.ApplicationContext-org.springframework.boot.ExitCodeGenerator...-

Code Example:

@Autowired
public void shutDown(ExecutorServiceExitCodeGenerator exitCodeGenerator) {
    SpringApplication.exit(applicationContext, exitCodeGenerator);
}

Call this method when you get exception for No Table space


问:
How to create a swiftmailer message and attach it to another message
We are using SwiftMailer in one of our functions who sends emails out.
At the end, there is a general report sent to the department manager in order to keep trace and be informed about the function usage.

The manager is now willing to also receive a copy of the email sent out, we could do this by adding one email copy as attachment to the email report.

Any idea on how can we create a swiftmailer message and not sending it, only using it as attachment for a new swiftmailer email.

答:
You could add your Swift_Message as an attachment like this:

```<code>$attachment = new \Swift_Attachment($messageAttachment, 'some-email.txt', 'text/plain');
</code>```

However, your email would be now attached as an .txt file which contains all mail details. I'm not sure if this is the expected behaviour!?

Full example:

```<code>$messageAttachment = (new \Swift_Message('Attached Email'))
    ->setFrom('yourmail@gmail.com')->setTo('yourmail@gmail.com')
    ->setBody("Attached Email Body", 'text/plain');
$attachment = new \Swift_Attachment($messageAttachment, 'some-email.txt', 'text/plain');

$message = (new \Swift_Message('Real Email'))
    ->setFrom('yourmail@gmail.com')->setTo('yourmail@gmail.com')
    ->setBody("Real Email Body", 'text/plain')
    ->attach($attachment);
$mailer->send($message);
</code>```

The content of the attached some-email.txt will look like this:

```<code>Message-ID: <568d128d97e530d1389cb83b154d64eb@swift.generated>
Date: Tue, 05 Dec 2017 17:00:05 +0100
Subject: Attached Email
From: yourmail@gmail.com
To: yourmail@gmail.com
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Attached Email Body
</code>```

Body:
You could add your Swift_Message as an attachment like this:

$attachment = new \Swift_Attachment($messageAttachment, 'some-email.txt', 'text/plain');

However, your email would be now attached as an .txt file which contains all mail details. I'm not sure if this is the expected behaviour!?

Full example:

$messageAttachment = (new \Swift_Message('Attached Email'))
    ->setFrom('yourmail@gmail.com')->setTo('yourmail@gmail.com')
    ->setBody("Attached Email Body", 'text/plain');
$attachment = new \Swift_Attachment($messageAttachment, 'some-email.txt', 'text/plain');

$message = (new \Swift_Message('Real Email'))
    ->setFrom('yourmail@gmail.com')->setTo('yourmail@gmail.com')
    ->setBody("Real Email Body", 'text/plain')
    ->attach($attachment);
$mailer->send($message);

The content of the attached some-email.txt will look like this:

Message-ID: <568d128d97e530d1389cb83b154d64eb@swift.generated>
Date: Tue, 05 Dec 2017 17:00:05 +0100
Subject: Attached Email
From: yourmail@gmail.com
To: yourmail@gmail.com
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Attached Email Body


问:
How to avoid color changes when button is disabled?
We have a Windows Forms project with quite a few FlatStyle buttons.

When we disable the buttons, the colors of the buttons are changed automatically Frown | :(

Is it possible to override this somehow, so we can control the colors ourselves?

答:
I followed the following approach :-
The Click() event of the button can be controlled using custom variable.

```<code>private bool btnDisabled;
private void btnClick(object sender, EventArgs e){
   if(!btnDisabled) return;}
</code>```

This way the button doesn't even need to be disabled. The button still has the click feel but no action will be taken. Have to use the right colors to communicate that the button is disabled.

Body:
I followed the following approach :-
The Click() event of the button can be controlled using custom variable.

private bool btnDisabled;
private void btnClick(object sender, EventArgs e){
   if(!btnDisabled) return;}

This way the button doesn't even need to be disabled. The button still has the click feel but no action will be taken. Have to use the right colors to communicate that the button is disabled.


问:
iReport crashing while importing / exporting data-source settings how can I debug it?
I am using IReport 5.6.0 (though 5.0.0 has the same behavior) on Windows 10 64 bit machine.

I have tried to run The IReport with: jdk 1.6 64 bit, jre 1.7 64 bit, jre 1.7 32 bit (I have also jdk 1.8 installed but I am not using that with iReport as I now there is an incompatibility issues).

The environment starts normally - however if i try to push import or export  buttons on datasource window - the iReport just exits and the window is closed - no error message is shown.

My colleagues with the same type of machines (W10 jre 1.7 32 bit) have no problem what so ever.

My question is - is there a way to get more information - as of why iReport exits what kind of exception is thrown etc... In other words how to debug this behavior?

答:
For the history ...

It turns out that the problem was caused by "God Mode" folder that was on my Desktop.
Also the crash report has been saving all that time on my desktop, without me realizing it.

Deleting the folder solved the problem.


问:
text not populating after hyphen in textbox from vb listview
I am working on an ASPX VB.NET web app that lets you search from a list of job titles and when you select a job title and click the add button it adds the job title to the textbox called tbJobTitle.

The problem is that when there is a job title with a hyphen in it only the 1st part of the title is passed to tbJobTitle so for example if you have the job title called 1234--admin assistant - IT admin as the job title only the admin assistant gets sent to the tbJobTitle textbox. I need the whole thing to pass to the tbJobTitle textbox.

Here is my .vb code:

```<code>Private Sub btnAddTitle_Click(sender As Object, e As EventArgs) Handles btnAddTitle.Click
    For Each item As ListItem In lbJobTitle.Items
        If item.Selected Then
            If Not lbTitles.Items.Contains(item) Then
                lbTitles.Items.Add(item)
                Dim str As String = lbTitles.SelectedItem.Text
                Dim strArr As String() = Nothing
                Dim splitchar As Char() = {"--"}
                strArr = str.Split(splitchar)
                tbJobTitle.Text = strArr(2)
            End If
        End If
End Sub
</code>```

答:
This happens because microsoft decided to set option strict to off as default. So every new developer runs in such ugly bugs. Normally this gives a compiler error. Why?

Because this is not valid:

```<code>Dim splitchar As Char() = {"--"}
</code>```

You are initializing a Char() with a single String. Valid would be this(note the "-"c):

```<code>Dim splitchar As Char() = {"-"c} ' this will split by a single hyphen
</code>```

Now, what happens if Option Strict is set to Off? it will compile and introduce a much worse bug. It will silently take the first char of the string and use that. So you actually get this array:

```<code>Dim splitchar As Char() = {"-"c} ' this will split by a single hyphen
</code>```

which is not what you wanted. This is what you wanted(note the String()):

```<code>Dim splitStrings As String() = {"--"} ' this will split by  double hyphen
strArr = str.Split(splitStrings, StringSplitOptions.None))
</code>```

You need the overload of String.Split that takes a String() and  StringSplitOptions.

I strongly recommend to set Option Strict to On and learn to write type safe and clean code.

Here is a class that demonstrates the whole mess:

```<code>Option Strict Off

Public Class OptionStrictDemo
    Shared sub ShowMess()
        Dim aChar As Char = "f"c
        Dim otherChar As Char = "foo"
        Dim isMess = aChar = otherChar
        Console.Write("Is it a mess? " & if(isMess, "yes", "no")) ' Is it a mess? yes
    End sub
End Class
</code>```

If you'd set Option Strict On(better make it default) you would get a compiler error.

Body:
I am working on an ASPX VB.NET web app that lets you search from a list of job titles and when you select a job title and click the add button it adds the job title to the textbox called tbJobTitle.

The problem is that when there is a job title with a hyphen in it only the 1st part of the title is passed to tbJobTitle so for example if you have the job title called 1234--admin assistant - IT admin as the job title only the admin assistant gets sent to the tbJobTitle textbox. I need the whole thing to pass to the tbJobTitle textbox.

Here is my .vb code:

Private Sub btnAddTitle_Click(sender As Object, e As EventArgs) Handles btnAddTitle.Click
    For Each item As ListItem In lbJobTitle.Items
        If item.Selected Then
            If Not lbTitles.Items.Contains(item) Then
                lbTitles.Items.Add(item)
                Dim str As String = lbTitles.SelectedItem.Text
                Dim strArr As String() = Nothing
                Dim splitchar As Char() = {"--"}
                strArr = str.Split(splitchar)
                tbJobTitle.Text = strArr(2)
            End If
        End If
End Sub

Body:
This happens because microsoft decided to set option strict to off as default. So every new developer runs in such ugly bugs. Normally this gives a compiler error. Why?

Because this is not valid:

Dim splitchar As Char() = {"--"}

You are initializing a Char() with a single String. Valid would be this(note the "-"c):

Dim splitchar As Char() = {"-"c} ' this will split by a single hyphen

Now, what happens if Option Strict is set to Off? it will compile and introduce a much worse bug. It will silently take the first char of the string and use that. So you actually get this array:

Dim splitchar As Char() = {"-"c} ' this will split by a single hyphen

which is not what you wanted. This is what you wanted(note the String()):

Dim splitStrings As String() = {"--"} ' this will split by  double hyphen
strArr = str.Split(splitStrings, StringSplitOptions.None))

You need the overload of String.Split that takes a String() and  StringSplitOptions.

I strongly recommend to set Option Strict to On and learn to write type safe and clean code.

Here is a class that demonstrates the whole mess:

Option Strict Off

Public Class OptionStrictDemo
    Shared sub ShowMess()
        Dim aChar As Char = "f"c
        Dim otherChar As Char = "foo"
        Dim isMess = aChar = otherChar
        Console.Write("Is it a mess? " & if(isMess, "yes", "no")) ' Is it a mess? yes
    End sub
End Class

If you'd set Option Strict On(better make it default) you would get a compiler error.


问:
How to implement a service oriented architecture in Objective-C?
I'm wondering which one of the following would be the correct usage / implementation in Objective-C of a service oriented design:

The first version is specific to static languages, using protocols (interfaces):

```<code>//
// get the cloud service from our service provider
//
id<CloudServices> myService = [ServiceProvider serviceWithProtocol:@protocol(CloudServices)];
</code>```

The second version isn't using protocols, is relying on the fact that Objective-C is actually dynamic:

```<code>//
// get the cloud service from our service provider
//
CloudServices *myService = [ServiceProvider serviceWithClass:[CloudServices class]];
</code>```

Obviously the difference is CloudServices being an interface or protocol, and we imply that the ServiceProvider can be configured to return different implementations of the CloudServices.

So my question is which style to choose, and why ?

Thanks.

答:
It depends on how your services work. Using classes, the ServiceProvider can simply instantiate the class if required and perform initialization on the object. Using protocols, ServiceProvider has to know which classes are available for services, which could prevent some bugs with passing the wrong class. You could also have one class implement multiple protocols and therefore be used for different calls to serviceWithProtocol:.

Short version: Using classes would be simpler, using protocols would be more flexible and possibly safer.

ContentLicense: CC BY-SA 2.5

Body:
I'm wondering which one of the following would be the correct usage / implementation in Objective-C of a service oriented design:

The first version is specific to static languages, using protocols (interfaces):

//
// get the cloud service from our service provider
//
id<CloudServices> myService = [ServiceProvider serviceWithProtocol:@protocol(CloudServices)];

The second version isn't using protocols, is relying on the fact that Objective-C is actually dynamic:

//
// get the cloud service from our service provider
//
CloudServices *myService = [ServiceProvider serviceWithClass:[CloudServices class]];

Obviously the difference is CloudServices being an interface or protocol, and we imply that the ServiceProvider can be configured to return different implementations of the CloudServices.

So my question is which style to choose, and why ?

Thanks.


问:
Process user input to "phrase/3" method in Prolog
I have build a DCG with Prolog. The code works, when I do the following call:

```<code>phrase(programm(R), [1,+,2], []).
</code>```

I want the user to write the input, so I did this:

```<code>main :- read(Input), atom_chars(Input, R), write(R), phrase(programm(E), R).
</code>```

Calling main and input e.g. '1+2' doesn't work. How can I process the user input to the phrase method for calling my DCG?

答:
The fundamental problem is the way you have defined characters and numbers in your grammar.  I assume you defined something along:

```<code>program(sum(L,R)) -->
    [L],
    [+],
    [R].
</code>```

You need first

```<code>:- set_prolog_flag(double_quotes, chars).

program(sum(L,R)) -->
   number(L),
   "+",
   number(R).

number(1) --> "1".
</code>```

Note that 1 is an integer and "1" is ['1']!

Body:
I have build a DCG with Prolog. The code works, when I do the following call:

phrase(programm(R), [1,+,2], []).

I want the user to write the input, so I did this:

main :- read(Input), atom_chars(Input, R), write(R), phrase(programm(E), R).

Calling main and input e.g. '1+2' doesn't work. How can I process the user input to the phrase method for calling my DCG?

Body:
The fundamental problem is the way you have defined characters and numbers in your grammar.  I assume you defined something along:

program(sum(L,R)) -->
    [L],
    [+],
    [R].

You need first

:- set_prolog_flag(double_quotes, chars).

program(sum(L,R)) -->
   number(L),
   "+",
   number(R).

number(1) --> "1".

Note that 1 is an integer and "1" is ['1']!


问:
Given a list of tuples representing ranges ,condense the ranges (Write a function)
I am learning Python 2.x and would like to address following issue.
Need a function to condense the ranges

Problem :Given a list of tuples representing ranges ,condense the ranges

```<code>Input : [(2,3),(4,5),(7,8),(8,10),(12,15)]
Output :[(2,5),(7,10),(12,15)]
</code>```

Any pointer or help would be great help

答:
Merging ranges is not as easy and straightforward as it seems. You have to pay attention to overlaps over multiple input ranges, as well as inclusions, i/e ranges entirely contained in another.

It is also necessary to ensure that the input is sorted by start values.

Here is a somewhat tested solution:

```<code>def overlap(r1, r2):
    return r1[1] >= r2[0] - 1    # <-- -1 to ensure ranges like (2, 3) and (4, 5) merge into (2, 5)

def merge_range(r1, r2):
    s1, e1 = r1
    s2, e2 = r2
    return (min(s1, s2), max(e1, e2))

def regroup_ranges(rgs):
    assert all([s <= e for s, e in rgs])
    if len(rgs) == 0:
        return rgs

    rngs.sort()

    regrouped = [rgs[0]]

    for r2 in rgs[1:]:
        r1 = regrouped.pop()
        if overlap(r1, r2):
            regrouped.append(merge_range(r1, r2))
        else:
            regrouped.append(r1)
            regrouped.append(r2)

    return regrouped
</code>```

Tests:

```<code>def test_regroup_ranges():
    rngs = [(2, 3), (4, 5), (7, 8), (8, 10), (12, 15)]
    compressed = [(2, 5), (7, 10), (12, 15)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 8), (4, 5), (7, 8), (8, 10), (12, 15)]
    compressed = [(2, 10), (12, 15)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3) ,(4, 5), (1, 16), (8, 10), (12, 15)]
    compressed = [(1, 16)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3), (4, 20), (7, 8), (8, 10), (12, 15)]
    compressed = [(2, 20)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3), (5, 8), (10, 12)]
    compressed = [(2, 3), (5, 8), (10, 12)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3)]
    compressed = [(2, 3)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = []
    compressed = []
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    print("***all tests pass***")

test_regroup_ranges()
</code>```

Tests results:

```<code>[(2, 5), (7, 10), (12, 15)]
[(2, 10), (12, 15)]
[(1, 16)]
[(2, 20)]
[(2, 3), (5, 8), (10, 12)]
[(2, 3)]
[]
***all tests pass***
</code>```

Body:
I am learning Python 2.x and would like to address following issue.
Need a function to condense the ranges

Problem :Given a list of tuples representing ranges ,condense the ranges

Input : [(2,3),(4,5),(7,8),(8,10),(12,15)]
Output :[(2,5),(7,10),(12,15)]

Any pointer or help would be great help

Body:
Merging ranges is not as easy and straightforward as it seems. You have to pay attention to overlaps over multiple input ranges, as well as inclusions, i/e ranges entirely contained in another.

It is also necessary to ensure that the input is sorted by start values.

Here is a somewhat tested solution:

def overlap(r1, r2):
    return r1[1] >= r2[0] - 1    # <-- -1 to ensure ranges like (2, 3) and (4, 5) merge into (2, 5)

def merge_range(r1, r2):
    s1, e1 = r1
    s2, e2 = r2
    return (min(s1, s2), max(e1, e2))

def regroup_ranges(rgs):
    assert all([s <= e for s, e in rgs])
    if len(rgs) == 0:
        return rgs

    rngs.sort()

    regrouped = [rgs[0]]

    for r2 in rgs[1:]:
        r1 = regrouped.pop()
        if overlap(r1, r2):
            regrouped.append(merge_range(r1, r2))
        else:
            regrouped.append(r1)
            regrouped.append(r2)

    return regrouped

Tests:

def test_regroup_ranges():
    rngs = [(2, 3), (4, 5), (7, 8), (8, 10), (12, 15)]
    compressed = [(2, 5), (7, 10), (12, 15)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 8), (4, 5), (7, 8), (8, 10), (12, 15)]
    compressed = [(2, 10), (12, 15)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3) ,(4, 5), (1, 16), (8, 10), (12, 15)]
    compressed = [(1, 16)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3), (4, 20), (7, 8), (8, 10), (12, 15)]
    compressed = [(2, 20)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3), (5, 8), (10, 12)]
    compressed = [(2, 3), (5, 8), (10, 12)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = [(2, 3)]
    compressed = [(2, 3)]
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    rngs = []
    compressed = []
    print(regroup_ranges(rngs))
    assert regroup_ranges(rngs) == compressed

    print("***all tests pass***")

test_regroup_ranges()

Tests results:

[(2, 5), (7, 10), (12, 15)]
[(2, 10), (12, 15)]
[(1, 16)]
[(2, 20)]
[(2, 3), (5, 8), (10, 12)]
[(2, 3)]
[]
***all tests pass***


问:
Update after Trigger
I have this trigger running in before insert sentences:

```<code>CREATE TRIGGER controlHoras before
insert ON conducen
REFERENCING NEW AS newrow for each row
BEGIN Atomic
declare entrega timestamp;
declare hoy date;
declare horaUsuario timestamp;
declare horaActual timestamp;
set (entrega)= (select max(horaentrega) from conducen where matricula = newrow.matricula and FECHARECOGIDA = newrow.fecharecogida);
set (hoy)= (today);
set (horaUsuario)=(select max(horaentrega) from conducen where FECHARECOGIDA = newrow.fecharecogida and userwin =newrow.userwin);
set (horaActual) = (sysdate);
if(newrow.horaRecogida < entrega) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'El coche esta ocupado a la hora que lo pretendes recoger, elige otra hora u otro coche.';
end if;
if(newrow.fecharecogida<hoy or newrow.HORARECOGIDA<horaActual) then
SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'Fecha o hora de recogida menor que la fecha actual.';
end if;
if(newrow.horaRecogida<horaUsuario) then
SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'No puedes conducir dos coches a la vez.';
end if;
end;
</code>```

But I need control the update setences, I have this trigger but not run correct:

```<code>CREATE TRIGGER controlHoras1 AFTER
UPDATE ON conducen
REFERENCING NEW AS newrow OLD AS oldrow FOR EACH ROW
BEGIN ATOMIC
declare entrega timestamp;
declare hoy date;
declare horaUsuario timestamp;
declare horaActual timestamp;

set (hoy)= (today);
set (horaUsuario)=(select max(oldrow.horaentrega) from conducen where FECHARECOGIDA = newrow.fecharecogida and userwin = newrow.userwin);
set (horaActual) = (sysdate);

if(newrow.fecharecogida < hoy or newrow.HORARECOGIDA < horaActual) then
SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'Fecha o hora de recogida menor que la fecha actual.';
end if;
if(newrow.horaRecogida < horaUsuario) then
SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'Verifica si lo datos son correctos y si el coche esta libre o si pretendes conducir dos coches a la vez.';
end if;
end;
</code>```

In the table  conducen i have this content;

(bcastrof, 9674-GZF, 2017-11-24, 2017-11-24 19:03:00.000000, 2017-11-24 22:03:00.000000)

but if intented update this row, using this sentence;

```<code>update conducen
set HORARECOGIDA='2017-11-24 20:03:00.000000', HORAENTREGA='2017-11-24 22:03:00.000000'
WHERE FECHARECOGIDA='2017-11-24'
AND USERWIN = 'bcastrof'
and matricula = '9674-GZF'
and HORARECOGIDA = '2017-11-24 19:03:00.000000';
</code>```

It doesn't work because it skips the exception 45002 the trigger. Please help.

答:
solution the problem:</p>

```<code>CREATE TRIGGER controlHoras1 AFTER
UPDATE ON conducen
REFERENCING NEW AS newrow OLD AS oldrow for each row
BEGIN Atomic
declare entrega timestamp;
declare hoy date;
declare horaUsuario timestamp;
declare horaActual timestamp;

set (entrega)= (select max(horaentrega) from conducen where matricula = newrow.matricula and FECHARECOGIDA = newrow.fecharecogida and horaentrega!=newrow.horaentrega);
set (hoy)= (today);
set (horaUsuario)=(select max(horaentrega) from conducen where FECHARECOGIDA = newrow.fecharecogida and userwin =newrow.userwin and horaentrega!=newrow.horaentrega and horarecogida<newrow.horarecogida);
set (horaActual) = (sysdate);
if(newrow.horaRecogida < entrega) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'El coche esta ocupado a la hora que lo pretendes recoger, elige otra hora u otro coche.';
end if;
if(newrow.fecharecogida<hoy or newrow.HORARECOGIDA<horaActual) then
SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'Fecha o hora de recogida menor que la fecha actual.';
end if;
if(newrow.horaRecogida<horaUsuario) then
SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'No puedes conducir dos coches a la vez.';
end if;
end;
</code>```

Title: Update after Trigger

Body:
I have this trigger running in before insert sentences:

CREATE TRIGGER controlHoras before
insert ON conducen
REFERENCING NEW AS newrow for each row
BEGIN Atomic
declare entrega timestamp;
declare hoy date;
declare horaUsuario timestamp;
declare horaActual timestamp;
set (entrega)= (select max(horaentrega) from conducen where matricula = newrow.matricula and FECHARECOGIDA = newrow.fecharecogida);
set (hoy)= (today);
set (horaUsuario)=(select max(horaentrega) from conducen where FECHARECOGIDA = newrow.fecharecogida and userwin =newrow.userwin);
set (horaActual) = (sysdate);
if(newrow.horaRecogida < entrega) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'El coche esta ocupado a la hora que lo pretendes recoger, elige otra hora u otro coche.';
end if;
if(newrow.fecharecogida<hoy or newrow.HORARECOGIDA<horaActual) then
SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'Fecha o hora de recogida menor que la fecha actual.';
end if;
if(newrow.horaRecogida<horaUsuario) then
SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'No puedes conducir dos coches a la vez.';
end if;
end;

But I need control the update setences, I have this trigger but not run correct:

CREATE TRIGGER controlHoras1 AFTER
UPDATE ON conducen
REFERENCING NEW AS newrow OLD AS oldrow FOR EACH ROW
BEGIN ATOMIC
declare entrega timestamp;
declare hoy date;
declare horaUsuario timestamp;
declare horaActual timestamp;

set (hoy)= (today);
set (horaUsuario)=(select max(oldrow.horaentrega) from conducen where FECHARECOGIDA = newrow.fecharecogida and userwin = newrow.userwin);
set (horaActual) = (sysdate);

if(newrow.fecharecogida < hoy or newrow.HORARECOGIDA < horaActual) then
SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'Fecha o hora de recogida menor que la fecha actual.';
end if;
if(newrow.horaRecogida < horaUsuario) then
SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'Verifica si lo datos son correctos y si el coche esta libre o si pretendes conducir dos coches a la vez.';
end if;
end;

In the table  conducen i have this content;

(bcastrof, 9674-GZF, 2017-11-24, 2017-11-24 19:03:00.000000, 2017-11-24 22:03:00.000000)

but if intented update this row, using this sentence;

update conducen
set HORARECOGIDA='2017-11-24 20:03:00.000000', HORAENTREGA='2017-11-24 22:03:00.000000'
WHERE FECHARECOGIDA='2017-11-24'
AND USERWIN = 'bcastrof'
and matricula = '9674-GZF'
and HORARECOGIDA = '2017-11-24 19:03:00.000000';

It doesn't work because it skips the exception 45002 the trigger. Please help.

Body:
solution the problem:

CREATE TRIGGER controlHoras1 AFTER
UPDATE ON conducen
REFERENCING NEW AS newrow OLD AS oldrow for each row
BEGIN Atomic
declare entrega timestamp;
declare hoy date;
declare horaUsuario timestamp;
declare horaActual timestamp;

set (entrega)= (select max(horaentrega) from conducen where matricula = newrow.matricula and FECHARECOGIDA = newrow.fecharecogida and horaentrega!=newrow.horaentrega);
set (hoy)= (today);
set (horaUsuario)=(select max(horaentrega) from conducen where FECHARECOGIDA = newrow.fecharecogida and userwin =newrow.userwin and horaentrega!=newrow.horaentrega and horarecogida<newrow.horarecogida);
set (horaActual) = (sysdate);
if(newrow.horaRecogida < entrega) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'El coche esta ocupado a la hora que lo pretendes recoger, elige otra hora u otro coche.';
end if;
if(newrow.fecharecogida<hoy or newrow.HORARECOGIDA<horaActual) then
SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'Fecha o hora de recogida menor que la fecha actual.';
end if;
if(newrow.horaRecogida<horaUsuario) then
SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'No puedes conducir dos coches a la vez.';
end if;
end;


问:
Java Split file lines into two lists
I'm currently writing an app that takes the data from the file. I need to sort the data in different ways. The problem is that the file is in format:

```<code>NAME1(tab)A(tab)B
NAME2(tab)C(tab)D
</code>```

I want to split data into two ArrayLists, one will gather NAME1, NAME2 etc, so the first element of line, the second list will gather the rest.

Here's my code:

```<code>Scanner scan = new Scanner(new File(fname));

while(scan.hasNext()){

}
scan.close();

System.out.println("Lang: ");
for(String item : lang)
    System.out.print(item + " ");

} catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

I tried to play with scanner methods, but there are no results and I have no idea what to do.

答: I would just use Scanner.nextLine(), then String.split("\t") and then append the line's parts to the respective lists.</p>

Title: Java Split file lines into two lists

Body:
I'm currently writing an app that takes the data from the file. I need to sort the data in different ways. The problem is that the file is in format:

NAME1(tab)A(tab)B
NAME2(tab)C(tab)D

I want to split data into two ArrayLists, one will gather NAME1, NAME2 etc, so the first element of line, the second list will gather the rest.

Here's my code:

Scanner scan = new Scanner(new File(fname));

while(scan.hasNext()){

}
scan.close();

System.out.println("Lang: ");
for(String item : lang)
    System.out.print(item + " ");

} catch (FileNotFoundException e) {
    e.printStackTrace();
}

I tried to play with scanner methods, but there are no results and I have no idea what to do.


问:
Making Google Visualization API to return the rendered visualization from https://charts.googleapis.com/* instead of http://charts.apis.google.com/*
The issue I am trying to solve is serving line charts prepared by Google visualization API on secure websites. I have read a couple of forums & blog posts but haven't come up with a workable solution.

One solution mentioned here is to get the image through server-side code, save it locally & then serve it. But the problem for me is how to generate the image URLs on the fly? I currently use visualization API to just feed my data to "google.visualization.ImageSparkLine" constructor & it does the rest.

Anyways after looking at the response generated by this method I get that an image is returned with a url pattern http://chart.apis.google.com/chart, which is the main cause of the problem on sites served via SSL. These causes warning to show up in FF, IE, Chrome.

Now I figured that if I just replaced the "http://chart.apis.google.com" WITH "https://chart.googleapis.com" everything works fine.

So any help for either 1. converting the image URL before it is fetched by the browser or 2. Getting secure response to begin with; will be great.

答:
I finally got this resolved by constructing the Chart Images URLs.

Now before making a call to google visualization API for generating the visualization, the JavaScript code checks if the location.protocol has "https" or not. If it does have https than it does,

It encodes the raw values string using "extended encode" standard. (see http://code.google.com/apis/chart/docs/data_formats.html)

Then it merges different parameters to construct a https://chart.googleapis.com/* URL (see http://code.google.com/apis/chart/docs/making_charts.html#multichart & http://code.google.com/apis/chart/docs/chart_params.html#gcharts_cht)

Dynamically generates the image using that URL & then attaches to the parent container.

Tested on FF3.6, Chrome, IE8 (w & w/o compatibility mode) without generating security warning messages or popups.


问:
Rewrite shell script without whitespace
Is it possible to write a shell script like that without using spaces, tabs or newlines:

```<code>/path/to/foo; test $? -ne 6
</code>```

The script runs another program and fails iff its return code is 6.

Background

I use this together within pam_exec.so and another program that controls access to a system. It does not relate to security, and I want to ensure access to the system if something about that other script fails (other than rc 6). The other program is a bit brittle, may break for various reasons, or simply be unavailable due to a messed up installation. I currently use a wrapper script, but that again needs to be deployed and i need to ensure that deployment of that script is consistent with the pam configuration. I would prefer a self-contained portable solution within the pam configuration.

Unfortunately 1) pam_exec.so doesn't care for the return code of the program it calls, and 2) the pam.d config parser does not care for quotes, it just splits arguments by " \n\t", so I cannot use

```<code>... pam_exec.so /bin/bash -c "/bath/to/foo; test$? -ne 6"
</code>```

I am curious if there is a way to reformulate that such that it does not need spaces and can be used here.

答:
Rather than dealing with whitespace I would create a wrapper script:

```<code>#!/bin/bash
# /usr/local/sbin/foo-wrapper
/bath/to/foo
test $? -ne 6
</code>```

pam config:

```<code>... pam_exec.so /usr/local/sbin/foo-wrapper
</code>```

Title: Rewrite shell script without whitespace

Body:
Is it possible to write a shell script like that without using spaces, tabs or newlines:

/path/to/foo; test $? -ne 6

The script runs another program and fails iff its return code is 6.

Background

I use this together within pam_exec.so and another program that controls access to a system. It does not relate to security, and I want to ensure access to the system if something about that other script fails (other than rc 6). The other program is a bit brittle, may break for various reasons, or simply be unavailable due to a messed up installation. I currently use a wrapper script, but that again needs to be deployed and i need to ensure that deployment of that script is consistent with the pam configuration. I would prefer a self-contained portable solution within the pam configuration.

Unfortunately 1) pam_exec.so doesn't care for the return code of the program it calls, and 2) the pam.d config parser does not care for quotes, it just splits arguments by " \n\t", so I cannot use

... pam_exec.so /bin/bash -c "/bath/to/foo; test$? -ne 6"

I am curious if there is a way to reformulate that such that it does not need spaces and can be used here.

Body:
Rather than dealing with whitespace I would create a wrapper script:

#!/bin/bash
# /usr/local/sbin/foo-wrapper
/bath/to/foo
test $? -ne 6

pam config:

... pam_exec.so /usr/local/sbin/foo-wrapper


问:
Why does AlertDialog.Builder limit the buttons / how does it work?
I am trying to make a simple two-button alert dialog without having to resort to making a separate class. AlertDialog.Builder class, which I am using to build the dialog, has three methods when it comes to adding buttons to the dialog.

```<code>setPositiveButton(...)
setNegativeButton(...)
setNeutralButton(...)
</code>```

Why does the Dialog hardcode this 3-button limit? Also, why do buttons need to be set as positive, negative, or neutral? What effect does a negative button press have compared to a positive or neutral button press?

I'm clearly missing something important, but it seems like this is a bad way to handle adding buttons? Because what if I want two (or more buttons) which shouldn't really be considered as positive or negative? The dialog doesn't allow adding more than one neutral button.

答:
There's a limit of three buttons primarily due to the limited width of a phone's screen in portrait mode. Imagine that all buttons are laid out in a row, as is typical for an AlertDialog. Beyond three buttons and you start to run out of width, text becomes truncated and the user is more at risk of inadvertently pressing the wrong button. If you require more then 3 buttons you'll either need a custom dialog with more buttons, or to rethink how exactly you want to handle the user's input while keeping in mind the restrictions of the user's potential screen size.

Likewise, the reason for three limited options of positive, neutral and negative are to provide UX consistency across the operating system. Consider an alert dialog from Android 1.5:

With that of Android 4.0 and 5.0:

Note how the order of the Positive and Negative buttons have been reversed. This was a deliberate design decision introduced as of the "Holo" UI in Android 3.0. By assigning a "Positive" and "Negative" button, the positions of these buttons can be changed in keeping with the UX of the user's OS version without the need for code changes within the app.

Further reading:

Why ‘Ok’ Buttons in Dialog Boxes Work Best on the Right

forms - OK/Cancel on left/right?

OK-Cancel or Cancel-OK? The trouble with buttons

Body:
I am trying to make a simple two-button alert dialog without having to resort to making a separate class. AlertDialog.Builder class, which I am using to build the dialog, has three methods when it comes to adding buttons to the dialog.

setPositiveButton(...)
setNegativeButton(...)
setNeutralButton(...)

Why does the Dialog hardcode this 3-button limit? Also, why do buttons need to be set as positive, negative, or neutral? What effect does a negative button press have compared to a positive or neutral button press?

I'm clearly missing something important, but it seems like this is a bad way to handle adding buttons? Because what if I want two (or more buttons) which shouldn't really be considered as positive or negative? The dialog doesn't allow adding more than one neutral button.


问:
The extern alias 'xxx' was not specified in a /reference option
I have two assemblies that unfortunately define the same type in the same namespace.  I'm trying to use a an extern alias to work around the problem.  In the Visual Studio IDE I have set the "Aliases" property of the reference to my alias.  This is supposed to change the C# compiler command line to be something like this:

```<code>/reference:MyAlias=MyAssembly.dll
</code>```

But it doesn't actually do that.  The Visual Studio IDE seems to just ignore the Aliases property setting on the reference.  So when I go and add the line extern alias MyAlias; at the top of my C# code file I get the error that the alias was not specified in a /reference option to the compiler.  I can't figure out what I am doing wrong.  Any ideas?

答: I had the same problem, and I could solve it only when I changed the target version to 4.6.1. The versions 4, 4.5, 4.5.1, or 4.6 did not help.</p>

Body:
I have two assemblies that unfortunately define the same type in the same namespace.  I'm trying to use a an extern alias to work around the problem.  In the Visual Studio IDE I have set the "Aliases" property of the reference to my alias.  This is supposed to change the C# compiler command line to be something like this:

/reference:MyAlias=MyAssembly.dll

But it doesn't actually do that.  The Visual Studio IDE seems to just ignore the Aliases property setting on the reference.  So when I go and add the line extern alias MyAlias; at the top of my C# code file I get the error that the alias was not specified in a /reference option to the compiler.  I can't figure out what I am doing wrong.  Any ideas?


问:
Anchor item to bottom of Ionic menu
I have the below html to build a side-menu in Ionic. I'm aiming to anchor the last item in the menu, 'login' to the bottom of the menu, away from the other items. Is there a simple way to do this in Ionic?</p>

```<code><ion-side-menus enable-menu-with-back-views="false">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-positive">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="left">
    <ion-header-bar class="bar-positive">
    </ion-header-bar>
    <ion-content>
      <ion-list>
        <ion-item nav-clear menu-close href="#/app/people">
          <i class="icon ion-ios7-people"></i>
          People
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/places">
          <i class="icon ion-ios7-location"></i>
          Places
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/perks">
          <i class="icon ion-ios7-star"></i>
          Perks
        </ion-item>
        <ion-item nav-clear menu-close ng-click="login()">
          Login
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>
</code>```

答:
I did it like this. You don't need to add some CSS.</p>

```<code><ion-side-menu side="left">
    <header class="bar bar-header bar-stable">
        <h1 class="title">Title</h1>
    </header>
    <ion-content class="has-header has-footer">
        <ion-list>
            <ion-item nav-clear menu-close ui-sref="home">Home</ion-item>
        </ion-list>
    </ion-content>

    <ion-footer-bar class="bar-stable" ng-click="logout()">
       <div class="title"><i class="icon ion-power"></i> Logout</div>
    </ion-footer-bar>
</ion-side-menu>
</code>```

Title: Anchor item to bottom of Ionic menu

Body:
I have the below html to build a side-menu in Ionic. I'm aiming to anchor the last item in the menu, 'login' to the bottom of the menu, away from the other items. Is there a simple way to do this in Ionic?

<ion-side-menus enable-menu-with-back-views="false">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-positive">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="left">
    <ion-header-bar class="bar-positive">
    </ion-header-bar>
    <ion-content>
      <ion-list>
        <ion-item nav-clear menu-close href="#/app/people">

          People
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/places">

          Places
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/perks">

          Perks
        </ion-item>
        <ion-item nav-clear menu-close ng-click="login()">
          Login
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>

Body:
I did it like this. You don't need to add some CSS.

<ion-side-menu side="left">
    <header class="bar bar-header bar-stable">
        <h1 class="title">Title</h1>
    </header>
    <ion-content class="has-header has-footer">
        <ion-list>
            <ion-item nav-clear menu-close ui-sref="home">Home</ion-item>
        </ion-list>
    </ion-content>

    <ion-footer-bar class="bar-stable" ng-click="logout()">
       <div class="title"><i class="icon ion-power"></i> Logout</div>
    </ion-footer-bar>
</ion-side-menu>


问:
Get GitHub git branch for AWS CodeBuild
I'm setup AWS CodeBuild to build automatically from GitHub. Other CI services provide an environment variable for the branch, but I can't find one for AWS CodeBuild. There is a CODEBUILD_SOURCE_VERSION that is set to either pr/7 where 7 is the pull request number or the git commit sha.

Given the commit sha, I've been trying to get the branch name, but no luck so far.

git branch --contains <commitsha> doesn't work because it is a detached head. How do I get the git branch for the commit from CodeBuild?

答:
You can run:

```<code>git branch -a --contains <sha>
</code>```

-a means all branches.  If your sha is in no branch, which could happen in some cases, you won't see anything.

Title: Get GitHub git branch for AWS CodeBuild

Body:
You can run:

git branch -a --contains <sha>

-a means all branches.  If your sha is in no branch, which could happen in some cases, you won't see anything.


问:
./bin/istioctl context-create segmentation fault
I'm following this guide of installing istio https://istio.io/docs/setup/consul/quick-start.html

At step 7, I noticed that pilot terminates after I run  docker-compose -f install/consul/istio.yaml up -d

So I ran istioctl context-create.
And I got a seg fault:

./bin/istioctl context-create
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x30 pc=0x1debb79]

goroutine 1 [running]:
main.getDefaultNamespace(0xc42021c620, 0x20, 0x0, 0x0)
    /home/sebastienvas/go/src/istio.io/pilot/cmd/istioctl/main.go:700 +0x99
main.glob..func4(0x2892960, 0x28be4b8, 0x0, 0x0)
    /home/sebastienvas/go/src/istio.io/pilot/cmd/istioctl/main.go:86 +0x39
istio.io/pilot/vendor/github.com/spf13/cobra.(*Command).execute(0x2892960, 0x28be4b8, 0x0, 0x0, 0x2892960, 0x28be4b8)
    /home/sebastienvas/go/src/istio.io/pilot/vendor/github.com/spf13/cobra/command.go:637 +0x549
istio.io/pilot/vendor/github.com/spf13/cobra.(*Command).ExecuteC(0x2891760, 0x1df15f3, 0x0, 0x0)
    /home/sebastienvas/go/src/istio.io/pilot/vendor/github.com/spf13/cobra/command.go:729 +0x339
istio.io/pilot/vendor/github.com/spf13/cobra.(*Command).Execute(0x2891760, 0x0, 0x154)
    /home/sebastienvas/go/src/istio.io/pilot/vendor/github.com/spf13/cobra/command.go:688 +0x2b
main.main()
    /home/sebastienvas/go/src/istio.io/pilot/cmd/istioctl/main.go:531 +0xc0

I upgraded to the latest go version:
go version
go version go1.9.2 darwin/amd64
And still the same issue

I would really appreciate if anyone could help me with this.

答: It sounds like there could be a few problems in your setup, but it's going to take some follow-up questions to narrow it down.  This would be better suited as a question in the istio-users google group https://groups.google.com/forum/#!forum/istio-users where the problem can get diagnosed through some back-and-forth.</p>


问:
replace comma followed by a character by semicolon while keeping the same character
Provided a vector like this: test = "Education & research,Non-Profit (NGOs, foundations, associations...),Government (local, regional, national),Individuals,Other" I would like to replace all commas that are followed by alhpa character (not space) while preserving original alpha character, so I can later split multiple values within a cell by splitting by semicolon.

So far, I have used the following code:

```<code>> gsub(",\\S", ";", test)
[1] "Education & research;on-Profit (NGOs, foundations, associations...);overnment (local, regional, national);ndividuals;ther"
</code>```

As you can see, I have replaced all commas (that's fine!) but I also deleted the first letter of the word following them! (that's wrong!). I get the same result if I type gsub(",[A-Z]", ";", test)

That's why I tried with

```<code>> gsub(",[A-Z]", ";[A-Z]", test)
[1] "Education & research;[A-Z]on-Profit (NGOs, foundations, associations...);[A-Z]overnment (local, regional, national);[A-Z]ndividuals;[A-Z]ther"
</code>```

But the replacement doesn't seem to accept [A-Z] as replacement token for the original character.

Is there any way to achieve what I am looking for?

答:
Brief

You can use a positive lookahead. Positive lookaheads assert that the given subpattern can be matched at that position without consuming characters.

Regex replacements are fairly literal in how they replace. So, as you've seen, a replacement of ;[A-Z] is literally used. Another way to achieve what you want is to make the next character part of a capture group such that your regex becomes ,([A-Z]) and you use the replacement of ;$1 (here $1 is a reference to the most recently matched text inside capture group 1). Although it's possible with groups, it's usually better to use assertions for things you don't actually want to replace (in this case the uppercase character) as my answer provides below.

Code

See regex in use here

```<code>,(?=[A-Z])
</code>```

For Unicode support you can use ,(?=\p{Lu}). \p{Lu} means any uppercase character in any script/language. This will match, for example, É whilst [A-Z] will not.

Replacement: ;

Usage

```<code>gsub(",(?=[A-Z])",";","Education & research,Non-Profit (NGOs, foundations, associations...),Government (local, regional, national),Individuals,Other", perl=TRUE)
</code>```

Note: This regex uses a positive lookahead and, as such, gsub requires perl=TRUE to be passed.

Results

Input

Education & research,Non-Profit (NGOs, foundations,
  associations...),Government (local, regional,
  national),Individuals,Other

Output

```<code>Education & research;Non-Profit (NGOs, foundations, associations...);Government (local, regional, national);Individuals;Other
</code>```

Explanation

, Match a literal comma

(?=[A-Z]) Positive lookahead ensuring what follows matches an uppercase ASCII letter

Body:
Provided a vector like this: test = "Education & research,Non-Profit (NGOs, foundations, associations...),Government (local, regional, national),Individuals,Other" I would like to replace all commas that are followed by alhpa character (not space) while preserving original alpha character, so I can later split multiple values within a cell by splitting by semicolon.

So far, I have used the following code:

> gsub(",\\S", ";", test)
[1] "Education & research;on-Profit (NGOs, foundations, associations...);overnment (local, regional, national);ndividuals;ther"

As you can see, I have replaced all commas (that's fine!) but I also deleted the first letter of the word following them! (that's wrong!). I get the same result if I type gsub(",[A-Z]", ";", test)

That's why I tried with

> gsub(",[A-Z]", ";[A-Z]", test)
[1] "Education & research;[A-Z]on-Profit (NGOs, foundations, associations...);[A-Z]overnment (local, regional, national);[A-Z]ndividuals;[A-Z]ther"

But the replacement doesn't seem to accept [A-Z] as replacement token for the original character.

Is there any way to achieve what I am looking for?

Body:
Brief

You can use a positive lookahead. Positive lookaheads assert that the given subpattern can be matched at that position without consuming characters.

Regex replacements are fairly literal in how they replace. So, as you've seen, a replacement of ;[A-Z] is literally used. Another way to achieve what you want is to make the next character part of a capture group such that your regex becomes ,([A-Z]) and you use the replacement of ;$1 (here $1 is a reference to the most recently matched text inside capture group 1). Although it's possible with groups, it's usually better to use assertions for things you don't actually want to replace (in this case the uppercase character) as my answer provides below.

Code

See regex in use here

,(?=[A-Z])

For Unicode support you can use ,(?=\p{Lu}). \p{Lu} means any uppercase character in any script/language. This will match, for example, É whilst [A-Z] will not.

Replacement: ;

Usage

gsub(",(?=[A-Z])",";","Education & research,Non-Profit (NGOs, foundations, associations...),Government (local, regional, national),Individuals,Other", perl=TRUE)

Note: This regex uses a positive lookahead and, as such, gsub requires perl=TRUE to be passed.

Results

Input

Education & research,Non-Profit (NGOs, foundations,
  associations...),Government (local, regional,
  national),Individuals,Other

Output

Education & research;Non-Profit (NGOs, foundations, associations...);Government (local, regional, national);Individuals;Other

Explanation

, Match a literal comma

(?=[A-Z]) Positive lookahead ensuring what follows matches an uppercase ASCII letter


问:
sample sequence of successive integer of an interval
I have a question about sampling: I would like to sample successive number in a vector without replacement. Is there a simple way to do so?
For example,

```<code>sample(c(1:100), 10, replace = F)
76 99 94 53 12 34  5 82 75 30
</code>```

gives me 10 number between 1 and 100. Now I would like to have 10 sequence of 3 successive integer without replacement: c(2,3,4), c(10,11,12), c(82,83,84)  etc.

The different sequences can't overlap, that is if c(2,3,4) is my first sampling, then none of the following one can have these numbers.

I would even look for the possibility of sampling 10 sequences of different sizes, the sizes given by a vector like

```<code>sizevec <- sample(c(1:4),10,replace = T)
</code>```

Thanks for the help

答:
A solution using tow while loop to take samples. After running the code, x is a list of desired output.

```<code># Set seed for reproduciblility
set.seed(123)

# Create a list to store values
x <- list()
# Create a vector to store values in x
y <- integer()

# Set the threshold to stop
threshold <- 4

# Set the condition
condition <- TRUE

while (length(x) < threshold){
  while (condition){
    # Sample a number between 1 to 98
    s <- sample(c(1:98), 1)
    # Create a sequence
    se <- s:(s + 2)
    # Check if the values in se is in y, save it to the condition
    condition <- any(se %in% y)
  }
  # Save se to the list
  x[[length(x) + 1]] <- se
  # Update y
  y <- unlist(x)
  # Reset the condition
  condition <- TRUE
}

# View the results
x
# [[1]]
# [1] 29 30 31
#
# [[2]]
# [1] 79 80 81
#
# [[3]]
# [1] 41 42 43
#
# [[4]]
# [1] 89 90 91
</code>```

Body:
I have a question about sampling: I would like to sample successive number in a vector without replacement. Is there a simple way to do so?
For example,

sample(c(1:100), 10, replace = F)
76 99 94 53 12 34  5 82 75 30

gives me 10 number between 1 and 100. Now I would like to have 10 sequence of 3 successive integer without replacement: c(2,3,4), c(10,11,12), c(82,83,84)  etc.

The different sequences can't overlap, that is if c(2,3,4) is my first sampling, then none of the following one can have these numbers.

I would even look for the possibility of sampling 10 sequences of different sizes, the sizes given by a vector like

sizevec <- sample(c(1:4),10,replace = T)

Thanks for the help

Body:
A solution using tow while loop to take samples. After running the code, x is a list of desired output.

# Set seed for reproduciblility
set.seed(123)

# Create a list to store values
x <- list()
# Create a vector to store values in x
y <- integer()

# Set the threshold to stop
threshold <- 4

# Set the condition
condition <- TRUE

while (length(x) < threshold){
  while (condition){
    # Sample a number between 1 to 98
    s <- sample(c(1:98), 1)
    # Create a sequence
    se <- s:(s + 2)
    # Check if the values in se is in y, save it to the condition
    condition <- any(se %in% y)
  }
  # Save se to the list
  x[[length(x) + 1]] <- se
  # Update y
  y <- unlist(x)
  # Reset the condition
  condition <- TRUE
}

# View the results
x
# [[1]]
# [1] 29 30 31
#
# [[2]]
# [1] 79 80 81
#
# [[3]]
# [1] 41 42 43
#
# [[4]]
# [1] 89 90 91


问:
PHP get_defined_vars() doesn't print superglobals inside function
I'm working through debugging some legacy code, and want to use a pre-built function that is essentially a wrapper for get_defined_vars().

Running this code directly in the calling file prints an array of variables as expected:

```<code>print_r(get_defined_vars());
</code>```

However, wrapping this in a simplified version of my function prints an empty array:

```<code>function debugAllVars() {
    print_r(get_defined_vars());
}
debugAllVars();
</code>```

Regardless of the scope, I would have expected "superglobal" variables such as $_POST to be present in the output.

Why is the output completely empty?

答:
get_defined_vars gets all variables defined in the scope that it's called in. Your debugAllVars function introduces a new scope, so get_defined_vars will at most give you all variables within debugAllVars. It cannot give you variables from the caller's scope.

Also see Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?.

Body:
I'm working through debugging some legacy code, and want to use a pre-built function that is essentially a wrapper for get_defined_vars().

Running this code directly in the calling file prints an array of variables as expected:

print_r(get_defined_vars());

However, wrapping this in a simplified version of my function prints an empty array:

function debugAllVars() {
    print_r(get_defined_vars());
}
debugAllVars();

Regardless of the scope, I would have expected "superglobal" variables such as $_POST to be present in the output.

Why is the output completely empty?


问:
C#/WPF How can I read "Bindings" from a TextBox (Data gets from a SQL-Table)?
I have a question. I search the problem but I didn't find a solution.
Hope someone can help me.

I have a "DataGrid" and in this is a "DataGrid.RowDetailsTemplate". There are "Textbox" they show data from a list binding. And I want to change this data when I click on a button, but I cant read the Bindings so I cant change them. Hope someone know what I mean.

WPF code:

```<code>    <dxn:NavBarGroup Name="_navBarOverlay" Header="Benutzerübersicht">
            <Grid Style="{StaticResource GridStyleAccordion}">
                <DataGrid x:Name="userDataGrid" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserResizeRows="True" RowDetailsVisibilityMode="VisibleWhenSelected" IsReadOnly="True" AlternatingRowBackground="{DynamicResource WihaGrauB}" ColumnWidth="auto" ColumnHeaderHeight="30"   AutoGenerateColumns="False" Grid.Row="0"   Width="auto" Height="auto">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Benutzer"  Binding="{Binding Name}" MinWidth="150" Width="2*" />
                        <DataGridTextColumn Header="OperatorID" Binding="{Binding OperatorID}" MinWidth="200" Width="3*"/>
                        <DataGridCheckBoxColumn Header="Aktiv" Binding="{Binding Aktiv}" MinWidth="50" Width="*"/>
                    </DataGrid.Columns>
                    <DataGrid.RowDetailsTemplate>
                        <DataTemplate>
                            <DockPanel>
                                <Image DockPanel.Dock="Left" Source="{Binding ImageUrl}" Height="30" Width="25" Margin="10,0,0,0"/>
                                <Grid Margin="10">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>
                                    <TextBlock Text="Name: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="1" Margin="2,2,2,2"/>
                                    <TextBox  x:Name="nameText" Text="{Binding  Path=Name, Mode=TwoWay}" Grid.Column="1" Width="150" TextAlignment="Center" HorizontalAlignment="Left" Grid.Row="1"  Margin="2,2,2,2"  />
                                    <TextBlock Text="OperatorID: " FontFamily="{DynamicResource WihaFontFamaly}" Grid.Row="2" FontWeight="Bold" Margin="2,2,2,2"/>
                                    <TextBox x:Name="operatorText" IsReadOnly="True" Text="{Binding OperatorID}" Width="150" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="2" TextAlignment="Center"  Margin="2,2,2,2" />
                                    <TextBlock Text="DeviceID: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="3" Margin="2,2,2,2"/>
                                    <TextBox Text="{Binding DeviceID}" Grid.Column="3" Width="150" HorizontalAlignment="Left" Grid.Row="3" TextAlignment="Center"  Margin="2,2,2,2"/>
                                    <TextBlock Text="Passwort: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="4" Margin="2,2,2,2"/>
                                    <TextBox Text="{Binding Passwort}" Grid.Column="4" Width="150" HorizontalAlignment="Left" Grid.Row="4" TextAlignment="Center"   Margin="2,2,2,2"/>
                                    <TextBlock Text="Aktiv:" FontWeight="Bold" FontFamily="{DynamicResource WihaFontFamaly}" Grid.Row="5" Margin="2,2,2,2"/>
                                    <CheckBox Grid.Column="5" Grid.Row="5" IsChecked="{Binding Aktiv}" Margin="2,2,2,2" />
                                    <Button Style="{StaticResource ButtonStyleWIHA}" Click="saveUserPanel_Click" Name="saveUserPanel" Content="Save" Grid.Row="6" />
                                </Grid>
                            </DockPanel>
                        </DataTemplate>
                    </DataGrid.RowDetailsTemplate>
                </DataGrid>
            </Grid>
        </dxn:NavBarGroup>
</code>```

C# code where the data comes:

```<code>     public void ShowAllOperator()
    {
        try
        {
            List<User> users = new List<User>();
            // string sql = "SELECT * FROM wiha_Operators";
            SqlConnection conn = new SqlConnection("Server=127.0.0.1;Database=Wiha;Trusted_Connection=true");
            conn.Open();
            // SqlCommand cmd = new SqlCommand(sql, conn);
            SqlCommand cmd = new SqlCommand("dbo.wiha_operators_SelectAll", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {

                while (rdr.Read())
                {
                    users.Add(new User() { Name = rdr.GetValue(2).ToString(), OperatorID = rdr.GetValue(0).ToString(), Aktiv = rdr.GetValue(4).Equals(true), ImageUrl = "C:/Users/Jason/Desktop/DeleteIcon.png", DeviceID = rdr.GetValue(1).ToString(), Passwort = rdr.GetValue(3).ToString() });
                }

            }
            userDataGrid.ItemsSource = users;
        }
        catch (Exception)
        {

            throw;
        }
    }
</code>```

Here I want to change them:

```<code>     private void saveUserPanel_Click(object sender, RoutedEventArgs e)
    {

    }
</code>```

My User list:

```<code>     public class User
    {
        public string Name { get; set; }
        public string OperatorID { get; set; }
        public bool Aktiv { get; set; }
        public string ImageUrl { get; set; }
        public string DeviceID { get; set; }
        public string Passwort { get; set; }

    }
</code>```

Hope you know what I want from you. You miss or didn't understand something? Ask me :)

EDIT

My new User class:

```<code>    public class User : INotifyPropertyChanged
    {
        private string _name = string.Empty;
        public event PropertyChangedEventHandler PropertyChanged;
        public string Name
        {
            get { return this._name; }
            set
            {
                if (value != this._name)
                {
                    this._name = value;
                    NotifyPropertyChanged();
                }
            }
        }
        public string OperatorID { get; set; }
        public bool Aktiv { get; set; }
        public string ImageUrl { get; set; }
        public string DeviceID { get; set; }
        public string Passwort { get; set; }

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
</code>```

I see only the old value.

答:
As @Ash suggests, you could use the DataContext of the Button, which is a User object, to access the Item, since it is part of the DataTemplate

```<code>private void saveUserPanel_Click(object sender, RoutedEventArgs e)
{
  var user = (sender as Button).DataContext as User;
  if(user != null)
  {
    user.Name = "NewName";
    var active = user.Aktiv;
    // ...
  }
}
</code>```

Notice that updating the user object in the code behind will not update your UI since Userdoes not implement INotifyPropertyChanged.

Body:
I have a question. I search the problem but I didn't find a solution.
Hope someone can help me.

I have a "DataGrid" and in this is a "DataGrid.RowDetailsTemplate". There are "Textbox" they show data from a list binding. And I want to change this data when I click on a button, but I cant read the Bindings so I cant change them. Hope someone know what I mean.

WPF code:

    <dxn:NavBarGroup Name="_navBarOverlay" Header="Benutzerübersicht">
            <Grid Style="{StaticResource GridStyleAccordion}">
                <DataGrid x:Name="userDataGrid" CanUserReorderColumns="True" CanUserResizeColumns="True" CanUserResizeRows="True" RowDetailsVisibilityMode="VisibleWhenSelected" IsReadOnly="True" AlternatingRowBackground="{DynamicResource WihaGrauB}" ColumnWidth="auto" ColumnHeaderHeight="30"   AutoGenerateColumns="False" Grid.Row="0"   Width="auto" Height="auto">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Benutzer"  Binding="{Binding Name}" MinWidth="150" Width="2*" />
                        <DataGridTextColumn Header="OperatorID" Binding="{Binding OperatorID}" MinWidth="200" Width="3*"/>
                        <DataGridCheckBoxColumn Header="Aktiv" Binding="{Binding Aktiv}" MinWidth="50" Width="*"/>
                    </DataGrid.Columns>
                    <DataGrid.RowDetailsTemplate>
                        <DataTemplate>
                            <DockPanel>
                                <Image DockPanel.Dock="Left" Source="{Binding ImageUrl}" Height="30" Width="25" Margin="10,0,0,0"/>
                                <Grid Margin="10">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>
                                    <TextBlock Text="Name: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="1" Margin="2,2,2,2"/>
                                    <TextBox  x:Name="nameText" Text="{Binding  Path=Name, Mode=TwoWay}" Grid.Column="1" Width="150" TextAlignment="Center" HorizontalAlignment="Left" Grid.Row="1"  Margin="2,2,2,2"  />
                                    <TextBlock Text="OperatorID: " FontFamily="{DynamicResource WihaFontFamaly}" Grid.Row="2" FontWeight="Bold" Margin="2,2,2,2"/>
                                    <TextBox x:Name="operatorText" IsReadOnly="True" Text="{Binding OperatorID}" Width="150" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="2" TextAlignment="Center"  Margin="2,2,2,2" />
                                    <TextBlock Text="DeviceID: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="3" Margin="2,2,2,2"/>
                                    <TextBox Text="{Binding DeviceID}" Grid.Column="3" Width="150" HorizontalAlignment="Left" Grid.Row="3" TextAlignment="Center"  Margin="2,2,2,2"/>
                                    <TextBlock Text="Passwort: " FontFamily="{DynamicResource WihaFontFamaly}" FontWeight="Bold" Grid.Row="4" Margin="2,2,2,2"/>
                                    <TextBox Text="{Binding Passwort}" Grid.Column="4" Width="150" HorizontalAlignment="Left" Grid.Row="4" TextAlignment="Center"   Margin="2,2,2,2"/>
                                    <TextBlock Text="Aktiv:" FontWeight="Bold" FontFamily="{DynamicResource WihaFontFamaly}" Grid.Row="5" Margin="2,2,2,2"/>
                                    <CheckBox Grid.Column="5" Grid.Row="5" IsChecked="{Binding Aktiv}" Margin="2,2,2,2" />
                                    <Button Style="{StaticResource ButtonStyleWIHA}" Click="saveUserPanel_Click" Name="saveUserPanel" Content="Save" Grid.Row="6" />
                                </Grid>
                            </DockPanel>
                        </DataTemplate>
                    </DataGrid.RowDetailsTemplate>
                </DataGrid>
            </Grid>
        </dxn:NavBarGroup>

C# code where the data comes:

     public void ShowAllOperator()
    {
        try
        {
            List<User> users = new List<User>();
            // string sql = "SELECT * FROM wiha_Operators";
            SqlConnection conn = new SqlConnection("Server=127.0.0.1;Database=Wiha;Trusted_Connection=true");
            conn.Open();
            // SqlCommand cmd = new SqlCommand(sql, conn);
            SqlCommand cmd = new SqlCommand("dbo.wiha_operators_SelectAll", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {

                while (rdr.Read())
                {
                    users.Add(new User() { Name = rdr.GetValue(2).ToString(), OperatorID = rdr.GetValue(0).ToString(), Aktiv = rdr.GetValue(4).Equals(true), ImageUrl = "C:/Users/Jason/Desktop/DeleteIcon.png", DeviceID = rdr.GetValue(1).ToString(), Passwort = rdr.GetValue(3).ToString() });
                }

            }
            userDataGrid.ItemsSource = users;
        }
        catch (Exception)
        {

            throw;
        }
    }

Here I want to change them:

     private void saveUserPanel_Click(object sender, RoutedEventArgs e)
    {

    }

My User list:

     public class User
    {
        public string Name { get; set; }
        public string OperatorID { get; set; }
        public bool Aktiv { get; set; }
        public string ImageUrl { get; set; }
        public string DeviceID { get; set; }
        public string Passwort { get; set; }

    }

Hope you know what I want from you. You miss or didn't understand something? Ask me :)

EDIT

My new User class:

    public class User : INotifyPropertyChanged
    {
        private string _name = string.Empty;
        public event PropertyChangedEventHandler PropertyChanged;
        public string Name
        {
            get { return this._name; }
            set
            {
                if (value != this._name)
                {
                    this._name = value;
                    NotifyPropertyChanged();
                }
            }
        }
        public string OperatorID { get; set; }
        public bool Aktiv { get; set; }
        public string ImageUrl { get; set; }
        public string DeviceID { get; set; }
        public string Passwort { get; set; }

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

I see only the old value.

Body:
As @Ash suggests, you could use the DataContext of the Button, which is a User object, to access the Item, since it is part of the DataTemplate

private void saveUserPanel_Click(object sender, RoutedEventArgs e)
{
  var user = (sender as Button).DataContext as User;
  if(user != null)
  {
    user.Name = "NewName";
    var active = user.Aktiv;
    // ...
  }
}

Notice that updating the user object in the code behind will not update your UI since Userdoes not implement INotifyPropertyChanged.


问:
Why won't my nested function call after the conditional?
Trying to call 'dialogue_b1_a()' using the input function within a function named dialogue_b1(). When I call dialogue_b1() normally, the prompt works, but after I type begin, it simply says that 'process executed with exit code 0', instead of calling the function I put if continue_b1 == begin. What am I doing wrong? Thanks.    </p>

```<code>def dialogue_b1():
    begin = 0
    print("You identify as a male.")
    print("...")
    continue_b1 = input('Type "begin" to continue.')
    if continue_b1 == begin:
        dialogue_b1_a()
    return
</code>```

答:
So you only need to change begin into string:

```<code>def dialogue_b1():
    begin = 0
    print("You identify as a male.")
    print("...")
    continue_b1 = input('Type "begin" to continue.')
    if continue_b1 == 'begin':
        dialogue_b1_a()
    return
</code>```

Body:
Trying to call 'dialogue_b1_a()' using the input function within a function named dialogue_b1(). When I call dialogue_b1() normally, the prompt works, but after I type begin, it simply says that 'process executed with exit code 0', instead of calling the function I put if continue_b1 == begin. What am I doing wrong? Thanks.

def dialogue_b1():
    begin = 0
    print("You identify as a male.")
    print("...")
    continue_b1 = input('Type "begin" to continue.')
    if continue_b1 == begin:
        dialogue_b1_a()
    return

Body:
So you only need to change begin into string:

def dialogue_b1():
    begin = 0
    print("You identify as a male.")
    print("...")
    continue_b1 = input('Type "begin" to continue.')
    if continue_b1 == 'begin':
        dialogue_b1_a()
    return


问:
Issue while redirecting bad row - SSIS
I'm Importing data from a flat file source (text comma delimited) into a table, but the data contains comma in certain fields causing the package to fail. I have added a file destination to log the bad rows to revisit later, but the bad rows don't get logged and the only part of the data get loaded in the table. I'm attaching below the image of the package and the incomplete execution screen. It looks like a simple thing to accomplish but I just can't figure out what causing the problem. Can anyone help?

Thanks

UPDATE

There is no error message in Progress actually. It looks like a successful run log. But it's not. The load is incomplete.

答:
In the Flat File Connection Manager, on the first page, you can pick a Text Qualifier, which is typically double quotes. Most programs that read CSV files know how to interpret strings encased in double quotes.

So now a single column value of

```<code>123 My Street, Any Town, USA
</code>```

become:

```<code>"123 My Street, Any Town, USA"
</code>```

Pretty standard stuff for CSV files

Title: Issue while redirecting bad row - SSIS

Body:
In the Flat File Connection Manager, on the first page, you can pick a Text Qualifier, which is typically double quotes. Most programs that read CSV files know how to interpret strings encased in double quotes.

So now a single column value of

123 My Street, Any Town, USA

become:

"123 My Street, Any Town, USA"

Pretty standard stuff for CSV files