问:
Format Dynamically added textBox in Excel
I am adding TextBoxes dynamically in a userform and want to make them a date format to ensure correct date entry.  I am unable to find any examples.

Here is my code for the userform activation:

```<code>Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)

fltDays = TextBox3.Value If TextBox3.Value = 0 Then Exit Sub

For i = 1 To fltDays

n = i - 1

Dim TextBox As Control

Set theLbl = FloatDayFrm.Controls.add("Forms.Label.1", "lbl_" & i, True)
    With theLbl
      .Caption = "Day " & i
      .Left = 20
      .Width = 60
      .Top = n * 24 + 100
      .Font.Size = 10
    End With

Set TextBox = FloatDayFrm.Controls.add("Forms.TextBox.1", "TextBox_" & n, True)
    With TextBox
        .Top = 100 + (n * 24)
        .Left = 90
        .Height = 18
        .Width = 50
        .Name = "txtBox" & i
        .Font.Size = 10
        .TabIndex = n + 4
        .TabStop = True
    End With Next i

FloatDayFrm.Height = 150 + fltDays * 24 With btnOK .Top = 102 + fltDays * 24 .TabStop = True .TabIndex = n + 5 End With

With btnCancel .Top = 102 + fltDays * 24 '.TabStop = True .TabIndex = n + 6 End With

End Sub
</code>```

This is my code for the Command button:

```<code>Private Sub btnOK_Click()

n = TextBox3.Value

For j = 1 To n

Set varFloatDay = FloatDayFrm.Controls("txtBox" & j)

Select Case varFloatDay
    Case ""
        MsgBox "Day " & j & " can't be blank", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is > TextBox2.Value
         MsgBox "Date is after end date", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is < TextBox1.Value
         MsgBox "Date is BEFORE end date", vbOKOnly, "Incorrect Value"
        Exit Sub
End Select

Next j

End Sub
</code>```

Any help would be appreciated.

答: Any input in a text box is a text string. If you want it to be a date you can use IsDate(TextBox1.Value) to determine if VBA is able to convert the string to a date (which is a number of Double type). VBA will not execute this test 100% correctly, however. For example, it may not recognised 3/2/17 as a date if your regional settings have the date separator as a period. It may convert 3.2.17 to March 2 if your regional settings are mm.dd.yy. While working on your own PC you may be able to control the regional settings. But if your project will be released into the wild it is better to use a calendar control to get a correct date.</p>

Body:
I am adding TextBoxes dynamically in a userform and want to make them a date format to ensure correct date entry.  I am unable to find any examples.

Here is my code for the userform activation:

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)

fltDays = TextBox3.Value If TextBox3.Value = 0 Then Exit Sub

For i = 1 To fltDays

n = i - 1

Dim TextBox As Control

Set theLbl = FloatDayFrm.Controls.add("Forms.Label.1", "lbl_" & i, True)
    With theLbl
      .Caption = "Day " & i
      .Left = 20
      .Width = 60
      .Top = n * 24 + 100
      .Font.Size = 10
    End With

Set TextBox = FloatDayFrm.Controls.add("Forms.TextBox.1", "TextBox_" & n, True)
    With TextBox
        .Top = 100 + (n * 24)
        .Left = 90
        .Height = 18
        .Width = 50
        .Name = "txtBox" & i
        .Font.Size = 10
        .TabIndex = n + 4
        .TabStop = True
    End With Next i

FloatDayFrm.Height = 150 + fltDays * 24 With btnOK .Top = 102 + fltDays * 24 .TabStop = True .TabIndex = n + 5 End With

With btnCancel .Top = 102 + fltDays * 24 '.TabStop = True .TabIndex = n + 6 End With

End Sub

This is my code for the Command button:

Private Sub btnOK_Click()

n = TextBox3.Value

For j = 1 To n

Set varFloatDay = FloatDayFrm.Controls("txtBox" & j)

Select Case varFloatDay
    Case ""
        MsgBox "Day " & j & " can't be blank", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is > TextBox2.Value
         MsgBox "Date is after end date", vbOKOnly, "Incorrect Value"
        Exit Sub
    Case Is < TextBox1.Value
         MsgBox "Date is BEFORE end date", vbOKOnly, "Incorrect Value"
        Exit Sub
End Select

Next j

End Sub

Any help would be appreciated.


来源: stackexchange

问:
Platform independent tool to copy text to clipboard
I am trying to write a function that copies a string parameter to the clipboard. I intend to use this in a Python script that I've been working on. This is what I have so far (found most this snippet on another stack overflow post):

```<code>from tkinter import Tk

    def copy_to_clipboard(text):
        text = str(text)
        r = Tk()
        r.withdraw()
        r.clipboard_clear()
        r.clipboard_append(text)
        r.destroy()
</code>```

My problem is that when the script stops, the copied text is no longer on the clipboard.

Is there any possible alternative or fix to this?

Is there a good platform independent solution to my problem? Or will I have to check for what OS the user is on and proceed from there?

答:
Yes, there is one for you :)

Use pyperclip.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a function that copies a string parameter to the clipboard. I intend to use this in a Python script that I've been working on. This is what I have so far (found most this snippet on another stack overflow post):

from tkinter import Tk

    def copy_to_clipboard(text):
        text = str(text)
        r = Tk()
        r.withdraw()
        r.clipboard_clear()
        r.clipboard_append(text)
        r.destroy()

My problem is that when the script stops, the copied text is no longer on the clipboard.

Is there any possible alternative or fix to this?

Is there a good platform independent solution to my problem? Or will I have to check for what OS the user is on and proceed from there?

ContentLicense: CC BY-SA 2.5


问:
Pandas - group by id and drop duplicates
I have the following data.

```<code>userid itemid timestamp
  1       1      50
  1       2      50
  1       3      50
  1       4      60
  2       1      40
  2       2      50
</code>```

I want to drop users who have duplicate timestamps.
In my example above, I want to drop userid=1  because he has viewed multiple items at timestamp=50. userid=2 should not be dropped since he has viewed items in different timestamps.

Can anyone help me?

答:
option 1

Use duplicated

```<code>dropid = df.loc[
    df.duplicated(subset=['userid', 'timestamp']),
    'userid'
].unique()
df[~df.userid.isin(dropid)]
</code>```

option 2

Use groupby and filter

```<code>df.set_index(['userid', 'timestamp']).groupby(level=0).filter(
    lambda x: ~x.index.is_unique
).reset_index()
</code>```

Body:
I have the following data.

userid itemid timestamp
  1       1      50
  1       2      50
  1       3      50
  1       4      60
  2       1      40
  2       2      50

I want to drop users who have duplicate timestamps.
In my example above, I want to drop userid=1  because he has viewed multiple items at timestamp=50. userid=2 should not be dropped since he has viewed items in different timestamps.

Can anyone help me?

Body:
option 1

Use duplicated

dropid = df.loc[
    df.duplicated(subset=['userid', 'timestamp']),
    'userid'
].unique()
df[~df.userid.isin(dropid)]

option 2

Use groupby and filter

df.set_index(['userid', 'timestamp']).groupby(level=0).filter(
    lambda x: ~x.index.is_unique
).reset_index()


问:
ORA-28086: The data redaction policy expression has an error
I am trying to create a policy for a column in a database by using below script, which is creating successfully in one data base but in other database it was giving errors.

FYI: Both the databases have EXECUTE PRIVILEGE on DBMS_REDACT POLICY

ORA-28086: The data redaction policy expression has an error.

```<code>BEGIN
DBMS_REDACT.ADD_POLICY(
object_schema =>'schemaname',
object_name =>'tablename',
column_name =>'columnname',
policy_name =>'policyneme',
function_type =>DBMS_REDACT.REGEXP,
policy_description =>'Masks the first 5 digits of SSN',
regexp_replace_string =>'XXXXX\3',
regexp_position =>1,
regexp_occurrence =>0,
regexp_match_parameter =>'i',
expression =>'1=1',
regexp_pattern =>'(\d\d\d)(\d\d)(\d\d\d\d)'
);
END;
</code>```

答:
This is a bug which is fixed in 12.2

When cursor_sharing=force it will fail with below error
ORA-28086: The data redaction policy expression has an error
http://oraniltips.blogspot.in/2017/03/ora-28086-data-redaction-policy.html?m=1

Body:
I am trying to create a policy for a column in a database by using below script, which is creating successfully in one data base but in other database it was giving errors.

FYI: Both the databases have EXECUTE PRIVILEGE on DBMS_REDACT POLICY

ORA-28086: The data redaction policy expression has an error.

BEGIN
DBMS_REDACT.ADD_POLICY(
object_schema =>'schemaname',
object_name =>'tablename',
column_name =>'columnname',
policy_name =>'policyneme',
function_type =>DBMS_REDACT.REGEXP,
policy_description =>'Masks the first 5 digits of SSN',
regexp_replace_string =>'XXXXX\3',
regexp_position =>1,
regexp_occurrence =>0,
regexp_match_parameter =>'i',
expression =>'1=1',
regexp_pattern =>'(\d\d\d)(\d\d)(\d\d\d\d)'
);
END;


问:
Why is PHP's mail function failing to deliver intermittently?
I have an event that fires every time a user successfully submits a form on my website. I can track the exact time that the event fired from my Google Analytics account. The time that the event fired, mirrors the delivery time of the email delivered to my inbox (yahoo mail).

However, I've noticed many times that, when the same event fires, no email is delivered to the the same email address. It never reaches its destination.

How can I fix this? What is the root of this problem?

Here is my php code:

```<code><?php
  if($_POST)
 {
   //check if its an ajax request, exit if not
   if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND      strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    die();
}

//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userLastName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userArrival"]) || !isset($_POST["userNumberPeople"])
|| !isset($_POST["userPickupLocation"]) || !isset($_POST["userRequest"]) || !isset($_POST["userTourSelection"]))
{
    die();
}

//Sanitize input data using PHP filter_var().
$user_Name              = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_LastName          = filter_var($_POST["userLastName"], FILTER_SANITIZE_STRING);
$user_Email             = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_TourSelection     = filter_var($_POST["userTourSelection"], FILTER_SANITIZE_STRING);
$user_Arrival           = filter_var($_POST["userArrival"], FILTER_SANITIZE_STRING);
$user_NumberPeople      = filter_var($_POST["userNumberPeople"], FILTER_SANITIZE_STRING);
$user_PickupLocation    = filter_var($_POST["userPickupLocation"], FILTER_SANITIZE_STRING);
$user_Request           = filter_var($_POST["userRequest"], FILTER_SANITIZE_STRING);

 $to_Email       = "something@yahoo.com"; //Replace with recipient email address
 $subject        = 'Tour request: '.$user_TourSelection.' '; //Subject line for emails

//additional php validation
if(strlen($user_Name)<2) // If length is less than 4 it will throw an HTTP error.
{
    header('HTTP/1.1 500 Name is too short or empty!');
    exit();
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
    header('HTTP/1.1 500 Please enter a valid email address!');
    exit();
}
if(strlen($user_Request)<5) //check emtpy message
{
    header('HTTP/1.1 500 Please explain in a few words how you would like us to assist you.');
    exit();
}

// message
 $message = '<strong>Name:</strong> '.$user_Name.' '.$user_LastName.' <br><br>
        <strong>Date of Arrival:</strong> '.$user_Arrival.' <br><br>
        <strong>Tour:</strong> '.$user_TourSelection.' <br><br>
        <strong>Number of people:</strong> '.$user_NumberPeople.' <br><br>
        <strong>Pick-Up Location:</strong> '.$user_PickupLocation.' <br><br>
        <strong>Request:</strong> '.$user_Request.'
        ';

//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
$headers .='Reply-To: '.$user_Email.'' . "\r\n" ;
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .='X-Mailer: PHP/' . phpversion();

 @$sentMail = mail($to_Email, $subject, $message, $headers);

if(!$sentMail)
{
    header('HTTP/1.1 500 Our server is under maintenance!<br> If this error persists please contact us directly: <strong>something@yahoo.com</strong>');
    exit();
}else{
    echo 'Congratulations '.$user_Name .'! ';
    echo 'We have received your request and we will respond as soon as possible.';
}
 }
  ?>
</code>```

答:
mail()'s delivery function ends when it hands off your mail to the SMTP server. Its sole responsibility is the real-world equivalent of taking your envelope and dropping it into the mailbox on the corner. The rest of the postal service (emptying that box, running it through processing centers, flying it to the recipient's country/city, etc...) is completely outside of mail()'s scope. As long as the envelope drops into the mailbox, mail() will return true and pretend it was delivered.

So... check your SMTP server's logs to see what really happened to the mail. Maybe it got marked as spam by the receiver and bounced. Maybe it's stuck in a queue somewhere, etc... Only the logs will tell you this - anything you can see/do in PHP is useless, because PHP and mail() only do maybe 1% of the email sending/delivery process, and something's wrong in that other 99%.

Body:
I have an event that fires every time a user successfully submits a form on my website. I can track the exact time that the event fired from my Google Analytics account. The time that the event fired, mirrors the delivery time of the email delivered to my inbox (yahoo mail).

However, I've noticed many times that, when the same event fires, no email is delivered to the the same email address. It never reaches its destination.

How can I fix this? What is the root of this problem?

Here is my php code:

<?php
  if($_POST)
 {
   //check if its an ajax request, exit if not
   if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND      strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    die();
}

//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userLastName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userArrival"]) || !isset($_POST["userNumberPeople"])
|| !isset($_POST["userPickupLocation"]) || !isset($_POST["userRequest"]) || !isset($_POST["userTourSelection"]))
{
    die();
}

//Sanitize input data using PHP filter_var().
$user_Name              = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_LastName          = filter_var($_POST["userLastName"], FILTER_SANITIZE_STRING);
$user_Email             = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_TourSelection     = filter_var($_POST["userTourSelection"], FILTER_SANITIZE_STRING);
$user_Arrival           = filter_var($_POST["userArrival"], FILTER_SANITIZE_STRING);
$user_NumberPeople      = filter_var($_POST["userNumberPeople"], FILTER_SANITIZE_STRING);
$user_PickupLocation    = filter_var($_POST["userPickupLocation"], FILTER_SANITIZE_STRING);
$user_Request           = filter_var($_POST["userRequest"], FILTER_SANITIZE_STRING);

 $to_Email       = "something@yahoo.com"; //Replace with recipient email address
 $subject        = 'Tour request: '.$user_TourSelection.' '; //Subject line for emails

//additional php validation
if(strlen($user_Name)<2) // If length is less than 4 it will throw an HTTP error.
{
    header('HTTP/1.1 500 Name is too short or empty!');
    exit();
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
    header('HTTP/1.1 500 Please enter a valid email address!');
    exit();
}
if(strlen($user_Request)<5) //check emtpy message
{
    header('HTTP/1.1 500 Please explain in a few words how you would like us to assist you.');
    exit();
}

// message
 $message = 'Name: '.$user_Name.' '.$user_LastName.'

        Date of Arrival: '.$user_Arrival.'

        Tour: '.$user_TourSelection.'

        Number of people: '.$user_NumberPeople.'

        Pick-Up Location: '.$user_PickupLocation.'

        Request: '.$user_Request.'
        ';

//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
$headers .='Reply-To: '.$user_Email.'' . "\r\n" ;
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .='X-Mailer: PHP/' . phpversion();

 @$sentMail = mail($to_Email, $subject, $message, $headers);

if(!$sentMail)
{
    header('HTTP/1.1 500 Our server is under maintenance!
 If this error persists please contact us directly: something@yahoo.com');
    exit();
}else{
    echo 'Congratulations '.$user_Name .'! ';
    echo 'We have received your request and we will respond as soon as possible.';
}
 }
  ?>


问:
How can I find the first occurrence in a string that is not numeric in java
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:</p>

```<code>public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}
</code>```

答:
How about you do it the following way?

```<code>    String s =  "698+33-47*2";
    String[] numbers = s.split("[*+/-]");
    List<String> list = Arrays.asList(numbers);
</code>```

This will give you the List of String containing 698, 33, 47, 2.

Body:
I'm working on my own method in Java that will be able to calculate math equations given a string. Basically my calculator gets something like "698+33-47*2".
I want to split the parts (using substring and finding the characters '+', '-', '*', '/') but I'm not sure how to find the first non numeric character. My method is like this so far:

public void DoEquation() {
  String s = storedData.getText() + data.getText();
  s = s.replaceAll(" ", "");

  ArrayList<String> list = new ArrayList<>();
  boolean checking = true;
  while (checking) {
    if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/") {
      checking = false;
      break;
    }
    // Logic for extracting the numbers into the list
    // Then extract the mathamatical sign and place into list
  }
  System.out.println(list); // For testing
}

Body:
How about you do it the following way?

    String s =  "698+33-47*2";
    String[] numbers = s.split("[*+/-]");
    List<String> list = Arrays.asList(numbers);

This will give you the List of String containing 698, 33, 47, 2.


问:
Unable to install IBM SDK for nodejs on Window 10
I am unable to install "ibm-6.9.1.0-node-v6.9.1-win-x64.exe" on my Windows 10. I am getting the following exception.

When I click on details , The following error message is visible-

```<code>Flexeraax2$aaa: Windows DLL failed to load
    at Flexeraax2.af(Unknown Source)
    at Flexeraax2.aa(Unknown Source)
    at com.zerog.ia.installer.LifeCycleManager.init(Unknown Source)
    at com.zerog.ia.installer.LifeCycleManager.executeApplication(Unknown Source)
    at com.zerog.ia.installer.Main.main(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.zerog.lax.LAX.launch(Unknown Source)
    at com.zerog.lax.LAX.main(Unknown Source)
</code>```

答:
I had the same problem. I solved it by calling for console:</p>

```<code>C:....> ibm-6.10.1.0-node-v6.10.1-win-x64 LAX_VM "C:\Program Files\Java\jdk1.7.0_80\bin\java.exe”
</code>```

Body:
I am unable to install "ibm-6.9.1.0-node-v6.9.1-win-x64.exe" on my Windows 10. I am getting the following exception.

When I click on details , The following error message is visible-

Flexeraax2$aaa: Windows DLL failed to load
    at Flexeraax2.af(Unknown Source)
    at Flexeraax2.aa(Unknown Source)
    at com.zerog.ia.installer.LifeCycleManager.init(Unknown Source)
    at com.zerog.ia.installer.LifeCycleManager.executeApplication(Unknown Source)
    at com.zerog.ia.installer.Main.main(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.zerog.lax.LAX.launch(Unknown Source)
    at com.zerog.lax.LAX.main(Unknown Source)

Body:
I had the same problem. I solved it by calling for console:

C:....> ibm-6.10.1.0-node-v6.10.1-win-x64 LAX_VM "C:\Program Files\Java\jdk1.7.0_80\bin\java.exe”


问:
pushing a new remote branch gives error committer e-mail address does not match
With a command similar to

```<code>git checkout -b a7e4767 new-branch
git push origin new-branch
</code>```

I get the following error

```<code>remote: ERROR:  In commit a7e4767a80e9b0730c8708973918c990af308a45
remote: ERROR:  committer email address someone.else@xyz.com
remote: ERROR:  does not match your user account.
remote: ERROR:
remote: ERROR:  The following addresses are currently registered:
remote: ERROR:    my.self@sap.com
</code>```

All my search turns up suggestions for amending the commit, but I don't think I want to amend that old commit.

答:
This doesn't sound like a git issue, strictly speaking. This sounds more like a feature offered by Gerrit

If you are registered with the system and your email address is setup correctly in your local repo, then you might be able to layer over a new commit with no changes and push that. The new commit will be tagged with your email address, which gets around the need to modify the existing commit. See How to commit no change and new message?

I think the proper way to handle this situation, however, would be to get the "Forge Committer" permission.

Body:
With a command similar to

git checkout -b a7e4767 new-branch
git push origin new-branch

I get the following error

remote: ERROR:  In commit a7e4767a80e9b0730c8708973918c990af308a45
remote: ERROR:  committer email address someone.else@xyz.com
remote: ERROR:  does not match your user account.
remote: ERROR:
remote: ERROR:  The following addresses are currently registered:
remote: ERROR:    my.self@sap.com

All my search turns up suggestions for amending the commit, but I don't think I want to amend that old commit.


问:
general-purpose binary protocols
I'm trying to find a suitable protocol middleware for my next distributed application. I've found several specifications in the last few days and was wondering if I missed an important one? It should be a binary protocol, support RPCs and optionally have open-source implementations in different languages. Here's the list of protocols I found:

CORBA

ICE

AMQP

Thrift

And this is the list of dismissed protocols:

XML based protocols because they are text based (XML-RCP, SOAP, hand-rolled, etc.)

Protocol Buffers (Closed Source)

COM (Windows-only)

答: I would recommend trying out RabbitMQ AMQP, and using Protocol Buffers, XML, or some other data format such as JSON, to taste.  In addition to being relatively simple and easy to get started with, this lets you mix and match RPC and asynchronous pubsub styles, and has a good spread across languages, protocols and platforms.  But it may not be a good fit for your problem -- it all depends what you are trying to do!  Cheers, alexis</p>

Title: general-purpose binary protocols

LastEditorDisplayName: zacherates

OwnerDisplayName: alexis


问:
Error adding "Azure Mobile Apps Table Controller"
I have a fresh install of Visual Studio 2017, RTM (15.0.0+26228.9).
I created a new project from the "Azure Mobile App" template. (created fine)
Then, under the Controllers folder, I right-clicked "Add Controller...".
I tried each of the following 2 templates, and received an error on each:

```<code>Azure Mobile Apps Custom Controller
Azure Mobile Apps Table Controller
</code>```

Considering the Table Controller first, I received the error: There was an error running the selected code generator: 'A TwoWay or OneWayToSource binding cannot work on the read-only property 'EntityTypes' of type 'Microsoft.Cct.MobileApps.WebExtensions.Scaffolding.MobileAppsTableControllerViewModel'.'

The Custom Controller allowed me to select the controller name, then showed the error: There was an error running the selected code generator: 'Could not find template '' in these folders ['C:\Program Files (x86)\Microsoft SDKs\Microsoft Azure\Mobile Apps\2.0\Scaffold'], including sub-folders.'

The standard Web API Controller - Empty worked fine.

Azure App Services Tools shows v3.0.0 (15.0.30209.0).

EDIT 4/1/2017: Reproduced the table controller symptom with a fresh Mobile App project, same error for table creation, even after reinstalling with latest tool version, as directed in comments:

Any ideas?

-John

答: Go to https://www.microsoft.com/en-us/download/details.aspx?id=54917, download AzureMobileAppsSdkPackagesV2.0.msi only and install it. Then try to add a new custom controller once more and the problem should be gone.

Body:
I have a fresh install of Visual Studio 2017, RTM (15.0.0+26228.9).
I created a new project from the "Azure Mobile App" template. (created fine)
Then, under the Controllers folder, I right-clicked "Add Controller...".
I tried each of the following 2 templates, and received an error on each:

Azure Mobile Apps Custom Controller
Azure Mobile Apps Table Controller

Considering the Table Controller first, I received the error: There was an error running the selected code generator: 'A TwoWay or OneWayToSource binding cannot work on the read-only property 'EntityTypes' of type 'Microsoft.Cct.MobileApps.WebExtensions.Scaffolding.MobileAppsTableControllerViewModel'.'

The Custom Controller allowed me to select the controller name, then showed the error: There was an error running the selected code generator: 'Could not find template '' in these folders ['C:\Program Files (x86)\Microsoft SDKs\Microsoft Azure\Mobile Apps\2.0\Scaffold'], including sub-folders.'

The standard Web API Controller - Empty worked fine.

Azure App Services Tools shows v3.0.0 (15.0.30209.0).

EDIT 4/1/2017: Reproduced the table controller symptom with a fresh Mobile App project, same error for table creation, even after reinstalling with latest tool version, as directed in comments:

Any ideas?

-John


问:
Laravel Nested ForEach Over Eloquent Collection
I'm trying to use a many to many relationship to accomplish the following workflow:

There are many sections and many users. Each user has sections they have unlocked. So for example, if there are two sections (Section I and Section II) the first user, Jim (id = 1), has unlocked Section X, the second user, Debbie (id = 2), has unlocked Section I and II.

To accomplish this, I have three databases, a standard Laravel users, then a sections which stores the section data (id = 1 for Section I and id = 2 for Section II) and then a user_section that I have successfully used as the joint table between the User and Section models. That join table is where users and sections intermingle, if there is an entry for a given user_id in that section, the corresponding section_id is unlocked.

I have the following function which is supposed to 1. Get all the sections for the view and 2. Let me know which of those sections are unlocked by the user.

The problem is I get duplicate Sections showing up, so it will say Section I is unlocked, then Section I is locked all in the same view, this must be in how I am traversing and comparing arrays. With tweaks to the code (where I place a break I can get rid of the duplicates, but then the wrong sections are locked.

My logic is here:

```<code>public function getSections(){
    $arrayofuserSections = array();
    $tempArray = array();
    $user = User::where("id",Auth::user()->id)->first();
    foreach ($user->section as $section) {
    $tempArray['Name'] = $section["name"];
    $tempArray['Goals'] = $section["goals"];
    array_push($arrayofuserSections,$tempArray);
}
    $finarray = array();
    $sections=Section::orderBy('order')->get();
    foreach ($sections as $section) {
    foreach($arrayofuserSections as $arraysection){
    if($section->name == $arraysection["Name"])
    {
    $arraysection["Unlocked"] = 1;
    array_push($finarray,$arraysection);
    }
    else{
    $arraysection["Unlocked"] = 0;
    $arraysection["Name"] = $section->name;
    $arraysection["Goals"] = "";
    array_push($finarray,$arraysection);
    }
    break;
    }
    }
    return $finarray;
}
</code>```

$user->section is derived from a method on the User model, here:

```<code>public function section()
    {
        return $this->belongsToMany('App\Models\Section','user_section')->withTimestamps();
    }
</code>```

My seeding for the user Debbie is here:

```<code>        DB::table('user_section')->insert([
            'user_id' => 2,
            'section_id'=>1
        ]);
        DB::table('user_section')->insert([
            'user_id' => 2,
            'section_id'=>2
        ]);
</code>```

And yet I get the following result when logged in as Debbie:

So even though Debbie has both sections in the join table, she gets only has one of them unlocked, and again this changes if I remove or move the break around.

答:
I think that you're coming at this from the wrong direction.

If you have set up your relationships correctly, you should be able to access sections from users, and users from sections.

```<code>// Find user with sections they have unlocked
$user = User::with('sections')->findOrFail(1);

// Find sections with users who have unlocked them
$section = Section::with('users')->findOrFail(1);
</code>```

If you approach this problem from the direction of sections, you can do the following:

```<code>// Find current user id
$userId = Auth::id();

// Find all sections with users who have unlocked them, limited to only the current user
$sections = Section::with([
        'users' => function ($query) use ($userId) {
            return $query->where('id', $userId);
        }
    ])->get();
</code>```

This will give you all sections, and eager load the users relation, where that is the current user. Thus, if the users relationship is empty, the current user hasn't unlocked that section.

Body:
I'm trying to use a many to many relationship to accomplish the following workflow:

There are many sections and many users. Each user has sections they have unlocked. So for example, if there are two sections (Section I and Section II) the first user, Jim (id = 1), has unlocked Section X, the second user, Debbie (id = 2), has unlocked Section I and II.

To accomplish this, I have three databases, a standard Laravel users, then a sections which stores the section data (id = 1 for Section I and id = 2 for Section II) and then a user_section that I have successfully used as the joint table between the User and Section models. That join table is where users and sections intermingle, if there is an entry for a given user_id in that section, the corresponding section_id is unlocked.

I have the following function which is supposed to 1. Get all the sections for the view and 2. Let me know which of those sections are unlocked by the user.

The problem is I get duplicate Sections showing up, so it will say Section I is unlocked, then Section I is locked all in the same view, this must be in how I am traversing and comparing arrays. With tweaks to the code (where I place a break I can get rid of the duplicates, but then the wrong sections are locked.

My logic is here:

public function getSections(){
    $arrayofuserSections = array();
    $tempArray = array();
    $user = User::where("id",Auth::user()->id)->first();
    foreach ($user->section as $section) {
    $tempArray['Name'] = $section["name"];
    $tempArray['Goals'] = $section["goals"];
    array_push($arrayofuserSections,$tempArray);
}
    $finarray = array();
    $sections=Section::orderBy('order')->get();
    foreach ($sections as $section) {
    foreach($arrayofuserSections as $arraysection){
    if($section->name == $arraysection["Name"])
    {
    $arraysection["Unlocked"] = 1;
    array_push($finarray,$arraysection);
    }
    else{
    $arraysection["Unlocked"] = 0;
    $arraysection["Name"] = $section->name;
    $arraysection["Goals"] = "";
    array_push($finarray,$arraysection);
    }
    break;
    }
    }
    return $finarray;
}

$user->section is derived from a method on the User model, here:

public function section()
    {
        return $this->belongsToMany('App\Models\Section','user_section')->withTimestamps();
    }

My seeding for the user Debbie is here:

        DB::table('user_section')->insert([
            'user_id' => 2,
            'section_id'=>1
        ]);
        DB::table('user_section')->insert([
            'user_id' => 2,
            'section_id'=>2
        ]);

And yet I get the following result when logged in as Debbie:

So even though Debbie has both sections in the join table, she gets only has one of them unlocked, and again this changes if I remove or move the break around.

Body:
I think that you're coming at this from the wrong direction.

If you have set up your relationships correctly, you should be able to access sections from users, and users from sections.

// Find user with sections they have unlocked
$user = User::with('sections')->findOrFail(1);

// Find sections with users who have unlocked them
$section = Section::with('users')->findOrFail(1);

If you approach this problem from the direction of sections, you can do the following:

// Find current user id
$userId = Auth::id();

// Find all sections with users who have unlocked them, limited to only the current user
$sections = Section::with([
        'users' => function ($query) use ($userId) {
            return $query->where('id', $userId);
        }
    ])->get();

This will give you all sections, and eager load the users relation, where that is the current user. Thus, if the users relationship is empty, the current user hasn't unlocked that section.


答:
You could create a csv file, which you can open with Excel.

write.csv(a[2], "myfile.csv", row.names = FALSE, col.names = FALSE.

Note that the file will be created in your current working directory, which you can find by running the following code: getwd().

On a different note, are you trying to get the column into Excel for further analysis? If you are, I encourage you to learn how to do that analysis in R.

Title: Is there anyway to delete rownames in R?

Body:
I made a table like this table name a.

   variable relative_importance scaled_importance percentage
1      x005        68046.078125          1.000000   0.195396
2      x004        63890.796875          0.938934   0.183464
3      x007        48253.820312          0.709134   0.138562
4      x012        43492.117188          0.639157   0.124889
5      x008        43132.035156          0.633865   0.123855
6      x013        32495.070312          0.477545   0.093310
7      x009        18466.910156          0.271388   0.053028
8      x015        10625.453125          0.156151   0.030511
9      x010         8893.750977          0.130702   0.025539
10     x014         4904.361816          0.072074   0.014083
11     x002         1812.269531          0.026633   0.005204
12     x001         1704.574585          0.025050   0.004895
13     x006         1438.692139          0.021143   0.004131
14     x011         1080.584106          0.015880   0.003103
15     x003           10.152302          0.000149   0.000029

and use this code to order that table.

setorder(a,variable)

and want to get only second column.

a[2]

   relative_importance
12            380.4296
11            645.4594
15             10.1440
4            8599.7715
2           10749.5752
13            263.7065
5            8434.3760
6            7443.8530
7            3602.8850
10            935.6713
14            256.7183
3            9160.4062
1           12071.1826
9            1173.0701
8            1698.0955

I want to copy "relative_importance" and paste in Excel.
But, I couldn't delete the rownames. (12,11,15...,9,8)
Is there any way to print only "relative_importance"? (print without rownames or hide rownames)

Thank you :)


问:
Python Dictionary to CSV
I have written code to read a CSV into a python dictionary, which works fine. I'm trying to get the dictionary back to a CSV. I have written the following:

```<code>import csv

itemDict={}

listReader = csv.reader(open('/Users/broberts/Desktop/Sum_CSP1.csv','rU'), delimiter = ',', quotechar='|')

for row in listReader:
    fID = row[0]
    fClassRange = row[1]
    fArea = row[2]

    if itemDict.has_key(fID):
        itemDict[fID][fClassRange]=fArea
    else:
        itemDict[fID] = {'5.0 to 5.25':'','5.25 to 5.5':'','5.5 to 5.75':'','5.75 to 6.0':'','6.0 to 6.25':'','6.25 to 6.5':'','6.5 to 6.75':'','6.75 to 7.0':'','7.0 to 7.25':'','7.25 to 7.5':'','7.5 to 7.75':'','7.75 to 8.0':'','8.0 to 8.25':'',}
        itemDict[fID][fClassRange]=fArea

listWriter = csv.writer(open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for a in itemDict:
    print a
    listWriter.writerow(a)
</code>```

In the last block, listWriter will not write anything to the CSV though it will print a.  I believe this has something to do with a dictionary being unordered.  I really need to write out the fID and each of the keys associated with each fID (fClassRange ex. "5.0 to 5.25") and then the value fArea associated with each fClassRange to the CSV, but I haven't even gotten that far in my code since I can't figure out how to write out even the fID.

I looked into using DictWriter, but I can't figure out how to tell it what the required fieldnames are.

答:
This is what i use, its simple and works fine for me.
when you have only one dictionary, use this

```<code>my_dict = {"tester": 1, "testers": 2}
with open('mycsvfile.csv', 'wb') as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writerow(dict((fn,fn) for fn in my_dict.keys()))
    w.writerow(my_dict)

$ cat mycsvfile.csv
testers,tester
2,1
</code>```

When you have a list of dictionaries, like what you get from SQL queries, you do like this.

```<code>my_dict = ({"tester": 1, "testers": 2},{"tester": 14, "testers": 28})
with open('mycsvfile.csv', 'wb') as f:
    w = csv.DictWriter(f, my_dict[0].keys())
    w.writerow(dict((fn,fn) for fn in my_dict[0].keys()))
    w.writerows(my_dict)

cat mycsvfile.csv
testers,tester
2,1
28,14
</code>```

Title: Python Dictionary to CSV

Body:
I have written code to read a CSV into a python dictionary, which works fine. I'm trying to get the dictionary back to a CSV. I have written the following:

import csv

itemDict={}

listReader = csv.reader(open('/Users/broberts/Desktop/Sum_CSP1.csv','rU'), delimiter = ',', quotechar='|')

for row in listReader:
    fID = row[0]
    fClassRange = row[1]
    fArea = row[2]

    if itemDict.has_key(fID):
        itemDict[fID][fClassRange]=fArea
    else:
        itemDict[fID] = {'5.0 to 5.25':'','5.25 to 5.5':'','5.5 to 5.75':'','5.75 to 6.0':'','6.0 to 6.25':'','6.25 to 6.5':'','6.5 to 6.75':'','6.75 to 7.0':'','7.0 to 7.25':'','7.25 to 7.5':'','7.5 to 7.75':'','7.75 to 8.0':'','8.0 to 8.25':'',}
        itemDict[fID][fClassRange]=fArea

listWriter = csv.writer(open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for a in itemDict:
    print a
    listWriter.writerow(a)

In the last block, listWriter will not write anything to the CSV though it will print a.  I believe this has something to do with a dictionary being unordered.  I really need to write out the fID and each of the keys associated with each fID (fClassRange ex. "5.0 to 5.25") and then the value fArea associated with each fClassRange to the CSV, but I haven't even gotten that far in my code since I can't figure out how to write out even the fID.

I looked into using DictWriter, but I can't figure out how to tell it what the required fieldnames are.

Body:
This is what i use, its simple and works fine for me.
when you have only one dictionary, use this

my_dict = {"tester": 1, "testers": 2}
with open('mycsvfile.csv', 'wb') as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writerow(dict((fn,fn) for fn in my_dict.keys()))
    w.writerow(my_dict)

$ cat mycsvfile.csv
testers,tester
2,1

When you have a list of dictionaries, like what you get from SQL queries, you do like this.

my_dict = ({"tester": 1, "testers": 2},{"tester": 14, "testers": 28})
with open('mycsvfile.csv', 'wb') as f:
    w = csv.DictWriter(f, my_dict[0].keys())
    w.writerow(dict((fn,fn) for fn in my_dict[0].keys()))
    w.writerows(my_dict)

cat mycsvfile.csv
testers,tester
2,1
28,14


问:
how to store json objects in mariadb?
```<code>{
"client_request": {
"id": 29318,
"pincode": 110009,
"client_order_id": "66967604933444",
"pickup_address": {
"pincode": 411026,
"id": 26269,
"address": "Khasra No. 93/5 94/1 Phirni Road Vill- Mundka New
Delhi Delhi"
},
"skus": [{
"client_sku_id": "SC45634",
"price": null,
"id": 26267,
"product_name": "xyz"
}]
</code>```

}

here i don't know what might be the number of json objects in skus ..
i read about dynamic col in maria db but then using dynamic col i am having problem storing array of json object ..

答:
Sounds like 2 tables, no JSON:

client_requests

skus (with the id of the client_request for which it applies)

I don't know what the current id is -- perhaps it came from a database implementation?

Title: how to store json objects in mariadb?

Body:
{
"client_request": {
"id": 29318,
"pincode": 110009,
"client_order_id": "66967604933444",
"pickup_address": {
"pincode": 411026,
"id": 26269,
"address": "Khasra No. 93/5 94/1 Phirni Road Vill- Mundka New
Delhi Delhi"
},
"skus": [{
"client_sku_id": "SC45634",
"price": null,
"id": 26267,
"product_name": "xyz"
}]

}

here i don't know what might be the number of json objects in skus ..
i read about dynamic col in maria db but then using dynamic col i am having problem storing array of json object ..


问:
What are all of the generic collections/types in the 4.0 .NET Framework?
Is there an exhaustive list of all of the "base" (not used in an object-oriented sense but more in a common sense) generic types in the 4.0 .NET Framework? I have found this list that I often send newer/mid-level devs to so they can understand how non-generic types map to generic types, but this is by no means exhaustive. I'm looking for something that also includes things such as KeyValuePair<>, Tuple<>, and other basic generics that may not be very-well known. Interfaces such as IObservable<> would be nice but not necessarily required.

答: You could reflect on all the BCL assemblies and use the IsGenericType method to get a list of generic types.</p>


问:
Calculate value based on amount of green against blue and red
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

```<code>var red:int = 53;
var green:int = 150;
var blue:int = 28;
</code>```

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

```<code>var red:int = 0;
var green:int = 255;
var blue:int = 0;
</code>```

Would receive the highest score(10) and:

```<code>var red:int = 255;
var green:int = 0;
var blue:int = 255;
</code>```

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

答:
If just checking a colour value to extract a score 0 - 10 from a 0 - 255 range then simply do :

```<code>score = Math.round( (green / 255 ) * 10 );
</code>```

So with this logic, we can see that where :

green = 253 gives score of 10
 green = 190 gives score of 7
 green = 128
  gives score of 5
 green = 47 gives score of 2

There is a threshold where if number is above X but less than Y it will give same score for example any green between 243 and 255 will give a score of 10.

PS: Some testable code:

```<code>var score:int = 0;
var green:int = 128; //#change this for testing
score = Math.round( (green / 255 ) * 10 );

trace ("score is : " + score);
</code>```

Body:
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

var red:int = 53;
var green:int = 150;
var blue:int = 28;

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

var red:int = 0;
var green:int = 255;
var blue:int = 0;

Would receive the highest score(10) and:

var red:int = 255;
var green:int = 0;
var blue:int = 255;

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

Body:
If just checking a colour value to extract a score 0 - 10 from a 0 - 255 range then simply do :

score = Math.round( (green / 255 ) * 10 );

So with this logic, we can see that where :

green = 253 gives score of 10
 green = 190 gives score of 7
 green = 128
  gives score of 5
 green = 47 gives score of 2

There is a threshold where if number is above X but less than Y it will give same score for example any green between 243 and 255 will give a score of 10.

PS: Some testable code:

var score:int = 0;
var green:int = 128; //#change this for testing
score = Math.round( (green / 255 ) * 10 );

trace ("score is : " + score);


问:
Swiper touch slider - Not sliding
I'm creating a swiper in jQuery. Im using Swiper touch slider - It's not working on my main domain. Only thing I can think of is that another JS file is overriding it? But I removed all of my JS files and its still not working. Heres the HTML code</p>

```<code>        <div class="device">
        <div class="swiper-button-next"></div>
        <div class="swiper-button-prev"></div>
        <div class="swiper-container" style="cursor: -webkit-grab;">
        <div class="swiper-wrapper" style="width: 3200px; height: 560px; transform: translate3d(-1920px, 0px, 0px); transition-duration: 0.3s;">
        <div class="swiper-slide swiper-slide-duplicate" style="width: 513px; height: 560px;">
        <div class="content-slide">
        <p class="title">Slide with HTML</p>
        <p>You can put any HTML inside of slide with any layout, not only images, even another Swiper!</p>
        </div>
        </div>
        <div class="swiper-slide" style="width: 513px; height: 560px;"> <img src="images/slider1-1.png"> </div>
        <div class="swiper-slide" style="width: 513px; height: 560px;"> <img src="images/slider1-2.png"> </div>
        <div class="swiper-slide swiper-slide-visible swiper-slide-active" style="width: 513px; height: 560px;">
        <div class="content-slide">
        <p class="title">Slide with HTML</p>
        <p>You can put any HTML inside of slide with any layout, not only images, even another Swiper!</p>
        </div>
        </div>
        <div class="swiper-slide swiper-slide-duplicate" style="width: 513px; height: 560px;"> <img src="images/slider1-1.png"> </div>
        </div>
        </div>
        <div class="pagination"><span class="swiper-pagination-switch"></span><span class="swiper-pagination-switch"></span><span class="swiper-pagination-switch swiper-visible-switch swiper-active-switch"></span></div>
        </div>
        <!-- Initialize Swiper -->
        <script>
        var swiper = new Swiper('.swiper-container', {
        pagination: '.swiper-pagination',
        paginationClickable: true,
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
        spaceBetween: 0
        });
        </script>

        This is the link to Swiper:
        http://idangero.us/swiper/#.WM4Hd_krIdU

        I also added in at the footer:
        <script src="js/swiper.js"></script>
        <script src="js/swiper.min.js"></script>
        <script src="js/swiper.jquery.js"></script>
        <script src="js/swiper.jquery.min.js"></script>
</code>```

答:
you should develop your html according to the following template:

```<code><!-- Slider main container -->
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>

<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>

<!-- If we need scrollbar -->
<div class="swiper-scrollbar"></div>
</div>
</code>```

load the minificated version (.min.js) OR the not minified (.js)

include the swiper initialization script in the very end of body (right before closing  tag)

you can read the docs here : http://idangero.us/swiper/get-started/#.WNsOA98xA8o

Title: Swiper touch slider - Not sliding

Body:
I'm creating a swiper in jQuery. Im using Swiper touch slider - It's not working on my main domain. Only thing I can think of is that another JS file is overriding it? But I removed all of my JS files and its still not working. Heres the HTML code

Slide with HTML

You can put any HTML inside of slide with any layout, not only images, even another Swiper!

Slide with HTML

You can put any HTML inside of slide with any layout, not only images, even another Swiper!

        This is the link to Swiper:
        http://idangero.us/swiper/#.WM4Hd_krIdU

        I also added in at the footer:

Body:
you should develop your html according to the following template:

<!-- Slider main container -->
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>

<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>

<!-- If we need scrollbar -->
<div class="swiper-scrollbar"></div>
</div>

load the minificated version (.min.js) OR the not minified (.js)

include the swiper initialization script in the very end of body (right before closing  tag)

you can read the docs here : http://idangero.us/swiper/get-started/#.WNsOA98xA8o


问:
Visual Studio Extension - set "Copy To Output Directory" property
I'm creating a VS extension, and I want to add a file to solution and set some properties. One of them is Copy to output directory, but I cannot find a way of setting it. Setting Build action works fine, but the desired property is not even listed in array while debugging.

```<code>private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
  var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
  var item = folder.ProjectItems.AddFromFileCopy(filePath);

  item.Properties.Item("BuildAction").Value = "None";
  // item.Properties.Item("CopyToOutputDirectory").Value = "CopyAlways"; // doesn't work - the dictionary doesn't contain this item, so it throws an exception

  return item;
}
</code>```

How can I set the property for my newly added item?

答:
Please modify the code like below, it works on my side.

```<code>    foreach (Property p in item.Properties)
            {
                if (p.Name == "CopyToOutputDirectory")
                {
                    p.Value = 1;
                }

                //dic[p.Name] = p.Value;
            }
</code>```

Update:

Please add the following code on your code, then check if the dictionary object has 'CopyToOutputDirectory'

```<code> Dictionary<string,object> dic = new Dictionary<string, object>();
            foreach (Property p in item.Properties)
            {
                dic[p.Name] = p.Value;
            }
</code>```

Body:
I'm creating a VS extension, and I want to add a file to solution and set some properties. One of them is Copy to output directory, but I cannot find a way of setting it. Setting Build action works fine, but the desired property is not even listed in array while debugging.

private EnvDTE.ProjectItem AddFileToSolution(string filePath)
{
  var folder = CurrentProject.ProjectItems.AddFolder(Path.GetDirectoryName(filePath));
  var item = folder.ProjectItems.AddFromFileCopy(filePath);

  item.Properties.Item("BuildAction").Value = "None";
  // item.Properties.Item("CopyToOutputDirectory").Value = "CopyAlways"; // doesn't work - the dictionary doesn't contain this item, so it throws an exception

  return item;
}

How can I set the property for my newly added item?

Body:
Please modify the code like below, it works on my side.

    foreach (Property p in item.Properties)
            {
                if (p.Name == "CopyToOutputDirectory")
                {
                    p.Value = 1;
                }

                //dic[p.Name] = p.Value;
            }

Update:

Please add the following code on your code, then check if the dictionary object has 'CopyToOutputDirectory'

 Dictionary<string,object> dic = new Dictionary<string, object>();
            foreach (Property p in item.Properties)
            {
                dic[p.Name] = p.Value;
            }


问:
How to disable a click and re enable it later on with jQuery
I have a function that is triggered by a click. I want after I click it, disabling the click. So I made this

```<code>$('.item-blog').on('click', function(){

    $('.item-blog').off('click');

});
</code>```

and It's working perfectly.

But later on, at the end of all the events, within the last function, when I have resetted all the stuff and I have run all the code, I want to be able to re click the first function in order to fire the same events again. So I put this within the last function that resets everything.

```<code>$('.item-blog').on('click');
</code>```

But it is not working at all.

I even tried bind and unbind but every time I want to re enable the click, it is never working.

Some help?

Thank you very much

答:
You can try the on and off as below to toggle the click.

$(document).ready(function(){

function toggleClick(on) {

   if(on) {
      $('.item-blog').on('click', function(){
         console.log('clicked');
         toggleClick(false);

      });

   } else {
      $('.item-blog').off('click');
   }

}

toggleClick(true);

$('.item-blog-reset').on('click', function(){
    console.log('Reset done');
    toggleClick(true);

});

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Click" class="item-blog" />
<input type="button" value="Reset" class="item-blog-reset" /></code>```

Body:
I have a function that is triggered by a click. I want after I click it, disabling the click. So I made this

$('.item-blog').on('click', function(){

    $('.item-blog').off('click');

});

and It's working perfectly.

But later on, at the end of all the events, within the last function, when I have resetted all the stuff and I have run all the code, I want to be able to re click the first function in order to fire the same events again. So I put this within the last function that resets everything.

$('.item-blog').on('click');

But it is not working at all.

I even tried bind and unbind but every time I want to re enable the click, it is never working.

Some help?

Thank you very much

Body:
You can try the on and off as below to toggle the click.

$(document).ready(function(){

function toggleClick(on) {

   if(on) {
      $('.item-blog').on('click', function(){
         console.log('clicked');
         toggleClick(false);

      });

   } else {
      $('.item-blog').off('click');
   }

}

toggleClick(true);

$('.item-blog-reset').on('click', function(){
    console.log('Reset done');
    toggleClick(true);

});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Click" class="item-blog" />
<input type="button" value="Reset" class="item-blog-reset" />


问:
Use case for jQuery promise refactoring
I'm wondering if it is possible to refactor this pseudo-code:

```<code>function foo() {
   if (condition) {
      return somethingReturningPromise().then(function (data) {
         doSomethingOnSuccess(data);
         return mainFunctionReturningPromise(); // here ...
      }, function () {
         return mainFunctionReturningPromise(); // here ...
      });
   }
   return mainFunctionReturningPromise(); // and here !!!
}

// ... somewhere ...
foo().done(function () {
   // here, mainFunctionReturningPromise successfully resolved
   continueProgram();
});
</code>```

As you can see, mainFunctionReturningPromise is called in all possible cases:

if condition is met and somethingReturningPromise() is on success

if condition is met and somethingReturningPromise() is on failure

if condition is not met

Because of the special treatment provided by doSomethingOnSuccess(data), I cannot seem to find a way to refactor the 3 calls to mainFunctionReturningPromise. Can you ?

答:
For mainFunctionReturningPromise to appear once, it needs to be a .then() callback at the end of a promise chain.

To guarantee .then() is available, you need a guaranteed promise, regardless of the outcome of outcome of if (condition).

This can be achieved in a number of ways.

An interesting way is to "turn the code inside-out". Start with a resolved promise ($.when() in jQuery) and perform the decision making (if (condition){...}) downstream, in a chained .then().

```<code>function foo() {
    return $.when() // resolved promise
    .then(function() {
        if (condition) {
            return somethingReturningPromise().then(doSomethingOnSuccess, function() {
                return $.when(); // this line may be omitted with jQuery 3+, where error handlers "catch" by default; but don't omit the function wrapper.
            });
        } // else `return undefined` is implicit.
    })
    .then(mainFunctionReturningPromise); // here's your single mention of `mainFunctionReturningPromise`, at the end of the chain.
}
</code>```

Title: Use case for jQuery promise refactoring

Body:
I'm wondering if it is possible to refactor this pseudo-code:

function foo() {
   if (condition) {
      return somethingReturningPromise().then(function (data) {
         doSomethingOnSuccess(data);
         return mainFunctionReturningPromise(); // here ...
      }, function () {
         return mainFunctionReturningPromise(); // here ...
      });
   }
   return mainFunctionReturningPromise(); // and here !!!
}

// ... somewhere ...
foo().done(function () {
   // here, mainFunctionReturningPromise successfully resolved
   continueProgram();
});

As you can see, mainFunctionReturningPromise is called in all possible cases:

if condition is met and somethingReturningPromise() is on success

if condition is met and somethingReturningPromise() is on failure

if condition is not met

Because of the special treatment provided by doSomethingOnSuccess(data), I cannot seem to find a way to refactor the 3 calls to mainFunctionReturningPromise. Can you ?

Body:
For mainFunctionReturningPromise to appear once, it needs to be a .then() callback at the end of a promise chain.

To guarantee .then() is available, you need a guaranteed promise, regardless of the outcome of outcome of if (condition).

This can be achieved in a number of ways.

An interesting way is to "turn the code inside-out". Start with a resolved promise ($.when() in jQuery) and perform the decision making (if (condition){...}) downstream, in a chained .then().

function foo() {
    return $.when() // resolved promise
    .then(function() {
        if (condition) {
            return somethingReturningPromise().then(doSomethingOnSuccess, function() {
                return $.when(); // this line may be omitted with jQuery 3+, where error handlers "catch" by default; but don't omit the function wrapper.
            });
        } // else `return undefined` is implicit.
    })
    .then(mainFunctionReturningPromise); // here's your single mention of `mainFunctionReturningPromise`, at the end of the chain.
}


问:
Queuing theory for programmers?
After being burnt several times on things that seemed "obviously fast enough" but sucked performance-wise under load, I'm starting to think that my "gut feeling" might be not enough when doing capacity planning, and some theoretical background is necessary.

So - community, can you point me to good resources on applications of queuing theory to programming?

Whatever - articles, case studies, books.

I found a couple of books that seem to be relevant so far; I'd be happy to hear your opinions on them, if you're familiar:

Software Performance and Scalability: A Quantitative Approach

The Art of Computer Systems Performance Analysis: Techniques for Experimental Design, Measurement, Simulation, and Modeling

Performance by Design: Computer Capacity Planning By Example

答:
I took a course in my MS program called "Performance of Computer Systems" - or something like that. Two months of the course covered queuing theory. Seems that the de facto book that is used for such courses is the book by Jain, i.e.

The Art of Computer Systems Performance Analysis: Techniques for Experimental Design, Measurement, Simulation, and Modeling

I think that this text tries to cover too much, and I can say that I only gained a breadth of the topic.

Title: Queuing theory for programmers?


问:
Speeding Up Python Code Time
```<code>start = time.time()
import csv
f = open('Speed_Test.csv','r+')
coordReader = csv.reader(f, delimiter = ',')
count = -1
successful_trip = 0
trips = 0

for line in coordReader:
    successful_single = 0
    count += 1
    R = interval*0.30
    if count == 0:
        continue
    if 26 < float(line[0]) < 48.7537144 and 26 < float(line[2]) <   48.7537144 and -124.6521017 < float(line[1]) < -68 and -124.6521017 < float(line[3]) < -68:
        y2,x2,y1,x1 = convertCoordinates(float(line[0]),float(line[1]),float(line[2]),float(line[3]))
        coords_line,interval = main(y1,x1,y2,x2)

        for item in coords_line:
            loop_count = 0
            r = 0
            min_dist = 10000

            for i in range(len(df)):
                dist = math.sqrt((item[1]-df.iloc[i,0])**2 + (item[0]-df.iloc[i,1])**2)
                if dist < R:
                    loop_count += 1
                    if dist < min_dist:
                        min_dist = dist
                        r = i
            if loop_count != 0:
                successful_single += 1
                df.iloc[r,2] += 1

        trips += 1
        if successful_single == (len(coords_line)):
            successful_trip += 1

end = time.time()
print('Percent Successful:',successful_trip/trips)
print((end - start))
</code>```

I have this code and explaining it would be extremely time consuming but it doesn't run as fast as I need it to in order to be able to compute as much as I'd like. Is there anything anyone sees off the bat that I could do to speed the process up? Any suggestions would be greatly appreciated.

In essence it reads in 2 lat and long coordinates and changes them to a cartesian coordinate and then goes through every coordinate along the path from on origin coordinate to the destination coordinate in certain interval lengths depending on distance. As it is doing this though there is a data frame (df) with 300+ coordinate locations that it checks against each one of the trips intervals and sees if one is within radius R and then stores the shortest on.

答: Take advantage of any opportunity to break out of a for loop once the result is known.  For example, at the end of the for line loop you check to see if successful_single == len(coords_line).  But that will happen any time the statement if loop_count != 0 is False, because at that point successful_single will not get incremented; you know that its value will never reach len(coords_line).  So you could break out of the for item loop right there - you already know it's not a "successful_trip."  There may be other situations like this.

Title: Speeding Up Python Code Time

Body:
start = time.time()
import csv
f = open('Speed_Test.csv','r+')
coordReader = csv.reader(f, delimiter = ',')
count = -1
successful_trip = 0
trips = 0

for line in coordReader:
    successful_single = 0
    count += 1
    R = interval*0.30
    if count == 0:
        continue
    if 26 < float(line[0]) < 48.7537144 and 26 < float(line[2]) <   48.7537144 and -124.6521017 < float(line[1]) < -68 and -124.6521017 < float(line[3]) < -68:
        y2,x2,y1,x1 = convertCoordinates(float(line[0]),float(line[1]),float(line[2]),float(line[3]))
        coords_line,interval = main(y1,x1,y2,x2)

        for item in coords_line:
            loop_count = 0
            r = 0
            min_dist = 10000

            for i in range(len(df)):
                dist = math.sqrt((item[1]-df.iloc[i,0])**2 + (item[0]-df.iloc[i,1])**2)
                if dist < R:
                    loop_count += 1
                    if dist < min_dist:
                        min_dist = dist
                        r = i
            if loop_count != 0:
                successful_single += 1
                df.iloc[r,2] += 1

        trips += 1
        if successful_single == (len(coords_line)):
            successful_trip += 1

end = time.time()
print('Percent Successful:',successful_trip/trips)
print((end - start))

I have this code and explaining it would be extremely time consuming but it doesn't run as fast as I need it to in order to be able to compute as much as I'd like. Is there anything anyone sees off the bat that I could do to speed the process up? Any suggestions would be greatly appreciated.

In essence it reads in 2 lat and long coordinates and changes them to a cartesian coordinate and then goes through every coordinate along the path from on origin coordinate to the destination coordinate in certain interval lengths depending on distance. As it is doing this though there is a data frame (df) with 300+ coordinate locations that it checks against each one of the trips intervals and sees if one is within radius R and then stores the shortest on.


问:
Xcode: Remove reference to files not showing up as option
I meant to add one file to my project and I accidentally added the entire directory.

Yikes!

I realized it immediately and tried to hit cancel to no avail.  The entire directory which contains lots of other Xcode projects got added to my xcode project.

I now want to remove all those files.  Normally, you delete and it gives the option to remove reference or move to trash.  In this case I don't want to move to trash as I don't want to delete the underlying files, only their presence in this project.  However, it is not giving me the option to remove references.  It is only giving the option to move to trash or cancel.

Can anyone suggest why I am not getting option to remove reference?  Or alternatively, can you suggest how to remove all these files without moving them to trash.

Thanks in advance for any suggestions.

答:
The project sub folder you might not be getting the remove reference option since there is no location for it in file inspector, try doing the delete operation on that root folder(of extra files added).

Still if you wont get option here are couple of options:

You can discard your local changes, if your repo is GIT and you are using SourceTree just reset your files or discard also you can do that from XCode > Source Control > Discard All changes

Select that folder in project and in the file inspector track the file path and take backup and then perform delete action with Move to trash option

Or if you don't have further option and not other way to fix, check out the code in new directory and trash the current one.


问:
How should I handle Facebook logins in my API [CakePHP 3]
I have an API with CakePHP and I want to handle login with Facebook, how should I go about this? I though about just creating a new user like usual with the information Facebook gives, but is there something else I can do? Users have to use a token generated by my app to make requests to my API. </p>

答: Take a look at this plugin https://github.com/ADmad/CakePHP-HybridAuth. It makes Facebook login super easy to integrate.</p>


问:
How to implementing angular-formly template for custom ui/css library?
I want to implementing angular-formly custom template for my application. I don't want to use bootstrap template because I have a custom UI/css library. How do I implement custom template? Do I get angular-formly-templates-vanilla or angular-formly-templates-bootstrap and customize it to my need. Currently I am implementing template using separate html files as below but I want to reuse template so is this the best solution?

```<code>  angular
        .module('myApp').run(function(formlyConfig) {
      formlyConfig.setType([{
        name: 'input',
        templateUrl: 'input.html',
        overwriteOk: true
      },
      {
        name: 'select',
        templateUrl: 'select.html',
        overwriteOk: true
      }]);
    });
</code>```

Html document

input.html

```<code><div class="custom-group">
   <label class="form-label" for="{{options.key}}">
   {{to.label}}
   </label>
   <input id="{{options.key}}" ng-model="model[options.key]" type="text">
</div>
</code>```

select.html

```<code><div class="custom-group">
   <label class="form-label" for="{{options.key}}">{{to.label}}</label>
   <span class="form-select-span">
   <select class="form-control" id="{{options.key}}" ng-model="model[options.key]"
      ng-options="option.value as option.name group by option.group for option in options.templateOptions.options">
   </select>
   </span>
</div>
</code>```

答:
Why don't you simply give it a className and then just overwrite the CSS?
You are attempting to re-invent the wheel when it doesn't need to be done.</p>

Body:
I want to implementing angular-formly custom template for my application. I don't want to use bootstrap template because I have a custom UI/css library. How do I implement custom template? Do I get angular-formly-templates-vanilla or angular-formly-templates-bootstrap and customize it to my need. Currently I am implementing template using separate html files as below but I want to reuse template so is this the best solution?

  angular
        .module('myApp').run(function(formlyConfig) {
      formlyConfig.setType([{
        name: 'input',
        templateUrl: 'input.html',
        overwriteOk: true
      },
      {
        name: 'select',
        templateUrl: 'select.html',
        overwriteOk: true
      }]);
    });

Html document

input.html

   {{to.label}}

   <input id="{{options.key}}" ng-model="model[options.key]" type="text">

select.html

   {{to.label}}

   <select class="form-control" id="{{options.key}}" ng-model="model[options.key]"
      ng-options="option.value as option.name group by option.group for option in options.templateOptions.options">
   </select>


问:
How do I use the value of a column in a csv to determine value of another column in the same csv using bash?
I have a large csv containing database information that I would like to update.

I would like to use the values in the email column (column 1) to determine the value of the segment column (column 4).

For example, if the email contains 'nhs.net' then the segment column should read 'Health - NHS'.

Currently the segment column reads 'Unknown Specialism' and I'm not sure how to overwrite this value using bash based on if the value in another column is true.

Example

zoe.russell@nhs.net, zoe, russell, Unknown Specialism

will become:

zoe.russell@nhs.net, zoe, russell, Health - NHS

I have this so far...(my first bash script, and first q on here)

```<code>#!/bin/bash

echo 'enter the email domain you are searching for in the email field'
read email
echo 'please enter the file you wish to search'
read file
echo 'ok looking for' $email 'in' $file
echo ...
# cat $file | grep -E -i $email

x=$(cat $file | grep -E -i $email | wc -l)
echo 'ok' $x 'email address were found in' $file
echo 'here is a sample of the first 10 lines in the segment column'
cat us.tmp | cut -d ',' -f10 | head -10

echo 'please enter the segment name you want to replace these with'
read new
echo value will be replaced with $new
</code>```

答:
In awk using another file for the segment column replacements:

```<code>$ cat repl.txt
nhs.net, Health - NHS
</code>```

The code:

```<code>$ awk '
BEGIN { FS=OFS="," }                            # delimiters are: ,
NR==FNR { a[$1]=$2; next }                      # read replacements in a hash
split($1,t,"@") && (t[2] in a) {                # get the domain name and use is
    $NF=a[t[2]]                                 # as reference to a hash
}
1' repl.txt file                                # 1 is the print command
zoe.russell@nhs.net, zoe, russell, Health - NHS
</code>```

Body:
I have a large csv containing database information that I would like to update.

I would like to use the values in the email column (column 1) to determine the value of the segment column (column 4).

For example, if the email contains 'nhs.net' then the segment column should read 'Health - NHS'.

Currently the segment column reads 'Unknown Specialism' and I'm not sure how to overwrite this value using bash based on if the value in another column is true.

Example

zoe.russell@nhs.net, zoe, russell, Unknown Specialism

will become:

zoe.russell@nhs.net, zoe, russell, Health - NHS

I have this so far...(my first bash script, and first q on here)

#!/bin/bash

echo 'enter the email domain you are searching for in the email field'
read email
echo 'please enter the file you wish to search'
read file
echo 'ok looking for' $email 'in' $file
echo ...
# cat $file | grep -E -i $email

x=$(cat $file | grep -E -i $email | wc -l)
echo 'ok' $x 'email address were found in' $file
echo 'here is a sample of the first 10 lines in the segment column'
cat us.tmp | cut -d ',' -f10 | head -10

echo 'please enter the segment name you want to replace these with'
read new
echo value will be replaced with $new

Body:
In awk using another file for the segment column replacements:

$ cat repl.txt
nhs.net, Health - NHS

The code:

$ awk '
BEGIN { FS=OFS="," }                            # delimiters are: ,
NR==FNR { a[$1]=$2; next }                      # read replacements in a hash
split($1,t,"@") && (t[2] in a) {                # get the domain name and use is
    $NF=a[t[2]]                                 # as reference to a hash
}
1' repl.txt file                                # 1 is the print command
zoe.russell@nhs.net, zoe, russell, Health - NHS


问:
Splitting a string into groups of either a number and a letter or just a single letter
I'm trying to decode a string that looks like this "2a3bc" into "aabbbc" in Python. So the first thing I need to do is to split it up into a list with groups that make sense. In other words: ['2a','3b','c'].

Essentially, match either (1) a number and a letter or (2) just a letter.

I've got this:

```<code>re.findall('\d+\S|\s', '2a3bc')
</code>```

and it returns:

```<code>['2a', '3b']
</code>```

So it's actually missing the c.

Perhaps my regex skills is lacking here, any help is appreciated.

答:
Your current expression could work with a small bugfix: \S is non-whitespace, while \s is whitespace. You're looking for non-whitespace in both cases, so you shouldn't use \s anywhere:

```<code>>>> re.findall(r'\d+\S|\S', '2a3bc')
['2a', '3b', 'c']
</code>```

However, this expression could be shorter: instead of using + for one or more digits, use * for zero or more, since the group might not be preceded by any digits, and you can then get rid of the alternation.

```<code>>>> re.findall(r'\d*\S', '2a3bc')
['2a', '3b', 'c']
</code>```

Again, though, note that \S is simply non-whitespace - that includes letters, digits, and even punctuation. \D, non-digits, has a similar problem: it excludes digits, but includes punctuation. The shortest, clearest regex for this, then, would replace the \S with \w, which indicates alphanumeric characters:

```<code>>>> re.findall(r'\d*\w', '2a3bc')
['2a', '3b', 'c']
</code>```

Since the other character class in the group is already digits, this particular \w will only match letters.

Body:
I'm trying to decode a string that looks like this "2a3bc" into "aabbbc" in Python. So the first thing I need to do is to split it up into a list with groups that make sense. In other words: ['2a','3b','c'].

Essentially, match either (1) a number and a letter or (2) just a letter.

I've got this:

re.findall('\d+\S|\s', '2a3bc')

and it returns:

['2a', '3b']

So it's actually missing the c.

Perhaps my regex skills is lacking here, any help is appreciated.

Body:
Your current expression could work with a small bugfix: \S is non-whitespace, while \s is whitespace. You're looking for non-whitespace in both cases, so you shouldn't use \s anywhere:

>>> re.findall(r'\d+\S|\S', '2a3bc')
['2a', '3b', 'c']

However, this expression could be shorter: instead of using + for one or more digits, use * for zero or more, since the group might not be preceded by any digits, and you can then get rid of the alternation.

>>> re.findall(r'\d*\S', '2a3bc')
['2a', '3b', 'c']

Again, though, note that \S is simply non-whitespace - that includes letters, digits, and even punctuation. \D, non-digits, has a similar problem: it excludes digits, but includes punctuation. The shortest, clearest regex for this, then, would replace the \S with \w, which indicates alphanumeric characters:

>>> re.findall(r'\d*\w', '2a3bc')
['2a', '3b', 'c']

Since the other character class in the group is already digits, this particular \w will only match letters.


问:
Hierarchy Climbing and Descending Unity
I have the following hierarchy on my Player prefab for what will be a very simple multiplayer shooter.

It works this way, the Controller object has the scripts that deal with player input, the PlayerShip object has all of the turning, moving, shooting scripts etc and the Camera is just as it sounds, a camera with a few scripts on it for moving it about.

When a new Player is instantiated the Control script needs to locate its relevant PlayerShip, simple enough.

This can be achieved using the following code:

```<code>_playerShip = gameObject.transform.parent.gameObject.transform.FindChild("PlayerShip").GetComponent<PlayerShip>();
</code>```

Which works fine, the only thing is, to me that looks very clunky, inelegant and brittle. Consequently, I'm wondering if there's a better, more efficient, less ugly way of achieving the same thing?

答:
If this isn't being called every frame consider this:

```<code>_playerShip = GameObject.Find("PlayerShip").GetComponent>PlayerShip>();
</code>```

Read more about the above here: https://docs.unity3d.com/ScriptReference/GameObject.Find.html

If it is being called every frame look in  to this:
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html

Either one should be easier to understand.

EDIT: I may have misunderstood. Would rearranging the hierarchy so that controller is a parent of playerShip? Then you should be able to just look at the child, rather than going through a parent to a sibling.

Title: Hierarchy Climbing and Descending Unity

Body:
I have the following hierarchy on my Player prefab for what will be a very simple multiplayer shooter.

It works this way, the Controller object has the scripts that deal with player input, the PlayerShip object has all of the turning, moving, shooting scripts etc and the Camera is just as it sounds, a camera with a few scripts on it for moving it about.

When a new Player is instantiated the Control script needs to locate its relevant PlayerShip, simple enough.

This can be achieved using the following code:

_playerShip = gameObject.transform.parent.gameObject.transform.FindChild("PlayerShip").GetComponent<PlayerShip>();

Which works fine, the only thing is, to me that looks very clunky, inelegant and brittle. Consequently, I'm wondering if there's a better, more efficient, less ugly way of achieving the same thing?

Body:
If this isn't being called every frame consider this:

_playerShip = GameObject.Find("PlayerShip").GetComponent>PlayerShip>();

Read more about the above here: https://docs.unity3d.com/ScriptReference/GameObject.Find.html

If it is being called every frame look in  to this:
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html

Either one should be easier to understand.

EDIT: I may have misunderstood. Would rearranging the hierarchy so that controller is a parent of playerShip? Then you should be able to just look at the child, rather than going through a parent to a sibling.


问:
What is the best way to get the Date object for the timestamp 1224642020?
In Ruby, what's the best way to get the Date object for the timestamp 1224642020?

答:
Ruby's Time class has an at method that will do exactly what you need. If you're in Rails, ActiveSupport adds a *to_date* method that will convert them all and get you an instance of Date.

```<code>date = Time.at(1224642020).to_date
</code>```

Otherwise, you can convert it by using strftime and Date's parse

```<code>date = Date.parse(Time.at(1224642020).strftime('%Y/%m/%d'))
</code>```

Body:
Ruby's Time class has an at method that will do exactly what you need. If you're in Rails, ActiveSupport adds a *to_date* method that will convert them all and get you an instance of Date.

date = Time.at(1224642020).to_date

Otherwise, you can convert it by using strftime and Date's parse

date = Date.parse(Time.at(1224642020).strftime('%Y/%m/%d'))


问:
Program closes after entering two numbers
```<code>#include <iostream>

int main() {

    std::cout << "Please enter two numbers" << std::endl;

    int v1, v2 = 0;

    std::cin >> v1 >> v2;
    std::cout << "The sum of " << v1 << " and " << v2
        << " is " << v1 + v2 << std::endl;

    std::cin.get();

    return 0;
}
</code>```

I added the cin.get() so that I could see the result in the terminal before it closes, but for some reason the program still closes immediately after printing the result. Is there a better way to prevent the window from closing immediately after running the code?

答:
```<code>std::cin >> v1 >> v2;
</code>```

At this point you type in, for example:

```<code>4 5 <Enter>
</code>```

(with the <Enter> key generating a newline character).

The first >> parses "4".

The second >> parses "5".

And your call to get() reads the newline character, '\n'.

And then your program immediately terminates.

Moral of the story

Use std::getline() to read a line of text entered interactively, from a terminal, rather than the >> operator. That's what std::getline() is for.

Body:
#include <iostream>

int main() {

    std::cout << "Please enter two numbers" << std::endl;

    int v1, v2 = 0;

    std::cin >> v1 >> v2;
    std::cout << "The sum of " << v1 << " and " << v2
        << " is " << v1 + v2 << std::endl;

    std::cin.get();

    return 0;
}

I added the cin.get() so that I could see the result in the terminal before it closes, but for some reason the program still closes immediately after printing the result. Is there a better way to prevent the window from closing immediately after running the code?

Body:
std::cin >> v1 >> v2;

At this point you type in, for example:

4 5 <Enter>

(with the <Enter> key generating a newline character).

The first >> parses "4".

The second >> parses "5".

And your call to get() reads the newline character, '\n'.

And then your program immediately terminates.

Moral of the story

Use std::getline() to read a line of text entered interactively, from a terminal, rather than the >> operator. That's what std::getline() is for.


问:
Using Matlab and urlread to read data from https?
I am trying to download a https page using url read:

str=urlread('https://funds.barclaysstockbrokers.co.uk/clients/bsl/search_factsheet_summary.aspx?code=B0XWN14')

Unfortunately, I get an error :

```<code>Error downloading URL. Your network connection may be down or your proxy settings improperly configured.
</code>```

I tried using urlread2 (http://www.mathworks.co.uk/matlabcentral/fileexchange/35693-urlread2/content/urlread2.m)

but that gives me this error:

```<code>Response stream is undefined
 below is a Java Error dump (truncated):
??? Error using ==> urlread2 at 217
Java exception occurred:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

What do I need to do?

答:
After matlab 2014b you can use:

```<code>DATA = webread(URL)
</code>```

This new API does not have all the issues urlread command has.

Body:
I am trying to download a https page using url read:

str=urlread('https://funds.barclaysstockbrokers.co.uk/clients/bsl/search_factsheet_summary.aspx?code=B0XWN14')

Unfortunately, I get an error :

Error downloading URL. Your network connection may be down or your proxy settings improperly configured.

I tried using urlread2 (http://www.mathworks.co.uk/matlabcentral/fileexchange/35693-urlread2/content/urlread2.m)

but that gives me this error:

Response stream is undefined
 below is a Java Error dump (truncated):
??? Error using ==> urlread2 at 217
Java exception occurred:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

What do I need to do?

Body:
After matlab 2014b you can use:

DATA = webread(URL)

This new API does not have all the issues urlread command has.


问:
Browser is blocking my jquery
So I'm not sure why but I get an error message from Chrome.

Error message:

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-TakXxMuCq+J+ccgIY6WUXR+xy3/BdgRbqG7Y1mNRWJQ='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

jQuery:

```<code><script type="text/javascript">
  $( document ).ready(function() {

    $.ajax({
      type:'GET',
      url:'http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=440&count=3&maxlength=300&format=json'
      success: function(data){
        console.log('success',data);
      }
    });
  });
</script>
</code>```

Sorry if this is a duplicate question.

I just had a hard time finding the answer to my problem.

But can someone explain why I am getting the error message that I am getting?

I want to give some extra information, so that you may understand my situation.

I was writing an app in HTML.

All the files used in the HTML other then the JSON are all from my machine.

I did not run them from any server including xampp. I simply double clicked my HTML file.

Title: Browser is blocking my jquery

Body:
So I'm not sure why but I get an error message from Chrome.

Error message:

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-TakXxMuCq+J+ccgIY6WUXR+xy3/BdgRbqG7Y1mNRWJQ='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

jQuery:

Sorry if this is a duplicate question.

I just had a hard time finding the answer to my problem.

But can someone explain why I am getting the error message that I am getting?

I want to give some extra information, so that you may understand my situation.

I was writing an app in HTML.

All the files used in the HTML other then the JSON are all from my machine.

I did not run them from any server including xampp. I simply double clicked my HTML file.

Body:
Are you writing a Chrome extension? It's not immediately clear from your question, but that's where I would expect to find this error message.

Inline script tags are not executed by extensions. The Google Content Security Policy pages state:

Inline JavaScript will not be executed. This restriction bans both
  inline <script> blocks and inline event handlers (e.g. <button
  onclick="...">).

The first restriction wipes out a huge class of cross-site scripting
  attacks by making it impossible for you to accidentally execute script
  provided by a malicious third-party. It does, however, require you to
  write your code with a clean separation between content and behavior
  (which you should of course do anyway, right?).

There is a way to relax this policy though

As of Chrome 46, inline scripts can be whitelisted by specifying the
  base64-encoded hash of the source code in the policy. This hash must
  be prefixed by the used hash algorithm (sha256, sha384 or sha512). See
  Hash usage for <script> elements for an example.