问:
The Little Schemer: `lat?` without `cond`?
One of the first questions in the second chapter of The Little Schemer (4th edition) asks the reader to write the function lat?, where (lat? l) returns true if l is a list of atoms.

It goes on to say:

You were not expected to be able to do this yet, because you are still missing some ingredients.

But I'm familiar with recursion, and the definition of atom? earlier in the book already introduced and (further implying the existence of or), so I gave it a shot anyway: (repl)

(define lat?
  (lambda (l)
    (or
      (null? l)
      (and
        (atom? (car l))
        (lat? (cdr l))))))
```

<p>On the next page, the book introduces the <code>cond</code> operator to enable this definition of <code>lat?</code>:</p>

<pre class="lang-lisp prettyprint-override"><code>(define lat?
  (lambda (l)
    (cond
      ((null? l) #t)
      ((atom? (car l)) (lat? (cdr l)))
      (else #f))))
</code>```

Is there any significant difference between these two implementations?

答:
cond is a special form, that takes (roughly) the form

```<code>(cond
  ((test-expression) (then-expression))
  ((test-expression2) (then-expression2))
  (else
   (then-expression3)))
</code>```

Its semantics is that it will evaluate the test-expressions in order, and for the first one that it finds to evaluate to #t (the true value), then it will evaluate its associated then-expression and return its value. If all the test-expressions evaluate to #f (the false value), and an else clause is present, then it will evaluate its associated then-expression3 in this case, and return its value.

So as far as semantics are concerned, the two implementations are equivalent. Their only difference might be that afaik the cond version is considered more idiomatic in the Scheme community.

Body:
One of the first questions in the second chapter of The Little Schemer (4th edition) asks the reader to write the function lat?, where (lat? l) returns true if l is a list of atoms.

It goes on to say:

You were not expected to be able to do this yet, because you are still missing some ingredients.

But I'm familiar with recursion, and the definition of atom? earlier in the book already introduced and (further implying the existence of or), so I gave it a shot anyway: (repl)

(define lat?
  (lambda (l)
    (or
      (null? l)
      (and
        (atom? (car l))
        (lat? (cdr l))))))

On the next page, the book introduces the cond operator to enable this definition of lat?:

(define lat?
  (lambda (l)
    (cond
      ((null? l) #t)
      ((atom? (car l)) (lat? (cdr l)))
      (else #f))))

Is there any significant difference between these two implementations?

Body:
cond is a special form, that takes (roughly) the form

(cond
  ((test-expression) (then-expression))
  ((test-expression2) (then-expression2))
  (else
   (then-expression3)))

Its semantics is that it will evaluate the test-expressions in order, and for the first one that it finds to evaluate to #t (the true value), then it will evaluate its associated then-expression and return its value. If all the test-expressions evaluate to #f (the false value), and an else clause is present, then it will evaluate its associated then-expression3 in this case, and return its value.

So as far as semantics are concerned, the two implementations are equivalent. Their only difference might be that afaik the cond version is considered more idiomatic in the Scheme community.


来源: stackexchange

问:
How to read this from file and get each value alone
I have this text file and I need to extract it to a Java program to determine array sizes and its values I can read each line alone but I can't get the value for lines that contains many numbers. Plus, how to count element in the third line.( 0 2 ) </p>

```<code>4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3
</code>```

<p>this code that I'm using: </p>

```<code> List<Integer> list = new ArrayList<Integer>();
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
        BufferedReader reader = null;
         List<Double> ints = new ArrayList<Double>();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (text.length() == 1) {
                    list.add(Integer.parseInt(text));
                } else {

                    String[] strs = text.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        ints.add(Double.parseDouble(strs[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }

//print out the list
        System.out.println(list);

        System.out.println(ints);
</code>```

答:
Try something like</p>

```<code>public static void main(String[] args) {
        List<Double> list = new ArrayList<>();
        File file = new File("text.txt");
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                String[] str = text.split(" ");
                for (int i = 0; i<str.length; i++) {
                    if(str[i].trim().length() > 0) {
                        list.add(Double.parseDouble(str[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }

//print out the list
        System.out.println(list);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this text file and I need to extract it to a Java program to determine array sizes and its values I can read each line alone but I can't get the value for lines that contains many numbers. Plus, how to count element in the third line.( 0 2 )

4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3

this code that I'm using:

 List<Integer> list = new ArrayList<Integer>();
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
        BufferedReader reader = null;
         List<Double> ints = new ArrayList<Double>();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (text.length() == 1) {
                    list.add(Integer.parseInt(text));
                } else {

                    String[] strs = text.trim().split("\\s+");

                    for (int i = 0; i < strs.length; i++) {
                        ints.add(Double.parseDouble(strs[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {

            }
        }

//print out the list
        System.out.println(list);

        System.out.println(ints);

Body:
Try something like

public static void main(String[] args) {
        List<Double> list = new ArrayList<>();
        File file = new File("text.txt");
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                String[] str = text.split(" ");
                for (int i = 0; i<str.length; i++) {
                    if(str[i].trim().length() > 0) {
                        list.add(Double.parseDouble(str[i]));
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }

//print out the list
        System.out.println(list);
    }


问:
how to set an empty initial value for react-date-picker?
I have a redux form which uses react-date-picker as it's date component, now on opening the form in edit mode, there in some cases the date field doesn't have a value or it has a blank (" ") value. Now in this case if my react-date-picker component doesn't find any suitable value to parse it shows "invalid date" on component, i tried with passing null, or by setting a check if there isn't any date or if it is blank pass undefined or null, i have googled it a lot but didn't find any suitable answer. My code looks like this

my custom date-picker component in my redux form :

import { _dateField, } from '../../../containers/reduxFormFields/formFields';

<Row>
          <Col md={6}>
           <FormGroup>
            <ControlLabel bsClass="">Actual Start Date</ControlLabel>

             <Field name="actualStartDate" component={_dateField} className="form-control" formType="edit" defaultValue={moment(this.props.initialValues.actualStartDate)} />

           </FormGroup>
          </Col>
          <Col md={6}>
           <FormGroup>
            <ControlLabel bsClass="">Actual End Date</ControlLabel>

             <Field name="actualEndDate" component={_dateField} className="form-control" formType="edit" defaultValue={moment(this.props.initialValues.actualEndDate)} />

           </FormGroup>
          </Col>
         </Row>```
</div>
</div>
</p>

<p>and my date-picker component looks like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>export const _dateField = ({ input, placeholder, defaultValue, className, formType,disabledValue, meta: { touched, error } }) => {console.log('values');console.log(defaultValue)
switch (formType) {
  case "edit":
   return (
    <div className="dateTimeSdiv">
     <DateField className={(touched && error) ? className + " error" : className} expandOnFocus={false} dateFormat="YYYY-MM-DD HH:mm:ss" updateOnDateClick forceValidDate defaultValue={defaultValue}  minDate={moment()} disabled = {disabledValue}>
      <DatePicker {...input} selected={input.value ? moment(input.value) : null} navigation locale="en" forceValidDate highlightWeekends highlightToday weekNumbers={false} weekStartDay={1} todayButton={false}></DatePicker>
     </DateField>
     {touched && error && <span> {error} </span>}
    </div>
   );
  case "create":
   return (
    <div className="dateTimeSdiv">
     <DateField className={(touched && error) ? className + " error" : className} expandOnFocus={false} dateFormat="YYYY-MM-DD HH:mm:ss" updateOnDateClick forceValidDate defaultValue={moment()}  minDate={moment()} disabled = {disabledValue}>
      <DatePicker {...input} selected={input.value ? moment(input.value) : null} navigation locale="en" forceValidDate highlightWeekends highlightToday weekNumbers={false} weekStartDay={1} todayButton={false}></DatePicker>
     </DateField>
     {touched && error && <span> {error} </span>}
    </div>
   );
 }
};</code>```

there are two seprate component which i am using for edit and create from each.
any help will be appreciable.

答:
find some workaround here, just changed my code where i was passing my date (coming from DB) to react-date-component like this

defaultValue = {moment(this.props.initialValues.actualStartDate)}```
</div>
</div>
</p>

<p>now changed code to </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> defaultValue = {this.props.initialValues.actualStartDate}</code>```

defaultValue property of react-date-picker was not taking the value as an moment object rather it worked when passed as string only.

Body:
I have a redux form which uses react-date-picker as it's date component, now on opening the form in edit mode, there in some cases the date field doesn't have a value or it has a blank (" ") value. Now in this case if my react-date-picker component doesn't find any suitable value to parse it shows "invalid date" on component, i tried with passing null, or by setting a check if there isn't any date or if it is blank pass undefined or null, i have googled it a lot but didn't find any suitable answer. My code looks like this

my custom date-picker component in my redux form :

import { _dateField, } from '../../../containers/reduxFormFields/formFields';

<Row>
          <Col md={6}>
           <FormGroup>
            <ControlLabel bsClass="">Actual Start Date</ControlLabel>

             <Field name="actualStartDate" component={_dateField} className="form-control" formType="edit" defaultValue={moment(this.props.initialValues.actualStartDate)} />

           </FormGroup>
          </Col>
          <Col md={6}>
           <FormGroup>
            <ControlLabel bsClass="">Actual End Date</ControlLabel>

             <Field name="actualEndDate" component={_dateField} className="form-control" formType="edit" defaultValue={moment(this.props.initialValues.actualEndDate)} />

           </FormGroup>
          </Col>
         </Row>

and my date-picker component looks like this:

export const _dateField = ({ input, placeholder, defaultValue, className, formType,disabledValue, meta: { touched, error } }) => {console.log('values');console.log(defaultValue)
switch (formType) {
  case "edit":
   return (

     <DateField className={(touched && error) ? className + " error" : className} expandOnFocus={false} dateFormat="YYYY-MM-DD HH:mm:ss" updateOnDateClick forceValidDate defaultValue={defaultValue}  minDate={moment()} disabled = {disabledValue}>
      <DatePicker {...input} selected={input.value ? moment(input.value) : null} navigation locale="en" forceValidDate highlightWeekends highlightToday weekNumbers={false} weekStartDay={1} todayButton={false}></DatePicker>
     </DateField>
     {touched && error &&  {error} }

   );
  case "create":
   return (

     <DateField className={(touched && error) ? className + " error" : className} expandOnFocus={false} dateFormat="YYYY-MM-DD HH:mm:ss" updateOnDateClick forceValidDate defaultValue={moment()}  minDate={moment()} disabled = {disabledValue}>
      <DatePicker {...input} selected={input.value ? moment(input.value) : null} navigation locale="en" forceValidDate highlightWeekends highlightToday weekNumbers={false} weekStartDay={1} todayButton={false}></DatePicker>
     </DateField>
     {touched && error &&  {error} }

   );
 }
};

there are two seprate component which i am using for edit and create from each.
any help will be appreciable.

Body:
find some workaround here, just changed my code where i was passing my date (coming from DB) to react-date-component like this

defaultValue = {moment(this.props.initialValues.actualStartDate)}

now changed code to

 defaultValue = {this.props.initialValues.actualStartDate}

defaultValue property of react-date-picker was not taking the value as an moment object rather it worked when passed as string only.


问:
An SPI class of type org.apache.lucene.codecs.Codec with name 'Lucene54' does not exist
With lucene-core-5.5.2 i am facing problem a in weblogic server. standalone search application works but when i deploy as WEB APP it is failing with below error

```<code>Exception type is 'java.lang.ExceptionInInitializerError'. Runtime error: java.lang.IllegalArgumentException: An SPI class of type org.apache.lucene.codecs.Codec with name 'Lucene54' does not exist. You need to add the corresponding JAR file supporting this SPI to your classpath. The current classpath supports the following names: []
</code>```

I tried creating folder structure under classes/ as META-INF/services/ added all files from lucene-core-5.5.2.jar META-INF\services\ directory also created jar file for META-INF\services\ and added in classpath but it doesn't recognize META-INF/services to load SPI

Any help would be really appreciated.

答:
I added the below code into configuration tags

```<code><transformers>
    <transformer  implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
        <resource>META-INF/services/org.apache.lucene.codecs.Codec</resource>
        <resource>META-INF/services/org.apache.lucene.codecs.PostingsFormat</resource>
    </transformer>
</transformers>
</code>```

And also I add lucene-core dependency at the top of the dependencies tag

```<code><dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-core</artifactId>
    <version>5.5.0</version>
</dependency>
</code>```

Body:
With lucene-core-5.5.2 i am facing problem a in weblogic server. standalone search application works but when i deploy as WEB APP it is failing with below error

Exception type is 'java.lang.ExceptionInInitializerError'. Runtime error: java.lang.IllegalArgumentException: An SPI class of type org.apache.lucene.codecs.Codec with name 'Lucene54' does not exist. You need to add the corresponding JAR file supporting this SPI to your classpath. The current classpath supports the following names: []

I tried creating folder structure under classes/ as META-INF/services/ added all files from lucene-core-5.5.2.jar META-INF\services\ directory also created jar file for META-INF\services\ and added in classpath but it doesn't recognize META-INF/services to load SPI

Any help would be really appreciated.

Body:
I added the below code into configuration tags

<transformers>
    <transformer  implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
        <resource>META-INF/services/org.apache.lucene.codecs.Codec</resource>
        <resource>META-INF/services/org.apache.lucene.codecs.PostingsFormat</resource>
    </transformer>
</transformers>

And also I add lucene-core dependency at the top of the dependencies tag

<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-core</artifactId>
    <version>5.5.0</version>
</dependency>

ContentLicense: CC BY-SA 4.0


问:
In C, when would type casting a char to an integer not return a value between 0 and 127?
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

```<code>char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;
</code>```

To mark character c as seen. Of course this relies on

```<code>(int) c
</code>```

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?

答:
It works with all 7-bit ascii characters. Other characters, like german umlauts, would be translated to a negative number, with the appropriate consequences for your algorithm.

You're on the safe side if you use unsigned char and make the array 256 entries wide.

ContentLicense: CC BY-SA 2.5

Body:
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;

To mark character c as seen. Of course this relies on

(int) c

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?


问:
Google App Engine Python - Pass ProjectID to NDB Client Library?
I am new with the Google App Engine. I am building an app in Standard Environment and would like to know how to pass the ProjectID to the Python NDB Client Library, in the same way that:

```<code># Imports the Google Cloud client library
from google.cloud import datastore

# Instantiates a client
datastore_client = datastore.Client('my_project_id')
</code>```

but using the ndb:

```<code>from google.appengine.ext import ndb
</code>```

Is there any related method in the library or is it just possible to include in the .yaml file?:

```<code>application: "my_project_id"
version: 1
</code>```

答:
If you are using GAE standard then you don't need to use from google.cloud import datastore.  That library allows people to access the datastore from other environments, such as GCE.  Datastore is built in to GAE standard through NDB.

For GAE standard, you shouldn't need the application name anywhere in your code, not even in the app.yaml file.  You specify the app name when you deploy with the gcloud command.

The old GUI tool need the app name in app.yaml but the current gcloud tools don't use it anymore.

Body:
I am new with the Google App Engine. I am building an app in Standard Environment and would like to know how to pass the ProjectID to the Python NDB Client Library, in the same way that:

# Imports the Google Cloud client library
from google.cloud import datastore

# Instantiates a client
datastore_client = datastore.Client('my_project_id')

but using the ndb:

from google.appengine.ext import ndb

Is there any related method in the library or is it just possible to include in the .yaml file?:

application: "my_project_id"
version: 1


问:
VBA keep changes in comment box
Wright now, I am keeping the last changes of data from a cell, in a comment, with this function:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    val_before = Target.Value

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Count > 1 Then
        MsgBox Target.Count & " cells were changed!"
        Exit Sub
    End If

    If Target.Comment Is Nothing Then
        Target.AddComment
        existingcomment = ""
    Else
        existingcomment = Target.Comment.Text & vbLf & vbLf
    End If

    Target.Comment.Text Text:=Format(Now(), "DD.MM.YYYY hh:mm") & ":" & vbLf & Environ("UserName") & _
        " changed " & val_before & Target.Address & " from:" & vbLf & """" & val_before & _
        """" & vbLf & "to:" & vbLf & """" & Target.Value & """"

End Sub
</code>```

original answer here: VBA Last Change Method

But I am trying to change it, to keep a maximum of 5 history changes in the comment box, and when a new change is made, to delete the oldest one. And I was thinking to do the following operations:

'count the : (double dots-from the time), when is bigger then 5, compare the date and time of the changes, delete the oldest one and log the new one(6th) for example.

Has anyone a better idea? I am new to VBA and also to programming.

答:
So, this is my working version:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

   If Range("A" & Target.Row).Value = "" Then GoTo EndeSub
   If Target.Row <= 2 Then GoTo EndeSub
   If Not Intersect(Range("C:JA"), Target) Is Nothing Then
     On Error GoTo EndeSub
     Application.EnableEvents = False
     Range("B" & Target.Row) = Now
   End If

    Application.Volatile
    Dim CommentBox As Object
    Set CommentBox = Range("B" & Target.Row).Comment
    Dim CommentString As String

    If Not CommentBox Is Nothing Then
        If CommentBox.Text <> "" Then
            CommentString = CommentBox.Text
            Range("B" & Target.Row).Comment.Delete
        End If
    Else
        CommentString = ""
    End If

    Dim CommentTemp As String
    CommentTemp = CommentString
    Dim LastDoubleDotPosition As Integer
    LastDoubleDotPosition = 0
    Dim LongestName As Integer
    LongestName = 0

    If InStr(CommentTemp, ":") > 0 Then StillTwoDoubleDots = True

    Do While InStr(CommentTemp, ":") > 0

        If InStr(CommentTemp, ":") > LongestName Then LongestName = InStr(CommentTemp, ":")
        CommentTemp = Right(CommentTemp, Len(CommentTemp) - InStr(CommentTemp, ":"))

    Loop

    count = CountChr(CommentString, ":")

    If count >= 5 Then

        LastDoubleDotPosition = Len(CommentString) - Len(CommentTemp) - 1
        CommentString = Left(CommentString, LastDoubleDotPosition - 13)

    End If

    'insert comment
    Dim FinalComment As String
    FinalComment = Format(Now(), "DD.MM.YYYY hh:mm") & " " & "by" & " " & Application.UserName & vbCrLf & CommentString 'newComment and the oldcomment
    Range("B" & Target.Row).AddComment FinalComment

    Set CommentBox = Range("B" & Target.Row).Comment

    LongestName = LongestName * 5
    If LongestName < 150 Then LongestName = 150

    With CommentBox
        .Shape.Height = 60
        .Shape.Width = LongestName
    End With

EndeSub:
    Application.EnableEvents = True

End Sub

'counter
Public Function CountChr(Expression As String, Character As String) As Long

    Dim Result As Long
    Dim Parts() As String
    Parts = Split(Expression, Character)
    Result = UBound(Parts, 1)
    If (Result = -1) Then
    Result = 0
    End If
    CountChr = Result

End Function
</code>```

Requirements were changed and I keep in the comment box only time&date of changes and the user name.

Title: VBA keep changes in comment box

Body:
Wright now, I am keeping the last changes of data from a cell, in a comment, with this function:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    val_before = Target.Value

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Count > 1 Then
        MsgBox Target.Count & " cells were changed!"
        Exit Sub
    End If

    If Target.Comment Is Nothing Then
        Target.AddComment
        existingcomment = ""
    Else
        existingcomment = Target.Comment.Text & vbLf & vbLf
    End If

    Target.Comment.Text Text:=Format(Now(), "DD.MM.YYYY hh:mm") & ":" & vbLf & Environ("UserName") & _
        " changed " & val_before & Target.Address & " from:" & vbLf & """" & val_before & _
        """" & vbLf & "to:" & vbLf & """" & Target.Value & """"

End Sub

original answer here: VBA Last Change Method

But I am trying to change it, to keep a maximum of 5 history changes in the comment box, and when a new change is made, to delete the oldest one. And I was thinking to do the following operations:

'count the : (double dots-from the time), when is bigger then 5, compare the date and time of the changes, delete the oldest one and log the new one(6th) for example.

Has anyone a better idea? I am new to VBA and also to programming.

Body:
So, this is my working version:

Private Sub Worksheet_Change(ByVal Target As Range)

   If Range("A" & Target.Row).Value = "" Then GoTo EndeSub
   If Target.Row <= 2 Then GoTo EndeSub
   If Not Intersect(Range("C:JA"), Target) Is Nothing Then
     On Error GoTo EndeSub
     Application.EnableEvents = False
     Range("B" & Target.Row) = Now
   End If

    Application.Volatile
    Dim CommentBox As Object
    Set CommentBox = Range("B" & Target.Row).Comment
    Dim CommentString As String

    If Not CommentBox Is Nothing Then
        If CommentBox.Text <> "" Then
            CommentString = CommentBox.Text
            Range("B" & Target.Row).Comment.Delete
        End If
    Else
        CommentString = ""
    End If

    Dim CommentTemp As String
    CommentTemp = CommentString
    Dim LastDoubleDotPosition As Integer
    LastDoubleDotPosition = 0
    Dim LongestName As Integer
    LongestName = 0

    If InStr(CommentTemp, ":") > 0 Then StillTwoDoubleDots = True

    Do While InStr(CommentTemp, ":") > 0

        If InStr(CommentTemp, ":") > LongestName Then LongestName = InStr(CommentTemp, ":")
        CommentTemp = Right(CommentTemp, Len(CommentTemp) - InStr(CommentTemp, ":"))

    Loop

    count = CountChr(CommentString, ":")

    If count >= 5 Then

        LastDoubleDotPosition = Len(CommentString) - Len(CommentTemp) - 1
        CommentString = Left(CommentString, LastDoubleDotPosition - 13)

    End If

    'insert comment
    Dim FinalComment As String
    FinalComment = Format(Now(), "DD.MM.YYYY hh:mm") & " " & "by" & " " & Application.UserName & vbCrLf & CommentString 'newComment and the oldcomment
    Range("B" & Target.Row).AddComment FinalComment

    Set CommentBox = Range("B" & Target.Row).Comment

    LongestName = LongestName * 5
    If LongestName < 150 Then LongestName = 150

    With CommentBox
        .Shape.Height = 60
        .Shape.Width = LongestName
    End With

EndeSub:
    Application.EnableEvents = True

End Sub

'counter
Public Function CountChr(Expression As String, Character As String) As Long

    Dim Result As Long
    Dim Parts() As String
    Parts = Split(Expression, Character)
    Result = UBound(Parts, 1)
    If (Result = -1) Then
    Result = 0
    End If
    CountChr = Result

End Function

Requirements were changed and I keep in the comment box only time&date of changes and the user name.


问:
Break the for loop based on the ajax success variable
For the following code, the emailCnt is 50 for first iteration, I need 25 in next iteration. What is the possible way to access the variable value outside the ajax success and break the for loop execution?</p>

```<code>var limit = 50;
var emailCnt = limit;
for (var i = 0; i < 20; i++) {
    console.log(emailCnt);///this value is 50 instead I need 25
    if (emailCnt < limit && i != 0) {
        break;
    }
    setTimeout(function () {
        submit_post(slNo, limit, function (output) {
            slNo = output;
            emailCnt = 25;
            $('#load_data').html('Hello');
        });
    }, 1000);
}
function submit_post(slNo, limit, handleData) {
    $.ajax({
        type: 'POST',
        async: false,
        url: url,
        data: { slNo: slNo, limit: limit },
        success: function (data) { handleData(data); }
    });
}
</code>```

答:
This successfully worked for me</p>

```<code>var limit           =   50;
var emailCnt        =   limit;
function submit_post(slNo, limit)
{
    var result="";
    $.ajax({
        type: 'POST',
        async: false,
        url: url,
        data: {slNo:slNo, limit:limit},
        success: function(data) { result = data; }
    });
    return result;
}
for(var i=0;i<20;i++)
{
    if(emailCnt     <   limit  &&  i  !=  0)
    {
        break;
    }
    setTimeout(function () {
    var output              =   submit_post(slNo, limit);
    slNo                    =   output;
    emailCnt                =   25;
    $('#load_data').html('Hello');
}, 1000);
}
</code>```

Body:
For the following code, the emailCnt is 50 for first iteration, I need 25 in next iteration. What is the possible way to access the variable value outside the ajax success and break the for loop execution?

var limit = 50;
var emailCnt = limit;
for (var i = 0; i < 20; i++) {
    console.log(emailCnt);///this value is 50 instead I need 25
    if (emailCnt < limit && i != 0) {
        break;
    }
    setTimeout(function () {
        submit_post(slNo, limit, function (output) {
            slNo = output;
            emailCnt = 25;
            $('#load_data').html('Hello');
        });
    }, 1000);
}
function submit_post(slNo, limit, handleData) {
    $.ajax({
        type: 'POST',
        async: false,
        url: url,
        data: { slNo: slNo, limit: limit },
        success: function (data) { handleData(data); }
    });
}

Body:
This successfully worked for me

var limit           =   50;
var emailCnt        =   limit;
function submit_post(slNo, limit)
{
    var result="";
    $.ajax({
        type: 'POST',
        async: false,
        url: url,
        data: {slNo:slNo, limit:limit},
        success: function(data) { result = data; }
    });
    return result;
}
for(var i=0;i<20;i++)
{
    if(emailCnt     <   limit  &&  i  !=  0)
    {
        break;
    }
    setTimeout(function () {
    var output              =   submit_post(slNo, limit);
    slNo                    =   output;
    emailCnt                =   25;
    $('#load_data').html('Hello');
}, 1000);
}


问:
insert a link into a react-tooltip
I am trying to set a link inside of a react-tooltip and instead of getting back a link, [Object object] is coming back into the tooltip. The format I am using is setting the link as the data-tip like this:

```<code><div data-place="right" data-type="dark" data-effect="solid" data-multiline="false" data-class="nav-tooltip" data-tip={link} delayHide={1000}>
   <div>view</div>
 </div>
 <ReactTooltip />
</code>```

I am confused as to why this doesn't work. I have tried string interpolation and no luck.

答:
You could try using getContent on ReactTooltip like this:

```<code><MenuItem data-tip="Shouldn't show this" data-for="tooltip">

<ReactTooltip id="tooltip" event="focus" getContent={() => {
                            return <div>Test</div>
                        }}/>
</code>```

The documentation shows this possibility: https://www.npmjs.com/package/react-tooltip

Note: if you have data-html={true} then it will return [Object object] as well

Edit: I think if you want to make a full html box out of a tooltip, then you'd better find a different plugin. Tooltip's shouldn't be used for full html right?

Title: insert a link into a react-tooltip

Body:
I am trying to set a link inside of a react-tooltip and instead of getting back a link, [Object object] is coming back into the tooltip. The format I am using is setting the link as the data-tip like this:

view

 <ReactTooltip />

I am confused as to why this doesn't work. I have tried string interpolation and no luck.

Body:
You could try using getContent on ReactTooltip like this:

<MenuItem data-tip="Shouldn't show this" data-for="tooltip">

<ReactTooltip id="tooltip" event="focus" getContent={() => {
                            return <div>Test</div>
                        }}/>

The documentation shows this possibility: https://www.npmjs.com/package/react-tooltip

Note: if you have data-html={true} then it will return [Object object] as well

Edit: I think if you want to make a full html box out of a tooltip, then you'd better find a different plugin. Tooltip's shouldn't be used for full html right?


问:
Firebase RT database child not updating from httpPostJson
I'm trying to log an event that happens with a Smartthings device into a Firebase database. The function in my Smartthings app is:

```<code>def reportSwitchOnHandler(evt){
log.debug "reportSwitchOnHandler called: $evt"

def params = [
    uri: "https://<project-id>.firebaseio.com/switchStateData/params.json?auth=<key>",

    body: [
            switchState: "test"
        ]
]

try {
    httpPostJson(params) { resp ->
        resp.headers.each {
            log.debug "${it.name} : ${it.value}"
        }
        log.debug "DEBUG (POST FIREBASE): response contentType: ${resp.    contentType}"
    }
} catch (e) {
    log.debug "something went wrong: $e"
}
</code>```

My "params" database structure returned json is:

```<code>{"lights":0,"switchState":"off"}
</code>```

I'm only wanting to update the switchState.

So with that said, when I run the above code, under the "params" structure, rather than updates the switchState child, it creates a new child with some random value like "-Kyn_TIEItKNNACLuEk5" and under that switchState is there with the "test" value.

```<code>{"-Kyn_TIEItKNNACLuEk5":{"switchState":"test"},"lights":0,"state":"off"}
</code>```

Any ideas what I'm missing for it to actually update the original switchState child and not be creating a new sub child (-Kyn_TIEItKNNACLuEk5)?

答: For future reference, I found a beta (as of this writing) feature in the Smartthings documents that now allows the PATCH command. Check out here, http://docs.smartthings.com/en/latest/smartapp-developers-guide/async-http.html.</p>

Body:
I'm trying to log an event that happens with a Smartthings device into a Firebase database. The function in my Smartthings app is:

def reportSwitchOnHandler(evt){
log.debug "reportSwitchOnHandler called: $evt"

def params = [
    uri: "https://<project-id>.firebaseio.com/switchStateData/params.json?auth=<key>",

    body: [
            switchState: "test"
        ]
]

try {
    httpPostJson(params) { resp ->
        resp.headers.each {
            log.debug "${it.name} : ${it.value}"
        }
        log.debug "DEBUG (POST FIREBASE): response contentType: ${resp.    contentType}"
    }
} catch (e) {
    log.debug "something went wrong: $e"
}

My "params" database structure returned json is:

{"lights":0,"switchState":"off"}

I'm only wanting to update the switchState.

So with that said, when I run the above code, under the "params" structure, rather than updates the switchState child, it creates a new child with some random value like "-Kyn_TIEItKNNACLuEk5" and under that switchState is there with the "test" value.

{"-Kyn_TIEItKNNACLuEk5":{"switchState":"test"},"lights":0,"state":"off"}

Any ideas what I'm missing for it to actually update the original switchState child and not be creating a new sub child (-Kyn_TIEItKNNACLuEk5)?


问:
cant get content by ContentChildren
I'm in situation where I have a 'Items' component that has ng-content:

```<code>@Component({
 selector: 'items'
 template: `<ng-content></ng-content>`
})
</code>```

I would like to get the value of this content, so that's why I'm using ContentChildren where I passed my 'Item' directive as selector.

```<code>@ContentChildren(Item) elements: QueryList<Item>;
</code>```

Unfortunately I can't get any data.

Here I attach a link to plunker

In elements property I would like to have all elements from 'App' component that I've marked with 'Item' directive.

```<code><items>
  <div item *ngFor="let num of nums">{{ num }}</div>
</items>
</code>```

Am I doing something wrong?

答:
You have wrong selector for Item component. It should be

[item] because you use it as attribute

Forked Plunker

Title: cant get content by ContentChildren

Body:
I'm in situation where I have a 'Items' component that has ng-content:

@Component({
 selector: 'items'
 template: `<ng-content></ng-content>`
})

I would like to get the value of this content, so that's why I'm using ContentChildren where I passed my 'Item' directive as selector.

@ContentChildren(Item) elements: QueryList<Item>;

Unfortunately I can't get any data.

Here I attach a link to plunker

In elements property I would like to have all elements from 'App' component that I've marked with 'Item' directive.

<items>

{{ num }}

</items>

Am I doing something wrong?


问:
Unable to start debugging on the web server.Could not start ASP.NET debugging
I am on windows 10, I am using visual studio 2013. In IIS, I have set Enable 32-Bit Applications to TRUE and after this, when I try to debug my application I am getting this error.

Unable to start debugging on the web server. Could not start ASP.NET debugging. More information may be available by starting the project without debugging

To solve this error, I tried the following:

restart iis by doing this

cd %windir%\Microsoft.NET\Framework\v4.0.30319

aspnet_regiis.exe -i

I have set debug attribute to true in web.config file

```<code><system.web>
<compilation debug="true" targetFramework="4.5">
...
</code>```

None of the above have worked. Any idea where am I going wrong? What should I do?

答:
Is "W3SVC" service is running in ur machine?
if not try to start the "world wide web publishing service" service in ur machine.</p>

Body:
I am on windows 10, I am using visual studio 2013. In IIS, I have set Enable 32-Bit Applications to TRUE and after this, when I try to debug my application I am getting this error.

Unable to start debugging on the web server. Could not start ASP.NET debugging. More information may be available by starting the project without debugging

To solve this error, I tried the following:

restart iis by doing this

cd %windir%\Microsoft.NET\Framework\v4.0.30319

aspnet_regiis.exe -i

I have set debug attribute to true in web.config file

<system.web>
<compilation debug="true" targetFramework="4.5">
...

None of the above have worked. Any idea where am I going wrong? What should I do?


问:
Numpy error: operands could not be broadcast together with shapes 1
I am a python beginner. I have an error message "ValueError: operands could not be broadcast together with shapes".

Here is my data:

```<code>import numpy as np
spent = np.array([
    10,  10,  13,  12,  109,   17,  31, 1,   39, 41,   45,
    41, 71,   161,   39,  115,    5,   51,   58,  334,  165, 1032,
    40,  52, 21,   68,  79,  482,  10,  265,  60,  67,   12,
    53,  188,  32,  397,  51, 17, 156,  100,  85,  53,  95,
     68,  308,   53,  675,   78,  27,  219,  45,  45,   30,   61,
    16,   72,   80,   96, 1386,  370,   16,   81,   28,   43,   90,
    33,   66,   77])
visit = np.array([
   19, 13, 16, 16, 18, 9, 12, 3, 15, 16, 16, 3, 4, 11, 11, 11, 11,
   12, 12, 12, 13, 13, 14, 14, 15, 15, 5, 6, 6, 7, 7, 7, 7, 7,
   17, 17, 8, 8, 8, 4, 4, 13, 8, 4, 4, 9, 20, 10, 11, 11, 14,
   12, 12, 15, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 16, 16, 18, 11,
   6])
</code>```

My job is select spent>100 and visit>10 together. So, I would like to find people who pay more than $100 among people who visited more than 10 times.
I have tried the following codes.

```<code>a=spent[spent>100] & [visit>10]
print(a)
</code>```

But, I have an error message "ValueError: operands could not be broadcast together with shapes". Could you advise me how to deal with this? I just have no idea.

答:
IIUC you don't need the mask on spent per se like you've done:

```<code>In[16]:
a=(spent>100) & (visit>10)
a

Out[16]:
array([False, False, False, False,  True, False, False, False, False,
       False, False, False, False,  True, False,  True, False, False,
       False,  True,  True,  True, False, False, False, False, False,
       False, False, False, False, False, False, False,  True, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False,  True, False, False, False,
       False, False, False, False, False,  True,  True, False, False,
       False, False, False, False, False, False], dtype=bool)
</code>```

This gives you a boolean mask that is only True where both conditions are met in both arrays, you can then use this to mask against the original arrays

So using this against spent:

```<code>In[18]:
spent[a]

Out[18]: array([ 109,  161,  115,  334,  165, 1032,  188,  219, 1386,  370])
</code>```

Your error was that you masked your original array which produced an array that was a different shape that what you're trying to broadcast against visit:

```<code>print(spent[spent>100].shape)
print((visit>10).shape)
(16,)
(69,)
</code>```

You could compound the conditions into the same mask:

```<code>In[20]:
spent[(spent > 100) & (visit > 10)]

Out[20]: array([ 109,  161,  115,  334,  165, 1032,  188,  219, 1386,  370])
</code>```

to produce the same result

Body:
I am a python beginner. I have an error message "ValueError: operands could not be broadcast together with shapes".

Here is my data:

import numpy as np
spent = np.array([
    10,  10,  13,  12,  109,   17,  31, 1,   39, 41,   45,
    41, 71,   161,   39,  115,    5,   51,   58,  334,  165, 1032,
    40,  52, 21,   68,  79,  482,  10,  265,  60,  67,   12,
    53,  188,  32,  397,  51, 17, 156,  100,  85,  53,  95,
     68,  308,   53,  675,   78,  27,  219,  45,  45,   30,   61,
    16,   72,   80,   96, 1386,  370,   16,   81,   28,   43,   90,
    33,   66,   77])
visit = np.array([
   19, 13, 16, 16, 18, 9, 12, 3, 15, 16, 16, 3, 4, 11, 11, 11, 11,
   12, 12, 12, 13, 13, 14, 14, 15, 15, 5, 6, 6, 7, 7, 7, 7, 7,
   17, 17, 8, 8, 8, 4, 4, 13, 8, 4, 4, 9, 20, 10, 11, 11, 14,
   12, 12, 15, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 16, 16, 18, 11,
   6])

My job is select spent>100 and visit>10 together. So, I would like to find people who pay more than $100 among people who visited more than 10 times.
I have tried the following codes.

a=spent[spent>100] & [visit>10]
print(a)

But, I have an error message "ValueError: operands could not be broadcast together with shapes". Could you advise me how to deal with this? I just have no idea.

Body:
IIUC you don't need the mask on spent per se like you've done:

In[16]:
a=(spent>100) & (visit>10)
a

Out[16]:
array([False, False, False, False,  True, False, False, False, False,
       False, False, False, False,  True, False,  True, False, False,
       False,  True,  True,  True, False, False, False, False, False,
       False, False, False, False, False, False, False,  True, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False,  True, False, False, False,
       False, False, False, False, False,  True,  True, False, False,
       False, False, False, False, False, False], dtype=bool)

This gives you a boolean mask that is only True where both conditions are met in both arrays, you can then use this to mask against the original arrays

So using this against spent:

In[18]:
spent[a]

Out[18]: array([ 109,  161,  115,  334,  165, 1032,  188,  219, 1386,  370])

Your error was that you masked your original array which produced an array that was a different shape that what you're trying to broadcast against visit:

print(spent[spent>100].shape)
print((visit>10).shape)
(16,)
(69,)

You could compound the conditions into the same mask:

In[20]:
spent[(spent > 100) & (visit > 10)]

Out[20]: array([ 109,  161,  115,  334,  165, 1032,  188,  219, 1386,  370])

to produce the same result


问:
Continue receiving data from Arduino after disconnect
I made a dashboard where light input from a lightsensor on a Arduino uno is converted to a percentage. I am trying to continue receiving input after my Arduino is disconnected.

```<code>try:
    ser = Serial(
        port='COM3',
        baudrate=19200,
        parity=PARITY_NONE,
        stopbits=STOPBITS_ONE,
        bytesize=EIGHTBITS,
        timeout=0)
except:
    print("Disconnected")

def updateTick():
    try:
        f.root.after(1000, updateTick)
        value = ser.read()
        min = 25                #min light value
        max = 50                #max light value
        if value:
            lightNum = int.from_bytes(value, byteorder='little')
            print(lightNum)
            lightToPercentage = round((lightNum - min) * 100 / (max - min))
            #print(lightToPercentage)
            view.l1.lightLabelCount.config(text="{}%".format(lightToPercentage))
            checkPreset(lightToPercentage)
            updateGraph(lightToPercentage)
    except:
        view.l1.lightLabelCount.config(text="N/A")
        view.l1.lightLabelPreset.config(text="[Restart]")
</code>```

So, when i start the dashboard, I receive data from my Arduino, when I disconnect my arduino, the percentage in de dashboard changes to N/A.

But what I am trying to do is to receive data again as soon as the Arduino is connected again.

Any idea how to do that?

答:
I'll try to express pseudo code of the possible solution came up my mind. It may help somehow. </p>

```<code>if(check if serial comm. exist)
   read received value
   write the value to dashboard
else
   write last received value to dashboard
   while(!(check if serial comm. exist))
      keep writing last received value to dashboard
//when comm. come back, it'll automaticly update the value
</code>```

Body:
I made a dashboard where light input from a lightsensor on a Arduino uno is converted to a percentage. I am trying to continue receiving input after my Arduino is disconnected.

try:
    ser = Serial(
        port='COM3',
        baudrate=19200,
        parity=PARITY_NONE,
        stopbits=STOPBITS_ONE,
        bytesize=EIGHTBITS,
        timeout=0)
except:
    print("Disconnected")

def updateTick():
    try:
        f.root.after(1000, updateTick)
        value = ser.read()
        min = 25                #min light value
        max = 50                #max light value
        if value:
            lightNum = int.from_bytes(value, byteorder='little')
            print(lightNum)
            lightToPercentage = round((lightNum - min) * 100 / (max - min))
            #print(lightToPercentage)
            view.l1.lightLabelCount.config(text="{}%".format(lightToPercentage))
            checkPreset(lightToPercentage)
            updateGraph(lightToPercentage)
    except:
        view.l1.lightLabelCount.config(text="N/A")
        view.l1.lightLabelPreset.config(text="[Restart]")

So, when i start the dashboard, I receive data from my Arduino, when I disconnect my arduino, the percentage in de dashboard changes to N/A.

But what I am trying to do is to receive data again as soon as the Arduino is connected again.

Any idea how to do that?

Body:
I'll try to express pseudo code of the possible solution came up my mind. It may help somehow.

if(check if serial comm. exist)
   read received value
   write the value to dashboard
else
   write last received value to dashboard
   while(!(check if serial comm. exist))
      keep writing last received value to dashboard
//when comm. come back, it'll automaticly update the value


问:
Drop column(s) on a table that has a materialized view
It seems that it's not possible to drop a column from a table when there is a defined materialized view on this table. For example, let's assume that we have this table:

```<code>> CREATE TABLE healthera.users (
>   user_id timeuuid PRIMARY KEY,
>   address text,
>   birthday int,
>   forename text,
>   user_password text,
>   username text
> );
</code>```

and we define the materialized view below:

```<code>> CREATE MATERIALIZED VIEW users_by_username AS
>   SELECT * FROM users
>   WHERE user_id IS NOT NULL AND username IS NOT NULL
>   PRIMARY KEY (username, user_id);
</code>```

Then we alter the users table and we add a column:

```<code>> ALTER TABLE users ADD last_name text;
</code>```

When we try to drop this column or any other column(s) from the users table then we get back this error:

```<code>> ALTER TABLE users DROP last_name ;
> InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot drop column last_name, depended on by materialized views (healthera.{users_by_username})"
</code>```

or

```<code>> ALTER TABLE users DROP forename ;
> InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot drop column forename, depended on by materialized views (healthera.{users_by_username})"
</code>```

Is this something expected? How should we handle this? Do we need to drop the materialized view, drop the column(s) and then recreate the materialized view again? If yes, how expensive is this for cassandra?

答:
You can add a column to the base table of a MV, but you cannot drop a column even if it is not part of the PK.

http://www.doanduyhai.com/blog/?p=1930

When creating a MV for an existing table w/data, it will kick off a building process to populate the MV in the background.

You can check the status -

```<code>SELECT * FROM system.views_builds_in_progress;
SELECT * FROM system.built_views;
</code>```

Body:
It seems that it's not possible to drop a column from a table when there is a defined materialized view on this table. For example, let's assume that we have this table:

> CREATE TABLE healthera.users (
>   user_id timeuuid PRIMARY KEY,
>   address text,
>   birthday int,
>   forename text,
>   user_password text,
>   username text
> );

and we define the materialized view below:

> CREATE MATERIALIZED VIEW users_by_username AS
>   SELECT * FROM users
>   WHERE user_id IS NOT NULL AND username IS NOT NULL
>   PRIMARY KEY (username, user_id);

Then we alter the users table and we add a column:

> ALTER TABLE users ADD last_name text;

When we try to drop this column or any other column(s) from the users table then we get back this error:

> ALTER TABLE users DROP last_name ;
> InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot drop column last_name, depended on by materialized views (healthera.{users_by_username})"

or

> ALTER TABLE users DROP forename ;
> InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot drop column forename, depended on by materialized views (healthera.{users_by_username})"

Is this something expected? How should we handle this? Do we need to drop the materialized view, drop the column(s) and then recreate the materialized view again? If yes, how expensive is this for cassandra?

Body:
You can add a column to the base table of a MV, but you cannot drop a column even if it is not part of the PK.

http://www.doanduyhai.com/blog/?p=1930

When creating a MV for an existing table w/data, it will kick off a building process to populate the MV in the background.

You can check the status -

SELECT * FROM system.views_builds_in_progress;
SELECT * FROM system.built_views;


问:
MongoDB update nested array of object by index
Let's suppose to there is db like below...

```<code>{ _id: 1234,
  key: 'Contacts',
  value: [
     { name: 'McDonald', phone: '1111'},
     { name: 'KFC', phone: '2222'}
  ]
}
</code>```

And I want to change KFC's phone number to '3333'.

What I did is

```<code>DB.findOne({ key: 'Contacts' }, function(err, db){

        db.value[1]['phone'] = '3333'
        db.save(function(err, result){
            // done
        })
    }
)
</code>```

But it didn't update the database. What am I wrong?

There's no specific _id in elements of array for some reason.

Only the way to find specific element is index.

答:
Use the positional operator $

more info : https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S

```<code>DB.update({key: "Contacts", "value.name": "KFC" },
         { $set: { "value.$.phone" : 666 } },function(err,doc){

         });
</code>```

Body:
Let's suppose to there is db like below...

{ _id: 1234,
  key: 'Contacts',
  value: [
     { name: 'McDonald', phone: '1111'},
     { name: 'KFC', phone: '2222'}
  ]
}

And I want to change KFC's phone number to '3333'.

What I did is

DB.findOne({ key: 'Contacts' }, function(err, db){

        db.value[1]['phone'] = '3333'
        db.save(function(err, result){
            // done
        })
    }
)

But it didn't update the database. What am I wrong?

There's no specific _id in elements of array for some reason.

Only the way to find specific element is index.

Body:
Use the positional operator $

more info : https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S

DB.update({key: "Contacts", "value.name": "KFC" },
         { $set: { "value.$.phone" : 666 } },function(err,doc){

         });


问:
How to combine 2 different dataframes together?
I have 2 DataFrames:

Users (~29.000.000 entries)

```<code>|-- userId: string (nullable = true)
</code>```

Impressions (~1000 entries)

```<code>|-- modules: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- content: array (nullable = true)
|    |    |    |-- element: string (containsNull = true)
|    |    |-- id: string (nullable = true)
</code>```

I want to walk through all the Users and attach to each User 1 Impression from these ~1000 entries. So actually at each ~1000th User the Impression would be the same, then the loop on the Impressions would start from the beginning and assign the same ~1000 impressions for the next ~1000 users.
At the end I want to have a DataFrame with the combined data. Also the Users dataframe could be reused by adding the columns of the Impressions or a newly created one would work also as a result.

You have any ideas, which would be a good solution here?

答:
Sketch of idea:

Add monotonically increasing id to both dataframes Users and Impressions via

```<code>val indexedUsersDF = usersDf.withColumn("index", monotonicallyIncreasingId)
val indexedImpressionsDF = impressionsDf.withColumn("index", monotonicallyIncreasingId)
</code>```

(see spark dataframe :how to add a index Column )

Determine number of rows in Impressions via count and store as int, e.g.

```<code>val numberOfImpressions = ...
</code>```

Apply UDF to index-column in indexedUsersDF that computes the modulo in a seperate column (e.g. moduloIndex)

```<code>val moduloIndexedUsersDF = indexedUsersDF.select(...)
</code>```

Join moduloIndexedUsersDF and indexedImperessionsDF on

```<code>moduloIndexedUsersDF("moduloIndex")===indexedImpressions("index")
</code>```

Body:
I have 2 DataFrames:

Users (~29.000.000 entries)

|-- userId: string (nullable = true)

Impressions (~1000 entries)

|-- modules: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- content: array (nullable = true)
|    |    |    |-- element: string (containsNull = true)
|    |    |-- id: string (nullable = true)

I want to walk through all the Users and attach to each User 1 Impression from these ~1000 entries. So actually at each ~1000th User the Impression would be the same, then the loop on the Impressions would start from the beginning and assign the same ~1000 impressions for the next ~1000 users.
At the end I want to have a DataFrame with the combined data. Also the Users dataframe could be reused by adding the columns of the Impressions or a newly created one would work also as a result.

You have any ideas, which would be a good solution here?

Body:
Sketch of idea:

Add monotonically increasing id to both dataframes Users and Impressions via

val indexedUsersDF = usersDf.withColumn("index", monotonicallyIncreasingId)
val indexedImpressionsDF = impressionsDf.withColumn("index", monotonicallyIncreasingId)

(see spark dataframe :how to add a index Column )

Determine number of rows in Impressions via count and store as int, e.g.

val numberOfImpressions = ...

Apply UDF to index-column in indexedUsersDF that computes the modulo in a seperate column (e.g. moduloIndex)

val moduloIndexedUsersDF = indexedUsersDF.select(...)

Join moduloIndexedUsersDF and indexedImperessionsDF on

moduloIndexedUsersDF("moduloIndex")===indexedImpressions("index")


答:
A possible solution would be using list comprehensions:

```<code>[(x, y) for x, y in zip(visit, spent) if x > 10 and y > 100]
</code>```

You could also use numpy as follows:

```<code>spent[visit > 10] > 100
</code>```

Title: Numpy error: operands could not be broadcast together with shapes 1

Body:
A possible solution would be using list comprehensions:

[(x, y) for x, y in zip(visit, spent) if x > 10 and y > 100]

You could also use numpy as follows:

spent[visit > 10] > 100


问:
Show text based on var value
I need this interactive element, where a user can toggle various buttons. Some buttons have the value of 4, and others of 1 and 0. When the toggled buttons add up to ie. 8, a text will be shown. And if it's 4 another text will be shown and so on.

Can anyone help me with the code below, as I can't seem to get it to work.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.selected {
color: red;
}
</style>

<button class="toggle" value=4>Car</button>
<button class="toggle" value=4>House</button>
<button class="toggle" value=1>MC</button>
<button class="toggle" value=1>Moped</button>
<button class="toggle" value=0>Life</button>
<button class="toggle" value=0>Dog</button>
<br/><br/>
<div class="demo"><div>

<script>
var totalAmount = 0;
$(document).ready(function() {
$('.toggle').on('click', function() {
    var value = $(this).val();
    if($(this).hasClass('selected')) {
       $(this).removeClass('selected');
       totalAmount = parseInt(totalAmount) - parseInt(value);
    }
    else {
      $(this).addClass('selected');
      totalAmount = parseInt(totalAmount) + parseInt(value);
    }
   });
});

if (totalAmount >= 9 ) {
  document.getElementById("demo").innerHTML = "A text to be here if
totalAmount is higher or equal than 9"
};

else if (totalAmount < 9 && > 4) {
    document.getElementById("demo").innerHTML = "A text to be here if
totalAmount is higher than 4 and less than 9"
};

else if (totalAmount <= 4) {
    document.getElementById("demo").innerHTML = "A text to be here if
totalAmount is less or equal to 4"
};

else {
  document.getElementById("demo").innerHTML = "A text to be here if nothing
else is"
};
</script>
</code>```

答:
There are syntax error, write else block properly i.e. if(){}else{}

condition should be totalAmount < 9 && totalAmount  > 4 not totalAmount < 9 && > 4

Move else if-else block in event handler.

Use ID attribute when using document.getElementById() function

var totalAmount = 0;
$(document).ready(function() {
  $('.toggle').on('click', function() {
    var value = $(this).val();
    if ($(this).hasClass('selected')) {
      $(this).removeClass('selected');
      totalAmount = parseInt(totalAmount) - parseInt(value);
    } else {
      $(this).addClass('selected');
      totalAmount = parseInt(totalAmount) + parseInt(value);
    }
console.log(totalAmount)
    if (totalAmount >= 9) {
      document.getElementById("demo").innerHTML = "A text to be here if totalAmount is higher or equal than 9"
    } else if (totalAmount < 9 && totalAmount > 4) {
      document.getElementById("demo").innerHTML = "A text to be here if totalAmount is higher than 4 and less than 9"
    } else if (totalAmount <= 4 && totalAmount > 1) {
      document.getElementById("demo").innerHTML = "A text to be here if totalAmount is less or equal to 4"
    } else {
      document.getElementById("demo").innerHTML = "A text to be here if nothing else is"
    };
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
  color: red;
}</code>```

<button class="toggle" value=4>Car</button>
<button class="toggle" value=4>House</button>
<button class="toggle" value=1>MC</button>
<button class="toggle" value=1>Moped</button>
<button class="toggle" value=0>Life</button>
<button class="toggle" value=0>Dog</button>

```

Title: Show text based on var value

Body:
I need this interactive element, where a user can toggle various buttons. Some buttons have the value of 4, and others of 1 and 0. When the toggled buttons add up to ie. 8, a text will be shown. And if it's 4 another text will be shown and so on.

Can anyone help me with the code below, as I can't seem to get it to work.

<button class="toggle" value=4>Car</button>
<button class="toggle" value=4>House</button>
<button class="toggle" value=1>MC</button>
<button class="toggle" value=1>Moped</button>
<button class="toggle" value=0>Life</button>
<button class="toggle" value=0>Dog</button>

Body:
There are syntax error, write else block properly i.e. if(){}else{}

condition should be totalAmount < 9 && totalAmount  > 4 not totalAmount < 9 && > 4

Move else if-else block in event handler.

Use ID attribute when using document.getElementById() function

var totalAmount = 0;
$(document).ready(function() {
  $('.toggle').on('click', function() {
    var value = $(this).val();
    if ($(this).hasClass('selected')) {
      $(this).removeClass('selected');
      totalAmount = parseInt(totalAmount) - parseInt(value);
    } else {
      $(this).addClass('selected');
      totalAmount = parseInt(totalAmount) + parseInt(value);
    }
console.log(totalAmount)
    if (totalAmount >= 9) {
      document.getElementById("demo").innerHTML = "A text to be here if totalAmount is higher or equal than 9"
    } else if (totalAmount < 9 && totalAmount > 4) {
      document.getElementById("demo").innerHTML = "A text to be here if totalAmount is higher than 4 and less than 9"
    } else if (totalAmount <= 4 && totalAmount > 1) {
      document.getElementById("demo").innerHTML = "A text to be here if totalAmount is less or equal to 4"
    } else {
      document.getElementById("demo").innerHTML = "A text to be here if nothing else is"
    };
  });
});

.selected {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="toggle" value=4>Car</button>
<button class="toggle" value=4>House</button>
<button class="toggle" value=1>MC</button>
<button class="toggle" value=1>Moped</button>
<button class="toggle" value=0>Life</button>
<button class="toggle" value=0>Dog</button>
<br/><br/>
<div id="demo">
  <div>


问:
How to store Japanese kanji character in Oracle database
This Japanese character , which has four bytes, is saved as ???? in Oracle database whereas other Japanese characters are saved properly.

The configuration in boot.rb of my rails application contains:

```<code>ENV['NLS_LANG'] = 'AMERICAN_AMERICA.UTF8'
</code>```

and sqldeveloper of oracle db has

```<code>NLS_LANGUAGE    AMERICAN
NLS_TERRITORY   AMERICA
NLS_CHARACTERSET    JA16SJISTILDE
</code>```

The datatype of the column is NVARCHAR2.

答:
Try NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Oracle Character set UTF8 is actually CESU-8 whereas AL32UTF8 is commonly known UTF-8

If you stay in Basic Multilingual Plane (BMP) then UTF8 and AL32UTF8 are equal, however when you have characters above U+FFFF then they are different.

 is U+20BB7 which is Supplementary Ideographic Plane

Body:
This Japanese character , which has four bytes, is saved as ???? in Oracle database whereas other Japanese characters are saved properly.

The configuration in boot.rb of my rails application contains:

ENV['NLS_LANG'] = 'AMERICAN_AMERICA.UTF8'

and sqldeveloper of oracle db has

NLS_LANGUAGE    AMERICAN
NLS_TERRITORY   AMERICA
NLS_CHARACTERSET    JA16SJISTILDE

The datatype of the column is NVARCHAR2.


问:
Is it possible to deploy an enterprise ASP.NET application and SQL schema changes with zero downtime?
We have a huge ASP.NET web application which needs to be deployed to LIVE with zero or nearly zero downtime. Let me point out that I've read the following question/answers but unfortunately it doesn't solve our problems as our architecture is a little bit more complicated.

Let's say that currently we have two IIS servers responding to requests and both are connected to the same MSSQL server. The solution seems like a piece of cake but it isn't because of the major schema changes we have to apply from time to time. Because of it's huge size, a simple database backup takes around 8 minutes which has become unacceptable, but it is a must before every new deploy for security reasons.

I would like to ask your help to get this deployment time down as much as possible. If you have any great ideas for a different architecture or maybe you've used tools which can help us here then please do not be shy and share the info.

Currently the best idea we came up is buying another SQL server which would be set up as a replica of the original DB. From the load balancer we would route all new traffic to one of the two IIS webservers. When the second webserver is free of running sessions then we can make deploy the new code. Now comes the hard part. At this point we would go offline with the website, take down the replication between the two SQL servers so we directly have a snapshot of the database in a hopefully consistent state (saves us 7.5 of the 8 minutes). Finally we would update the database schema on the main SQL server, and route all traffic via the updated webserver while we are upgrading the second webserver to the new version.

Please also share your thoughts regarding this solution. Can we somehow manage to eliminate the need for going offline with the website? How do bluechip companies with mammuth web applications do deployment?

Every idea or suggestion is more than welcome! Buying new hardware or software is really not a problem - we just miss the breaking idea. Thanks in advance for your help!

Edit 1 (2010.01.12):

Another requirement is to eliminate manual intervention, so in fact we are looking for a way which can be applied in an automated way.

Let me just remind you the requirement list:

1. Backup of database

2a. Deploy of website

2b. Update of database schema

3. Change to updated website

4 (optional): easy way of reverting to the old website if something goes very wrong.

答:
I saw this post a while ago, but have never used it, so can't vouch for ease of use/suitability, but MS have a free web farm deployment framework that may suit you:

http://weblogs.asp.net/scottgu/archive/2010/09/08/introducing-the-microsoft-web-farm-framework.aspx


问:
absolute css not working as expected
I'm trying to apply absolute positioning on class car. I expect it to be placed in top-left corner inside rectangle. The current behavior is being placed in top-left corner of the page which I don't want. As far as I know absolute element must be positioned inside its ancestor.

body {
  padding: 25px;
}

.car {
  position: absolute;
}

#rectangle {
  /* display: inline-block;
            position: absolute;
            top: 150px;
            left:25px; */
  width: 3324px;
  height: 5112px;
  background-color: #00b3ee;
}

#intro {
  /* position: absolute;
            top: 800px;
            left:25px; */
  border: solid 1px;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <div id="intro">
    <p>
      Floor <b><i>{{ $title }}</i></b> setup successfully finished!
      Return to floors.
    </p>
  </div>

  <div id="rectangle">
    <img src="{{ url($map_image_path) }}">

      <img id="dynamic" src="http://localhost/ParkingMinis/public/images/icons/car/reza1.png">

  </div>

</body></code>```

答:
Hey cheack this out http://learnlayout.com/position.html

#rectangle {

   position : relative;

  }```

Title: absolute css not working as expected

Body:
I'm trying to apply absolute positioning on class car. I expect it to be placed in top-left corner inside rectangle. The current behavior is being placed in top-left corner of the page which I don't want. As far as I know absolute element must be positioned inside its ancestor.

body {
  padding: 25px;
}

.car {
  position: absolute;
}

#rectangle {
  /* display: inline-block;
            position: absolute;
            top: 150px;
            left:25px; */
  width: 3324px;
  height: 5112px;
  background-color: #00b3ee;
}

#intro {
  /* position: absolute;
            top: 800px;
            left:25px; */
  border: solid 1px;
  padding: 10px;
}

      Floor {{ $title }} setup successfully finished!
      Return to floors.


问:
How can the foreign field shows the name instead of its id?
In my models.py, there are two model, the AvailableArea has a foreign field refer to AddressRegion:

```<code>class AddressRegion(models.Model):
    name = models.CharField(max_length=8)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

class AvailableArea(models.Model):
    name = models.CharField(max_length=8)
    addressregion = models.ForeignKey(AddressRegion, default=1, related_name='availableareas', on_delete=models.CASCADE)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name
</code>```

In the serializers.py, I serialize all the fields:

```<code>class AvailableAreaSerializer(ModelSerializer):
    """
    region
    """
    class Meta:
        model = AvailableArea
        fields = "__all__"
</code>```

In the views.py:

```<code>class AddressRegionListAPIView(ListAPIView):
    serializer_class = AddressRegionSerializer
    permission_classes = []
    queryset = AddressRegion.objects.all()
</code>```

The rest framework data is like this:

```<code>[
    {
        "id": 13,
        "name": "st-01",
        "addressregion": 3
    },
    {
        "id": 14,
        "name": "tg-02",
        "addressregion": 4
    },
    {
        "id": 15,
        "name": "sx-01",
        "addressregion": 3
    }
]
</code>```

I want the addressregion not shows the addressregion's id, but shows the addressregion's name.

答:
You can do the following:</p>
```<code>class AvailableAreaSerializer(ModelSerializer):

    addressregion_name= serializers.ReadOnlyField(source='addressregion.name')

    class Meta:
        model = AvailableArea
        fields = ('id', 'name', 'addressregion_name')
</code>```

Body:
In my models.py, there are two model, the AvailableArea has a foreign field refer to AddressRegion:

class AddressRegion(models.Model):
    name = models.CharField(max_length=8)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

class AvailableArea(models.Model):
    name = models.CharField(max_length=8)
    addressregion = models.ForeignKey(AddressRegion, default=1, related_name='availableareas', on_delete=models.CASCADE)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

In the serializers.py, I serialize all the fields:

class AvailableAreaSerializer(ModelSerializer):
    """
    region
    """
    class Meta:
        model = AvailableArea
        fields = "__all__"

In the views.py:

class AddressRegionListAPIView(ListAPIView):
    serializer_class = AddressRegionSerializer
    permission_classes = []
    queryset = AddressRegion.objects.all()

The rest framework data is like this:

[
    {
        "id": 13,
        "name": "st-01",
        "addressregion": 3
    },
    {
        "id": 14,
        "name": "tg-02",
        "addressregion": 4
    },
    {
        "id": 15,
        "name": "sx-01",
        "addressregion": 3
    }
]

I want the addressregion not shows the addressregion's id, but shows the addressregion's name.

Body:
You can do the following:

class AvailableAreaSerializer(ModelSerializer):

    addressregion_name= serializers.ReadOnlyField(source='addressregion.name')

    class Meta:
        model = AvailableArea
        fields = ('id', 'name', 'addressregion_name')


问:
ALM Rest API : site-session returns 'The remote server returned an error: (400) Bad Request.'
I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.

What am I doing wrong please... very confused!

```<code>    // Authentication XML : 0 = User, 1 = Password
    private const string AuthenticationXML = @"<alm-authentication>" +
        "<user>{0}</user><password>{1}</password></alm-authentication>";

    baseRequestURL = settings.QualityCentreURL + "/qcbin/";
</code>```

Authentication is done first (and is successful) :

```<code>string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);

string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);

byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";

Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();

authenticationCookie = myauthres.Headers.Get("Set-Cookie");
</code>```

The Site-Session code is :

```<code>    public void GetSiteSession()
    {
        // Creat the web request fore site-session.
        string request = baseRequestURL + "rest/site-session";
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);

        string xml = String.Empty;
        byte[] requestbytes = Encoding.UTF8.GetBytes(xml);

        // Update the attributes before sending.
        webRequest.Method = "POST";
        webRequest.ContentType = "application/xml";
        webRequest.Accept = "application/xml";
        webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);

        try
        {
            Stream requestStream = webRequest.GetRequestStream();
            requestStream.Write(requestbytes, 0, requestbytes.Length);
            requestStream.Close();

            HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
            Stream responseStream = webRequestResponse.GetResponseStream();
            XDocument doc = XDocument.Load(responseStream);
        }
        catch (System.Net.WebException except)
        {
            Console.WriteLine(except.Message);
        }
    }
</code>```

I have tried cutting  ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.

The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P

答:
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'</p>

```<code>        string requestURL = baseRequestURL + "api/authentication/sign-in";

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);

            var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
            request.CookieContainer = authenticationCookieContainer;
            request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));

            var authResponse = request.GetResponse();
            errorString = String.Empty;
        }
        catch (System.Net.WebException except)
        {
            errorString = except.Message;
            return false;
        }

        errorString = String.Empty;
        return true;
    }
</code>```

Body:
I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.

What am I doing wrong please... very confused!

    // Authentication XML : 0 = User, 1 = Password
    private const string AuthenticationXML = @"<alm-authentication>" +
        "<user>{0}</user><password>{1}</password></alm-authentication>";

    baseRequestURL = settings.QualityCentreURL + "/qcbin/";

Authentication is done first (and is successful) :

string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);

string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);

byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";

Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();

authenticationCookie = myauthres.Headers.Get("Set-Cookie");

The Site-Session code is :

    public void GetSiteSession()
    {
        // Creat the web request fore site-session.
        string request = baseRequestURL + "rest/site-session";
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);

        string xml = String.Empty;
        byte[] requestbytes = Encoding.UTF8.GetBytes(xml);

        // Update the attributes before sending.
        webRequest.Method = "POST";
        webRequest.ContentType = "application/xml";
        webRequest.Accept = "application/xml";
        webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);

        try
        {
            Stream requestStream = webRequest.GetRequestStream();
            requestStream.Write(requestbytes, 0, requestbytes.Length);
            requestStream.Close();

            HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
            Stream responseStream = webRequestResponse.GetResponseStream();
            XDocument doc = XDocument.Load(responseStream);
        }
        catch (System.Net.WebException except)
        {
            Console.WriteLine(except.Message);
        }
    }

I have tried cutting  ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.

The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P

Body:
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'

        string requestURL = baseRequestURL + "api/authentication/sign-in";

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);

            var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
            request.CookieContainer = authenticationCookieContainer;
            request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));

            var authResponse = request.GetResponse();
            errorString = String.Empty;
        }
        catch (System.Net.WebException except)
        {
            errorString = except.Message;
            return false;
        }

        errorString = String.Empty;
        return true;
    }


问:
GetObject with edge.js
I'm currently working to replace my ActiveX-Implementation in IE through a REST-API based on node.js with running edge.js

So far the basic examples from the page implementing worked pretty well. I have my index.js set up to

```<code>var edge = require('edge');
var edgeVb = require('edge-vb');
var path = require('path');

var helloVb = edge.func('vb', path.join(__dirname, 'simpleVbFunction.vb'));

helloVb('Testing with String', (err, res) => {
    if(err) throw err;
    console.log(res);
});
</code>```

And the simpleVbFunction.vb as

```<code>Async Function(Input As Object) As Task(Of Object)
    Return Await Task.Run(Function()
        Return "NodeJS Welcomes: " & Input.ToString()
    End Function)
End Function
</code>```

So far so good. Now i want to be able to access an application running on the machine running node.js. In this case Catia (could as well be Excel though)

Usually for this I'd use a simpleVbFunction.vb like this

```<code>Async Function(Input As Object) As Task(Of Object)
    Return Await Task.Run(Function()
        Dim CATIA as Object
        set CATIA = GetObject(, "CATIA.Application")
        Return CATIA.ActiveDocument.Application.FullName
    End Function)
End Function
</code>```

However this does not work. I'm getting the following error.

Error: Unable to compile VB code.
      ----> Errors when compiling as a CLR library:
      C:\Users\xxxxxx\AppData\Local\Temp\4hf2uw3z.0.vb(1,0) : error BC30203: Bezeichner erwartet.
      ----> Errors when compiling as a CLR async lambda expression:
      C:\Users\xxxxxx\AppData\Local\Temp\cypj4ltp.0.vb(7,0) : error BC30451: "GetObject" ist nicht deklariert. Auf das Objekt kann
  aufgrund der Schutzstufe möglicherweise nicht zugegriffen werden.
      at Error (native)
      at Object.exports.func (C:\Users\xxxxxx\coding\node\tst_win32ole\node_modules\edge\lib\edge.js:169:17)
      at Object. (C:\Users\xxxxxx\coding\node\tst_win32ole\index.js:6:20)
      at Module._compile (module.js:570:32)
      at Object.Module._extensions..js (module.js:579:10)
      at Module.load (module.js:487:32)
      at tryModuleLoad (module.js:446:12)
      at Function.Module._load (module.js:438:3)
      at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
      at ontimeout (timers.js:386:14)

Now I have to admin my VB.NET skills are a little bit rusty and this might just be an error in my VB-Code but I think it's something else. Has anyone of you been able to access a COM-Object via edge.js and if yes how was this possible?

[edit]
OK. I came a little further by switching to C# from VB (At least the code commented out to access the name of the Excel Application works). But this opened another problem. My code here looks like this

```<code>using System.Threading.Tasks;
using System;
using System.Runtime.InteropServices;
// using INFITF;

   public class Startup
   {
       public async Task<object> Invoke(object input)
       {
            // dynamic xl = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
            // return xl.Name;
           object CATIA0 = Marshal.GetActiveObject("CATIA.Application");
           INFITF.Application CATIA = CATIA0 as INFITF.Application;
       }
   }
</code>```

Now the problem is, that when working with Visual Studio and compiling the dlls get included automatically (when setting CATIA as INFITF.Application). But with edge.js I'd get the error that the namespace INFITF could not be found. Any ideas how to get that working?

Sorry for the long question. I'll tidy this up after this is solved.

[/edit]

答:
OK. I figured out most of it. First as you are not working with an IDE and you won't add Ressources like you're used to be this will work different with edge.js. You will have to find your dll and implement it. In my case I had to find the

Interop.INFITF.dll

from the Catia directory.

After that your node.js Code will look like this. (My functionality for testing now was just that once a second I'll log the name of the currently opened Part in Catia)

```<code>var edge = require('edge');
var path = require('path');

var getCat = edge.func({
    source: path.join(__dirname, 'accessCatia.cs')
, references :[
    './Resources/Interop.INFITF.dll'
]});

setInterval(function(){
    getCat('someInputString', (err, res)=>{
        if(err){
            console.log('ERROR FOUND: ');
            console.log(err);
            return;
        }
        console.log(res);
    });
},1000);
</code>```

My accessCatia.cs will look like this.

```<code>using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System;

   public class Startup
   {
       public async Task<object> Invoke(object input)
       {

           object cat0 = Marshal.GetActiveObject("Catia.Application");
           INFITF.Application cat = cat0 as INFITF.Application;
           INFITF.Document doc = cat.ActiveDocument as INFITF.Document;

           return doc.FullName;

       }
   }
</code>```

Now what's still open is that the objects recieved seem to have a different structure than what you'd get with VB.net or via ActiveX in the Internet Explorer. For example

doc.FullName exists as regular but doc.Name will not be found when using C# instead you'd have to use doc.get_Name().

Unfortunately DassaultSystems is pretty bad in terms of documentation but that might be stuff for another topic.

Title: GetObject with edge.js

Body:
I'm currently working to replace my ActiveX-Implementation in IE through a REST-API based on node.js with running edge.js

So far the basic examples from the page implementing worked pretty well. I have my index.js set up to

var edge = require('edge');
var edgeVb = require('edge-vb');
var path = require('path');

var helloVb = edge.func('vb', path.join(__dirname, 'simpleVbFunction.vb'));

helloVb('Testing with String', (err, res) => {
    if(err) throw err;
    console.log(res);
});

And the simpleVbFunction.vb as

Async Function(Input As Object) As Task(Of Object)
    Return Await Task.Run(Function()
        Return "NodeJS Welcomes: " & Input.ToString()
    End Function)
End Function

So far so good. Now i want to be able to access an application running on the machine running node.js. In this case Catia (could as well be Excel though)

Usually for this I'd use a simpleVbFunction.vb like this

Async Function(Input As Object) As Task(Of Object)
    Return Await Task.Run(Function()
        Dim CATIA as Object
        set CATIA = GetObject(, "CATIA.Application")
        Return CATIA.ActiveDocument.Application.FullName
    End Function)
End Function

However this does not work. I'm getting the following error.

Error: Unable to compile VB code.
      ----> Errors when compiling as a CLR library:
      C:\Users\xxxxxx\AppData\Local\Temp\4hf2uw3z.0.vb(1,0) : error BC30203: Bezeichner erwartet.
      ----> Errors when compiling as a CLR async lambda expression:
      C:\Users\xxxxxx\AppData\Local\Temp\cypj4ltp.0.vb(7,0) : error BC30451: "GetObject" ist nicht deklariert. Auf das Objekt kann
  aufgrund der Schutzstufe möglicherweise nicht zugegriffen werden.
      at Error (native)
      at Object.exports.func (C:\Users\xxxxxx\coding\node\tst_win32ole\node_modules\edge\lib\edge.js:169:17)
      at Object. (C:\Users\xxxxxx\coding\node\tst_win32ole\index.js:6:20)
      at Module._compile (module.js:570:32)
      at Object.Module._extensions..js (module.js:579:10)
      at Module.load (module.js:487:32)
      at tryModuleLoad (module.js:446:12)
      at Function.Module._load (module.js:438:3)
      at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
      at ontimeout (timers.js:386:14)

Now I have to admin my VB.NET skills are a little bit rusty and this might just be an error in my VB-Code but I think it's something else. Has anyone of you been able to access a COM-Object via edge.js and if yes how was this possible?

[edit]
OK. I came a little further by switching to C# from VB (At least the code commented out to access the name of the Excel Application works). But this opened another problem. My code here looks like this

using System.Threading.Tasks;
using System;
using System.Runtime.InteropServices;
// using INFITF;

   public class Startup
   {
       public async Task<object> Invoke(object input)
       {
            // dynamic xl = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
            // return xl.Name;
           object CATIA0 = Marshal.GetActiveObject("CATIA.Application");
           INFITF.Application CATIA = CATIA0 as INFITF.Application;
       }
   }

Now the problem is, that when working with Visual Studio and compiling the dlls get included automatically (when setting CATIA as INFITF.Application). But with edge.js I'd get the error that the namespace INFITF could not be found. Any ideas how to get that working?

Sorry for the long question. I'll tidy this up after this is solved.

[/edit]

Body:
OK. I figured out most of it. First as you are not working with an IDE and you won't add Ressources like you're used to be this will work different with edge.js. You will have to find your dll and implement it. In my case I had to find the

Interop.INFITF.dll

from the Catia directory.

After that your node.js Code will look like this. (My functionality for testing now was just that once a second I'll log the name of the currently opened Part in Catia)

var edge = require('edge');
var path = require('path');

var getCat = edge.func({
    source: path.join(__dirname, 'accessCatia.cs')
, references :[
    './Resources/Interop.INFITF.dll'
]});

setInterval(function(){
    getCat('someInputString', (err, res)=>{
        if(err){
            console.log('ERROR FOUND: ');
            console.log(err);
            return;
        }
        console.log(res);
    });
},1000);

My accessCatia.cs will look like this.

using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System;

   public class Startup
   {
       public async Task<object> Invoke(object input)
       {

           object cat0 = Marshal.GetActiveObject("Catia.Application");
           INFITF.Application cat = cat0 as INFITF.Application;
           INFITF.Document doc = cat.ActiveDocument as INFITF.Document;

           return doc.FullName;

       }
   }

Now what's still open is that the objects recieved seem to have a different structure than what you'd get with VB.net or via ActiveX in the Internet Explorer. For example

doc.FullName exists as regular but doc.Name will not be found when using C# instead you'd have to use doc.get_Name().

Unfortunately DassaultSystems is pretty bad in terms of documentation but that might be stuff for another topic.


问:
Odoo installation ''error: [Errno 98] Address already in use''
I followed this installation guide for odoo and I get an error in the very end
when I run odoo-bin file it gives me this error

```<code>teo@teo-Lenovo-Yoga-3-14:/opt/odoo/odoo-10.0$ ./odoo-bin
2017-07-06 15:03:20,583 3754 INFO ? odoo: Odoo version 10.0
2017-07-06 15:03:20,583 3754 INFO ? odoo: addons paths: ['/home/teo/.local/share/Odoo/addons/10.0', u'/opt/odoo/odoo-10.0/odoo/addons', u'/opt/odoo/odoo-10.0/addons']
2017-07-06 15:03:20,583 3754 INFO ? odoo: database: default@default:default
2017-07-06 15:03:20,601 3754 INFO ? odoo.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069
Exception in thread odoo.service.httpd:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 251, in http_thread
    self.httpd = ThreadedWSGIServerReloadable(self.interface, self.port, app)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 106, in __init__
    handler=RequestHandler)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 440, in __init__
    HTTPServer.__init__(self, (host, int(port)), handler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 116, in server_bind
    super(ThreadedWSGIServerReloadable, self).server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use
</code>```

I think it may be related to the odoo.conf file because I specify a port but it still assumes de default port 8069

this is my odoo.conf file

```<code>[options]

; This is the password that allows database operations:

; admin_passwd = PASSWORD

db_host = False

db_port = 8470

db_user = odoo

db_password = False

addons_path = /opt/odoo/odoo-10.0/addons

;Log Settings

logfile = /var/log/odoo/odoo.log

log_level = error
</code>```

Does anyone have an idea of what's happening, for the record I tried to install odoo before but failed so I already had DB user created for e.g.

答:
[Errno 98] error you use following two commands
Get the id of the process running by following command

root@odoo:~# ps ax | grep servername

Then kill the already running process

sudo kill -9 process_id

Body:
I followed this installation guide for odoo and I get an error in the very end
when I run odoo-bin file it gives me this error

teo@teo-Lenovo-Yoga-3-14:/opt/odoo/odoo-10.0$ ./odoo-bin
2017-07-06 15:03:20,583 3754 INFO ? odoo: Odoo version 10.0
2017-07-06 15:03:20,583 3754 INFO ? odoo: addons paths: ['/home/teo/.local/share/Odoo/addons/10.0', u'/opt/odoo/odoo-10.0/odoo/addons', u'/opt/odoo/odoo-10.0/addons']
2017-07-06 15:03:20,583 3754 INFO ? odoo: database: default@default:default
2017-07-06 15:03:20,601 3754 INFO ? odoo.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069
Exception in thread odoo.service.httpd:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 251, in http_thread
    self.httpd = ThreadedWSGIServerReloadable(self.interface, self.port, app)
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 106, in __init__
    handler=RequestHandler)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 440, in __init__
    HTTPServer.__init__(self, (host, int(port)), handler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 116, in server_bind
    super(ThreadedWSGIServerReloadable, self).server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use

I think it may be related to the odoo.conf file because I specify a port but it still assumes de default port 8069

this is my odoo.conf file

[options]

; This is the password that allows database operations:

; admin_passwd = PASSWORD

db_host = False

db_port = 8470

db_user = odoo

db_password = False

addons_path = /opt/odoo/odoo-10.0/addons

;Log Settings

logfile = /var/log/odoo/odoo.log

log_level = error

Does anyone have an idea of what's happening, for the record I tried to install odoo before but failed so I already had DB user created for e.g.