问:
Maximum meeting limits a user can join via Skype For business ucwa application
I need to check whether a user is in the lobby in several meeting at once. I am able to get the required information via EventChannel If I join a user via skype ucwa application. This works for up to 4 meetings for me. Meaning if I join for the same user to 4 different meetings I get events in event channel which belongs to 4 meetings and can find whether another user is in the lobby or not.

But in production environment this number can be reached to more than 100 and also I need to execute these steps in a timely manner. Say once in every 3 minutes I need to check whether users are in lobby or not. But right now if I try to join more than 4 or sometimes 5 meetings I get a 403 error and error code is "Forbidden" and the error subcode is "MaxEventCountReached".

There is no documentation about this errorcode anywhere. Even after 4 meeting joins If I try to Delete the skype aplication which I use to initially log in and create(POST) the application again and try to join meeting ,most of the time I get the error.

Does anyone have an idea on how to proceed ?

P.S Client application is written in Java

答: You cannot join more than 4 meetings at one time by design. I cant really think of a good way to join lots of meetings for monitoring lobby's. This can be handled by the Trusted Application API for meetings in O365. Its not using a user principal which is restricted to the 4 meeting joins. You can join a Trusted Application endpoint to more than 4 meetings but I have not actually tested this.</p>


来源: stackexchange

问:
factorial of a number
I have the following code but it is not giving perfect result for factorial can u find it out plz</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
</code>```

答:
You have to return the value. Here you go:

```<code>function fact(x) {
   if(x==0) {
      return 1;
   }
   return x * fact(x-1);
}

function run(number) {
    alert(fact(parseInt(number, 10)));
}
</code>```

and

```<code><input type="button" value="Find factiorial" onclick="run(txt1.value)">
</code>```

(How to make it work for negative numbers I leave up to you ;) (but I showed in this post anyway))

Just for fun, a more correct, non recursive algorithm:

```<code>function fact(x) {
       if(x == 0) {
           return 1;
       }
       if(x < 0 ) {
           return undefined;
       }
       for(var i = x; --i; ) {
           x *= i;
       }
       return x;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: factorial of a number

Body:
I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1">

  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>

Body:
You have to return the value. Here you go:

function fact(x) {
   if(x==0) {
      return 1;
   }
   return x * fact(x-1);
}

function run(number) {
    alert(fact(parseInt(number, 10)));
}

and

<input type="button" value="Find factiorial" onclick="run(txt1.value)">

(How to make it work for negative numbers I leave up to you ;) (but I showed in this post anyway))

Just for fun, a more correct, non recursive algorithm:

function fact(x) {
       if(x == 0) {
           return 1;
       }
       if(x < 0 ) {
           return undefined;
       }
       for(var i = x; --i; ) {
           x *= i;
       }
       return x;
}


问:
Polymer iron-ajax POST method not working
I'm learning Polymer. I'm unable to figure the code to "post" using <iron-ajax>. I'm using an online testing API (https://reqres.in/), and I should receive this response back with status code 200:

```<code>{"token": "QpwL5tke4Pnpja7X"}".
</code>```

I couldn't find a tutorial to show a POST example. I have been searching online for the past 24 hours, but everything is about GET and not POST.

If anyone familiar with <iron-ajax> could review my code and help me get it to work or figure out how to write the correct code, it would be very helpful for a beginner like me.

Is my code correct with the body property?

Is the response the 200 status code or the token?

```<code><!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">

<dom-module id="my-view2">
  <!--test using this data: {
      "email": "peter@klaven",
      "password": "cityslicka"
  }-->
  <template>
    <iron-ajax>
        auto
        method="post"
        url="https://reqres.in/api/login"
        handle-as="json"
        content-type="application/json"
        body =[{"email": "peter@klaven", "password": "cityslicka"}]
        on-response={{handleResponse}}

    </iron-ajax>

    <!--Handle response-->
    <p> response handling code goes here, how to show the response from the server here?</p>
    <p> It should show: {"token": "QpwL5tke4Pnpja7X"} </p>
    <div>
    <p> {{handleResponse}} </p>
    </div>
  </template>

  <script>
    class MyView2 extends Polymer.Element {
      static get is() { return 'my-view2'};

      static get proporties() {
        return {
          handleResponse: {
            type: Object,
            notify: true,
            readOnly: true
          }
        };
      }
    }

    window.customElements.define(MyView2.is, MyView2);
  </script>
</dom-module>
</code>```

答:
Your HTML is malformed (perhaps a copy-paste typo?). The iron-ajax's attributes should be inside the opening tag like this:

```<code><iron-ajax
  auto
  method="post"
  ...
>
</iron-ajax>
</code>```

You probably meant to bind the handleResponse property to <iron-ajax>.lastResponse, which contains the response to the AJAX request.

```<code><iron-ajax last-response={{handleResponse}} ...>
</code>```

Note that the binding of
{{handleResponse}}
 would render the response object as [object Object]. If you want to see the response contents, you'll have to use a computed binding that returns a string (e.g., with JSON.stringify()) like this:

```<code>// <template>
<p>json(handleResponse)</p>

// <script>
class XFoo extends Polymer.Element {
  ...
  json(obj) {
    return JSON.stringify(obj);
  }
}
</code>```

The attribute value of <iron-ajax>.body should be single-quoted like this:

```<code><iron-ajax body='[{"foo": "bar"}]'>
</code>```

The full example should look something like this:

```<code><dom-module id="x-foo">
  <template>
    <iron-ajax
              auto
              method="post"
              url="//httpbin.org/post"
              body='[{"foo": "{{foo}}"}]'
              handle-as="json"
              content-type="application/json"
              last-response="{{lastResponse}}"
              >
    </iron-ajax>
    ```[[json(lastResponse)]]```
  </template>
  <script>
    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {
          foo: {
            type: String,
            value: 'bar'
          }
        }
      }

      json(obj) {
        return JSON.stringify(obj, null, 2);
      }
    }
    customElements.define(XFoo.is, XFoo);
  </script>
</dom-module>
</code>```

demo

ContentLicense: CC BY-SA 3.0

Body:
I'm learning Polymer. I'm unable to figure the code to "post" using <iron-ajax>. I'm using an online testing API (https://reqres.in/), and I should receive this response back with status code 200:

{"token": "QpwL5tke4Pnpja7X"}".

I couldn't find a tutorial to show a POST example. I have been searching online for the past 24 hours, but everything is about GET and not POST.

If anyone familiar with <iron-ajax> could review my code and help me get it to work or figure out how to write the correct code, it would be very helpful for a beginner like me.

Is my code correct with the body property?

Is the response the 200 status code or the token?

<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">

<dom-module id="my-view2">

  <template>
    <iron-ajax>
        auto
        method="post"
        url="https://reqres.in/api/login"
        handle-as="json"
        content-type="application/json"
        body =[{"email": "peter@klaven", "password": "cityslicka"}]
        on-response={{handleResponse}}

    </iron-ajax>

 response handling code goes here, how to show the response from the server here?

 It should show: {"token": "QpwL5tke4Pnpja7X"}

 {{handleResponse}}

  </template>

</dom-module>

Body:
Your HTML is malformed (perhaps a copy-paste typo?). The iron-ajax's attributes should be inside the opening tag like this:

<iron-ajax
  auto
  method="post"
  ...
>
</iron-ajax>

You probably meant to bind the handleResponse property to <iron-ajax>.lastResponse, which contains the response to the AJAX request.

<iron-ajax last-response={{handleResponse}} ...>

Note that the binding of <p>{{handleResponse}}</p> would render the response object as [object Object]. If you want to see the response contents, you'll have to use a computed binding that returns a string (e.g., with JSON.stringify()) like this:

// <template>
<p>json(handleResponse)</p>

// <script>
class XFoo extends Polymer.Element {
  ...
  json(obj) {
    return JSON.stringify(obj);
  }
}

The attribute value of <iron-ajax>.body should be single-quoted like this:

<iron-ajax body='[{"foo": "bar"}]'>

The full example should look something like this:

<dom-module id="x-foo">
  <template>
    <iron-ajax
              auto
              method="post"
              url="//httpbin.org/post"
              body='[{"foo": "{{foo}}"}]'
              handle-as="json"
              content-type="application/json"
              last-response="{{lastResponse}}"
              >
    </iron-ajax>
    <pre>[[json(lastResponse)]]</pre>
  </template>
  <script>
    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {
          foo: {
            type: String,
            value: 'bar'
          }
        }
      }

      json(obj) {
        return JSON.stringify(obj, null, 2);
      }
    }
    customElements.define(XFoo.is, XFoo);
  </script>
</dom-module>

demo


问:
WPF Dynamic Icon Wierdness
I have an WPF application that has a dynamic icon.  Three emoji icons depending on apps state (Happy, Sad, Thinking).
I have a Binding on the Icon, with a ValueConvertor doing the work and it works great.

Or so I thought.

If I run the .exe directly from the directory, it works exactly as planned.

If I run the app via a shortcut (on the desktop), it does not show
any of the emoji, and just the default icon. (Yes the shortcut has
Start in Field set correctly)

It is almost like the it cant find the resource; example: icon = @"pack://application:,,,/Media/emojiSad.ico" because it is being run from the desktop.

答:
Is your icon's build action property set to 'Resource'?

Nomatter where you deploy your project from, it should almost always pick up your image if its Build Action is set to 'Resource'

Title: WPF Dynamic Icon Wierdness


问:
Convert tf.string character array to vector of 1-hot-encoded float32 arrays?
I'm writing a feature engineering method for my TensorFlow model. I am trying to convert a tf.string to a vector of 1-hot encodings based on the characters in it.

Specifically, lets say I have a TF input string of "UDRLURDL" (In my case, each character corresponds to a direction.). I want to convert that string to a vector of say 1-hot encoded float32s. We have 4 characters (UDRL), so the 1-hot encoded output would be

```<code>[
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, 1],
    [1, 0, 0, 0],
    [0, 0, 1, 0],
    [0, 1, 0, 0],
    [0, 0, 0, 1],
]
</code>```

I more or less didn't see any TF ops that operated on individual characters within a string. Can we somehow treat a tf.string as a character array and do this conversion?

My final solution (inspired by @hars):

```<code>  original_string = tf.squeeze(original_string, axis=1)
  split_string = tf.string_split(original_string, delimiter="")

  table = tf.contrib.lookup.index_table_from_tensor(
      mapping=tf.constant(["U", "D", "L", "R"]), num_oov_buckets=0)
  indices = table.lookup(split_string.values)
  embeddings = tf.constant([[1, 0, 0, 0],
                            [0, 1, 0, 0],
                            [0, 0, 1, 0],
                            [0, 0, 0, 1]])
  encoded = tf.nn.embedding_lookup(embeddings, indices)
</code>```

答:
I prefer use one hot instead of embedding_lookup.

```<code>import tensorflow as tf

vocabulary = "UDLR"
original_string = "UDLRUDLR"
mapping_characters = tf.string_split([vocabulary], delimiter="")
input_characters = tf.string_split([original_string], delimiter="")
table = tf.contrib.lookup.index_table_from_tensor(
    mapping=mapping_characters.values, default_value=0)
encoded = tf.one_hot(table.lookup(input_characters.values),
                     len(vocabulary), dtype=tf.int8)
tf.InteractiveSession().as_default()
tf.tables_initializer().run()
print(encoded.eval())
</code>```

result:

```<code>[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]
 [1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]
</code>```

Body:
I'm writing a feature engineering method for my TensorFlow model. I am trying to convert a tf.string to a vector of 1-hot encodings based on the characters in it.

Specifically, lets say I have a TF input string of "UDRLURDL" (In my case, each character corresponds to a direction.). I want to convert that string to a vector of say 1-hot encoded float32s. We have 4 characters (UDRL), so the 1-hot encoded output would be

[
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, 1],
    [1, 0, 0, 0],
    [0, 0, 1, 0],
    [0, 1, 0, 0],
    [0, 0, 0, 1],
]

I more or less didn't see any TF ops that operated on individual characters within a string. Can we somehow treat a tf.string as a character array and do this conversion?

My final solution (inspired by @hars):

  original_string = tf.squeeze(original_string, axis=1)
  split_string = tf.string_split(original_string, delimiter="")

  table = tf.contrib.lookup.index_table_from_tensor(
      mapping=tf.constant(["U", "D", "L", "R"]), num_oov_buckets=0)
  indices = table.lookup(split_string.values)
  embeddings = tf.constant([[1, 0, 0, 0],
                            [0, 1, 0, 0],
                            [0, 0, 1, 0],
                            [0, 0, 0, 1]])
  encoded = tf.nn.embedding_lookup(embeddings, indices)

Body:
I prefer use one hot instead of embedding_lookup.

import tensorflow as tf

vocabulary = "UDLR"
original_string = "UDLRUDLR"
mapping_characters = tf.string_split([vocabulary], delimiter="")
input_characters = tf.string_split([original_string], delimiter="")
table = tf.contrib.lookup.index_table_from_tensor(
    mapping=mapping_characters.values, default_value=0)
encoded = tf.one_hot(table.lookup(input_characters.values),
                     len(vocabulary), dtype=tf.int8)
tf.InteractiveSession().as_default()
tf.tables_initializer().run()
print(encoded.eval())

result:

[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]
 [1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]


问:
Why am I getting an "End of Statement" compile error in my Excel VBA code?
Below is my code in VBA:

```<code>Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

If Hamza_Variable = 7 Then

MsgBox Hamza_Variable & " Is da bomb"

Elself Hamza_Variable > 7 Then

MsgBox Hamza_Variable & " Is da bigger bomb"

Else

MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End If
</code>```

It is continuously giving the compile error "End of Statement" on the following line:

```<code>Elself Hamza_Variable > 7 Then
</code>```

It highlights Then and gives this error.

答:
Since you are starting to learn, maybe you should get familair with Select Case statement:

```<code>Option Explicit

Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

Select Case Hamza_Variable
    Case 7
        MsgBox Hamza_Variable & " Is da bomb"
    Case Is > 7
        MsgBox Hamza_Variable & " Is da bigger bomb"
    Case Else
        MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End Select

End Sub
</code>```

Body:
Below is my code in VBA:

Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

If Hamza_Variable = 7 Then

MsgBox Hamza_Variable & " Is da bomb"

Elself Hamza_Variable > 7 Then

MsgBox Hamza_Variable & " Is da bigger bomb"

Else

MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End If

It is continuously giving the compile error "End of Statement" on the following line:

Elself Hamza_Variable > 7 Then

It highlights Then and gives this error.

Body:
Since you are starting to learn, maybe you should get familair with Select Case statement:

Option Explicit

Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

Select Case Hamza_Variable
    Case 7
        MsgBox Hamza_Variable & " Is da bomb"
    Case Is > 7
        MsgBox Hamza_Variable & " Is da bigger bomb"
    Case Else
        MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End Select

End Sub


问:
XAML - Binding Group Header In Group Header Style
Not trying to post a duplicate of this thread:
WPF - Binding to current item from within group header style

I got the binding working.  I'm stil unclear why it works.    This part of the XAML sets up the group item and binds the Texbox to the text.  What I don't understand is the Binding to the 'Name' property.  What is 'Name' a property of? The group header?  Until I found the linked thread I was trying to bind to a property on the items in the data grid.

```<code> <ControlTemplate TargetType="{x:Type GroupItem}">
      <Expander IsExpanded="True"
                Background="#FF112255"
                BorderBrush="#FF002255"
                Foreground="#FFEEEEEE"
                BorderThickness="1,1,1,5">
         <Expander.Header>
           <StackPanel Orientation="Horizontal">
              <TextBlock FontWeight="Bold"
                         Text="SVC Node: "/>
                 <TextBlock FontWeight="Bold"
                            Text="{Binding Name}"/>
             </StackPanel>
           </Expander.Header>
         <Expander.Content>
        <ItemsPresenter />
       </Expander.Content>
      </Expander>
  </ControlTemplate>
</code>```

答:
if your model contains the Name property and also GroupItem's DataContext contains  same model object then Name property visible and able to access inside the control template. So that name property binding works in TextBlock.

Updated:
 based on my analysis , corresponding grouped property has assigned internally into group item's Name property, SO that it automatically derived to its childs,

Body:
Not trying to post a duplicate of this thread:
WPF - Binding to current item from within group header style

I got the binding working.  I'm stil unclear why it works.    This part of the XAML sets up the group item and binds the Texbox to the text.  What I don't understand is the Binding to the 'Name' property.  What is 'Name' a property of? The group header?  Until I found the linked thread I was trying to bind to a property on the items in the data grid.

 <ControlTemplate TargetType="{x:Type GroupItem}">
      <Expander IsExpanded="True"
                Background="#FF112255"
                BorderBrush="#FF002255"
                Foreground="#FFEEEEEE"
                BorderThickness="1,1,1,5">
         <Expander.Header>
           <StackPanel Orientation="Horizontal">
              <TextBlock FontWeight="Bold"
                         Text="SVC Node: "/>
                 <TextBlock FontWeight="Bold"
                            Text="{Binding Name}"/>
             </StackPanel>
           </Expander.Header>
         <Expander.Content>
        <ItemsPresenter />
       </Expander.Content>
      </Expander>
  </ControlTemplate>


问:
window.open being flagged as a pop-up
I'm trying to figure out how I can bypass the pop blocking issue when using window.open. Here is the code I'm working on.

The first script I've built a script uses bit.ly API in shortening a URL address. Basically it gets the parameters then passes it to the API.

Then the second script calls the get_short_url function in order to share the bit.ly url via twitter using an on-click event. Unfortunately window.open seems to be flagged as a pop up by the browser. Is there way to bypass this

```<code><script>
var base_url      = window.location.origin,
    hash_bang     = "/#/sign-up?referral=",
    login         = "login",
    api_key       = "api_key";

function get_short_url(login, api_key, func, value) {
    var value = document.getElementById('input-refcode').value;

    $.getJSON(
        "https://api-ssl.bitly.com//v3/shorten?callback=?",
        {
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": base_url + hash_bang + value
        },

        function(response)
        {
            func(response.data.url);
        }
    );
}
</script>
</code>```

```<code><script>

$('#twitter').on('click', function() {

    get_short_url(login, api_key, function(short_url) {
        win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
        win.focus();
    });
});
</script>
</code>```

答:
I've got this working on Firefox, Chrome & internet explorer.

var url = 'https://twitter.com/intent/tweet?text='+encodeURIComponent('Get Free Rides at Electric Studio! Sign up xx to purchase your first timer package! After your first ride, you get 1 ride on us! https://www.electricstudio.ph/');
console.log(url);
var win = window.open(url, '_blank');
win.focus();```

Title: window.open being flagged as a pop-up


问:
Customize field in blackberry
Can you please tell me how to customize my components at a BlackBerry?

E.g. I need a verticalfieldManager which will have a label field, an image, placed one after the other. Also this verticalFieldManager should be in the center of the screen, it should not start from the immediate left or right of the screen.

I want a border for this verticalFieldManager, too.

答:
You can also create custom manager and set the position of contents as per your choice and requirement

now add your custom manager to a manager say basemanager and add this basemanager to screen

Title: Customize field in blackberry


问:
Youtube API with Retrofit2 not able to parse response(Error: PlaylistItemListResponse has type PageInfo got LinkedHashMap)
I am trying to use Youtube API with Retrfoit2 on Android but both Jackson/JSON converters are not able to parse objects.

YoutubeService

```<code>public interface YoutubeService {
    @GET("playlistItems?part=snippet%2CcontentDetails")
    Observable<PlaylistItemListResponse> getVideos(@Query("maxResults") Integer maxResults,
                                               @Query("pageToken")String pageToken,
                                               @Query("playlistId")String playlistId,
                                               @Query("key")String key);
}
</code>```

Here is how I am using it:

```<code>Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(YouTube.DEFAULT_BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(JacksonConverterFactory.create())
            .build();
    youtubeService = retrofit.create(YoutubeService.class);
</code>```

Below is the error I am getting:

```<code>reactivex.exceptions.OnErrorNotImplementedException: field com.google.api.services.youtube.model.PlaylistItemListResponse.pageInfo has type com.google.api.services.youtube.model.PageInfo, got java.util.LinkedHashMap (through reference chain: com.google.api.services.youtube.model.PlaylistItemListResponse["pageInfo"])
</code>```

This is model for PlaylistItemResponse

Java files for PlaylistItemResponse

This is response

Can someone guide me how to solve this?

答:
I can't understand deeper with your problem but try to change like below.

1.Make it With Gson

addConverterFactory(GsonConverterFactory.create(gson))

2.change your model class PlaylistItemListResponse with below.

Link of model class

because its all about your model class issue.

Happy coding

Body:
I am trying to use Youtube API with Retrfoit2 on Android but both Jackson/JSON converters are not able to parse objects.

YoutubeService

public interface YoutubeService {
    @GET("playlistItems?part=snippet%2CcontentDetails")
    Observable<PlaylistItemListResponse> getVideos(@Query("maxResults") Integer maxResults,
                                               @Query("pageToken")String pageToken,
                                               @Query("playlistId")String playlistId,
                                               @Query("key")String key);
}

Here is how I am using it:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(YouTube.DEFAULT_BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(JacksonConverterFactory.create())
            .build();
    youtubeService = retrofit.create(YoutubeService.class);

Below is the error I am getting:

reactivex.exceptions.OnErrorNotImplementedException: field com.google.api.services.youtube.model.PlaylistItemListResponse.pageInfo has type com.google.api.services.youtube.model.PageInfo, got java.util.LinkedHashMap (through reference chain: com.google.api.services.youtube.model.PlaylistItemListResponse["pageInfo"])

This is model for PlaylistItemResponse

Java files for PlaylistItemResponse

This is response

Can someone guide me how to solve this?


问:
Angular Schema Form - arrayIndex as a parameter for button onClick
How can I pass the arrayIndex as a parameter to the function in onClick? Eg:

```<code>{
  key:"someKey"
  type:"array",
  items:[
    {
      "key":"someKey[].itemNo"
    },
    {
      "type":"button",
      "onClick":"someFunction(someKey[arrayIndex].itemNo)"
    }
  ]
}
</code>```

arrayIndex in "condition" works. But in the function, undefined is what I am getting. I am able to access the entire model or the form's data in someFunction (i.e. i can access someKey), but I need access to the particular item in the array(i.e. someKey[index]).

UPDATED as requested:
(Taken from schema form example page)

See the performAction button. I need the email in the button's context to be passed into a function.

Form:

```<code>[

  {
    "key": "comments",
    "add": "New",
    "style": {
      "add": "btn-success"
    },
    "items": [
      "comments[].name",
      "comments[].email",
      {
        "key": "comments[].spam",
        "type": "checkbox",
        "title": "Yes I want spam.",
        "condition": "model.comments[arrayIndex].email"
      },
      {
        "key": "comments[].comment",
        "type": "textarea"
      },
      {
        "type":"button",
        "onClick":"performAction(comments[arrayIndex].email)",
        "title":"Perform Action"
      }
    ]
  },
  {
    "type": "submit",
    "style": "btn-info",
    "title": "OK"
  }
]
</code>```

Schema:

```<code>{
  "type": "object",
  "title": "Comment",
  "required": [
    "comments"
  ],
  "properties": {
    "comments": {
      "type": "array",
      "maxItems": 2,
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "title": "Name",
            "type": "string"
          },
          "email": {
            "title": "Email",
            "type": "string",
            "pattern": "^\\S+@\\S+$",
            "description": "Email will be used for evil."
          },
          "spam": {
            "title": "Spam",
            "type": "boolean",
            "default": true
          },
          "comment": {
            "title": "Comment",
            "type": "string",
            "maxLength": 20,
            "validationMessage": "Don't be greedy!"
          }
        },
        "required": [
          "name",
          "comment"
        ]
      }
    }
  }
}
</code>```

答: This was added in v1.0.0-alpha.1 with the addition of arrayIndices.

Body:
How can I pass the arrayIndex as a parameter to the function in onClick? Eg:

{
  key:"someKey"
  type:"array",
  items:[
    {
      "key":"someKey[].itemNo"
    },
    {
      "type":"button",
      "onClick":"someFunction(someKey[arrayIndex].itemNo)"
    }
  ]
}

arrayIndex in "condition" works. But in the function, undefined is what I am getting. I am able to access the entire model or the form's data in someFunction (i.e. i can access someKey), but I need access to the particular item in the array(i.e. someKey[index]).

UPDATED as requested:
(Taken from schema form example page)

See the performAction button. I need the email in the button's context to be passed into a function.

Form:

[

  {
    "key": "comments",
    "add": "New",
    "style": {
      "add": "btn-success"
    },
    "items": [
      "comments[].name",
      "comments[].email",
      {
        "key": "comments[].spam",
        "type": "checkbox",
        "title": "Yes I want spam.",
        "condition": "model.comments[arrayIndex].email"
      },
      {
        "key": "comments[].comment",
        "type": "textarea"
      },
      {
        "type":"button",
        "onClick":"performAction(comments[arrayIndex].email)",
        "title":"Perform Action"
      }
    ]
  },
  {
    "type": "submit",
    "style": "btn-info",
    "title": "OK"
  }
]

Schema:

{
  "type": "object",
  "title": "Comment",
  "required": [
    "comments"
  ],
  "properties": {
    "comments": {
      "type": "array",
      "maxItems": 2,
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "title": "Name",
            "type": "string"
          },
          "email": {
            "title": "Email",
            "type": "string",
            "pattern": "^\\S+@\\S+$",
            "description": "Email will be used for evil."
          },
          "spam": {
            "title": "Spam",
            "type": "boolean",
            "default": true
          },
          "comment": {
            "title": "Comment",
            "type": "string",
            "maxLength": 20,
            "validationMessage": "Don't be greedy!"
          }
        },
        "required": [
          "name",
          "comment"
        ]
      }
    }
  }
}


问:
How do i fix my spawning script from randomly stopping the spawning of enemies?
I have a simple script that is supposed to spawn zombies with time delays that can be inputted. The script seems to work fine however, after I move my character for a while, the gameobject which is running the script stops spawning zombies.If my character stands still, the zombies will continue to spawn. The red arrow is pointing to the gameObject that is spawning the zombies.

```<code>using UnityEngine;
using System.Collections;

public class spawn : MonoBehaviour
{
    public GameObject zombie;
    public float delayTime = 4f;

    IEnumerator Start()
    {
        var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
        yield return new WaitForSeconds(delayTime);
        StartCoroutine(Start());
    }
}
</code>```

Scene setup is as follows:

答:
First separate your spawning function from your Start function to avoid confusion.

```<code>void Start()
{
    StartCoroutine(SpawningRoutine());
}
</code>```

Then you want your coroutine to continue spawning forever? You need a loop inside the coroutine. In the example below I made an infinite loop but you could have a counter for the number of zombies you want for example.

```<code>IEnumerator SpawningRoutine()
{
    while(true)
    {
        var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
        yield return new WaitForSeconds(delayTime);
    }
}
</code>```

Lastly remember to put this spawn script on an object that is not a zombie. Have a separate spawn object with only this script on it. You probably do this already.

Edit in response to logging:

Add a logging script to your zombie prefab like so:

```<code>private static int zombieCounter = 0;
void Start()
{
    Debug.Log("Number of zombies spawned so far: " + zombieCounter++);
}
</code>```

Body:
I have a simple script that is supposed to spawn zombies with time delays that can be inputted. The script seems to work fine however, after I move my character for a while, the gameobject which is running the script stops spawning zombies.If my character stands still, the zombies will continue to spawn. The red arrow is pointing to the gameObject that is spawning the zombies.

using UnityEngine;
using System.Collections;

public class spawn : MonoBehaviour
{
    public GameObject zombie;
    public float delayTime = 4f;

    IEnumerator Start()
    {
        var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
        yield return new WaitForSeconds(delayTime);
        StartCoroutine(Start());
    }
}

Scene setup is as follows:

Body:
First separate your spawning function from your Start function to avoid confusion.

void Start()
{
    StartCoroutine(SpawningRoutine());
}

Then you want your coroutine to continue spawning forever? You need a loop inside the coroutine. In the example below I made an infinite loop but you could have a counter for the number of zombies you want for example.

IEnumerator SpawningRoutine()
{
    while(true)
    {
        var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
        yield return new WaitForSeconds(delayTime);
    }
}

Lastly remember to put this spawn script on an object that is not a zombie. Have a separate spawn object with only this script on it. You probably do this already.

Edit in response to logging:

Add a logging script to your zombie prefab like so:

private static int zombieCounter = 0;
void Start()
{
    Debug.Log("Number of zombies spawned so far: " + zombieCounter++);
}


问:
Treat a string as a file in python
In the interest of not rewriting an open source library,  I want to treat a string of text as a file in python 3.

Suppose I have the file contents as a string:

```<code>not_a_file = 'there is a lot of blah blah in this so-called file'
</code>```

I want to treat this variable, i.e. the contents of a file, as a  path-like object that way I can use it in python's open() function.

Here is a simple example which shows my dilemma:

```<code>not_a_file = 'there is a lot of blah blah in this so-called file'
file_ptr = open(not_a_file, 'r')
</code>```

Clearly the example doesn't work because not_a_file is not a path-like object.  I don't want to write a file nor create any temporary directories for portability purposes.

With that said, I need is to solve this mystery:

```<code>not_a_file = 'there is a lot of blah blah in this so-called file'
... Something goes here ...
file_ptr = open(also_not_a_file, 'r')
</code>```

What I've Tried So Far

I've looked into StringIO and tried using that as a path-like object and no dice:

import StringIO
output = StringIO.StringIO()
output.write('First line.\n')
file_ptr = open(output,'r')

Well this doesn't work because StringIO isn't a path-like object.

I've tried tempfile in a similar fashion with no success.

import tempfile
tp = tempfile.TemporaryFile()
tp.write(b'there is a lot of blah blah in this so-called file')
open(tp,'r')

Finally I tried mmap to see if I can write the string into memory and then open the memory pointer with open with no success.

Any help is appreciated! :-)

Edit 1: What I'm thinking of to possibly solve problem

So pathlib.PurePath can work with open() if PurePath is initialized to a file.  Perhaps I can create an instance of a class that inherits PurePath and when read by open(), it reads my string.  Let me give an example:

```<code>from pathlib import PurePath

not_a_file = 'there is a lot of blah blah in this so-called file'
class Magic(PurePath):
    def __init__(self, string_input):
        self.file_content = string_input
        PurePath.__init__(self, 'Something magical goes here')
    #some more magic happens in this class

also_not_a_file = Magic(not_a_file)
fp = open(also_not_a_file,'r')
print(fp.readlines()) # 'there is a lot of blah blah in this so-called file'
</code>```

答:
You can create a temporary file and pass its name to open:

On Unix:

```<code>tp = tempfile.NamedTemporaryFile()
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.flush()
open(tp.name, 'r')
</code>```

On Windows, you need to close the temporary file before it can be opened:

```<code>tp = tempfile.NamedTemporaryFile(delete=False)
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.close()
open(tp.name, 'r')
</code>```

You then become responsible for deleting the file once you're done using it.

Title: Treat a string as a file in python

Body:
In the interest of not rewriting an open source library,  I want to treat a string of text as a file in python 3.

Suppose I have the file contents as a string:

not_a_file = 'there is a lot of blah blah in this so-called file'

I want to treat this variable, i.e. the contents of a file, as a  path-like object that way I can use it in python's open() function.

Here is a simple example which shows my dilemma:

not_a_file = 'there is a lot of blah blah in this so-called file'
file_ptr = open(not_a_file, 'r')

Clearly the example doesn't work because not_a_file is not a path-like object.  I don't want to write a file nor create any temporary directories for portability purposes.

With that said, I need is to solve this mystery:

not_a_file = 'there is a lot of blah blah in this so-called file'
... Something goes here ...
file_ptr = open(also_not_a_file, 'r')

What I've Tried So Far

I've looked into StringIO and tried using that as a path-like object and no dice:

import StringIO
output = StringIO.StringIO()
output.write('First line.\n')
file_ptr = open(output,'r')

Well this doesn't work because StringIO isn't a path-like object.

I've tried tempfile in a similar fashion with no success.

import tempfile
tp = tempfile.TemporaryFile()
tp.write(b'there is a lot of blah blah in this so-called file')
open(tp,'r')

Finally I tried mmap to see if I can write the string into memory and then open the memory pointer with open with no success.

Any help is appreciated! :-)

Edit 1: What I'm thinking of to possibly solve problem

So pathlib.PurePath can work with open() if PurePath is initialized to a file.  Perhaps I can create an instance of a class that inherits PurePath and when read by open(), it reads my string.  Let me give an example:

from pathlib import PurePath

not_a_file = 'there is a lot of blah blah in this so-called file'
class Magic(PurePath):
    def __init__(self, string_input):
        self.file_content = string_input
        PurePath.__init__(self, 'Something magical goes here')
    #some more magic happens in this class

also_not_a_file = Magic(not_a_file)
fp = open(also_not_a_file,'r')
print(fp.readlines()) # 'there is a lot of blah blah in this so-called file'

Body:
You can create a temporary file and pass its name to open:

On Unix:

tp = tempfile.NamedTemporaryFile()
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.flush()
open(tp.name, 'r')

On Windows, you need to close the temporary file before it can be opened:

tp = tempfile.NamedTemporaryFile(delete=False)
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.close()
open(tp.name, 'r')

You then become responsible for deleting the file once you're done using it.


问:
making a single xdf files from 2 other xdf files
I am using the RevoScaleR package in MS Visual Studio, and I'm stuck on a step.

I have one XDF file with a column called "Total_Admits_Pred". I have another XDF file with a column called "Total_Admits".

Both XDF files have the same number of rows. I would like to combine the two XDF files into a single XDF file with both of these columns. How could I do that?

Thanks!

Thomas

答:
You can add columns to an existing xdf file with rxDataStep:

```<code>xdf1 <- RxXdfData("file1.xdf")  # dataset containing Total_Admits_Pred
xdf2 <- RxXdfData("file2.xdf")  # dataset containing Total_Admits

rxDataStep(xdf1, xdf2, varsToKeep="Total_Admits_Pred", append="cols")
</code>```

This will result in file2.xdf containing all its pre-existing columns, plus Total_Admits_Pred.

Another way is to use the dplyrXdf package:

```<code>devtools::install_github("RevolutionAnalytics/dplyrXdf")

df <- data.frame(Total_Admits_Pred=xdf1$Total_Admits_Pred,
                 Total_Admits=xdf2$Total_Admits)
</code>```

This creates an in-memory data frame with just the two columns you want. The advantage of this, over the other answer, is that it reads only those two columns into memory.

Body:
You can add columns to an existing xdf file with rxDataStep:

xdf1 <- RxXdfData("file1.xdf")  # dataset containing Total_Admits_Pred
xdf2 <- RxXdfData("file2.xdf")  # dataset containing Total_Admits

rxDataStep(xdf1, xdf2, varsToKeep="Total_Admits_Pred", append="cols")

This will result in file2.xdf containing all its pre-existing columns, plus Total_Admits_Pred.

Another way is to use the dplyrXdf package:

devtools::install_github("RevolutionAnalytics/dplyrXdf")

df <- data.frame(Total_Admits_Pred=xdf1$Total_Admits_Pred,
                 Total_Admits=xdf2$Total_Admits)

This creates an in-memory data frame with just the two columns you want. The advantage of this, over the other answer, is that it reads only those two columns into memory.


问:
DOM pdf codeigniter: Class 'DOMPDF' not found error
I trying to add DOM PDF library to my codeigniter application

1.Download dompdf  and copy the dompdf folder to libraries folder.

2.Create  file named Dompdf.php in libraries folder

In my controller

```<code>public function pdf_test()
   {
       $this->load->library('Dompdf');
       $this->Dompdf->loadHtml('hello world');
       $this->pdf->render();
       $this->pdf->stream("welcome.pdf");
   }
</code>```

Dompdf.php

```<code><?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * CodeIgniter PDF Library
 *
 * Generate PDF's in your CodeIgniter applications.
 *
 * @package         CodeIgniter
 * @subpackage      Libraries
 * @category        Libraries
 * @author          Chris Harvey
 * @license         MIT License
 * @link            https://github.com/chrisnharvey/CodeIgniter-PDF-Generator-Library
 */
require_once(dirname(__FILE__) . '/dompdf/autoload.inc.php');
class Pdf extends DOMPDF
{
    /**
     * Get an instance of CodeIgniter
     *
     * @access  protected
     * @return  void
     */
    protected function ci()
    {
        return get_instance();
    }
    /**
     * Load a CodeIgniter view into domPDF
     *
     * @access  public
     * @param   string  $view The view to load
     * @param   array   $data The view data
     * @return  void
     */
    public function load_view($view, $data = array())
    {
        $html = $this->ci()->load->view($view, $data, TRUE);
        $this->load_html($html);
    }
}
</code>```

But i will this error.

Message: Class 'DOMPDF' not found

Filename: libraries/Dompdf.php

Line Number: 16

I am  using latest DOMPDF

答:
in my case. i use this

$dompdf = new Dompdf\DOMPDF();

```<code>require_once(_MAP."libraries/dompdf/autoload.inc.php");
$dompdf = new Dompdf\DOMPDF();
$html = 'rats :)';
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
</code>```

Body:
I trying to add DOM PDF library to my codeigniter application

1.Download dompdf  and copy the dompdf folder to libraries folder.

2.Create  file named Dompdf.php in libraries folder

In my controller

public function pdf_test()
   {
       $this->load->library('Dompdf');
       $this->Dompdf->loadHtml('hello world');
       $this->pdf->render();
       $this->pdf->stream("welcome.pdf");
   }

Dompdf.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * CodeIgniter PDF Library
 *
 * Generate PDF's in your CodeIgniter applications.
 *
 * @package         CodeIgniter
 * @subpackage      Libraries
 * @category        Libraries
 * @author          Chris Harvey
 * @license         MIT License
 * @link            https://github.com/chrisnharvey/CodeIgniter-PDF-Generator-Library
 */
require_once(dirname(__FILE__) . '/dompdf/autoload.inc.php');
class Pdf extends DOMPDF
{
    /**
     * Get an instance of CodeIgniter
     *
     * @access  protected
     * @return  void
     */
    protected function ci()
    {
        return get_instance();
    }
    /**
     * Load a CodeIgniter view into domPDF
     *
     * @access  public
     * @param   string  $view The view to load
     * @param   array   $data The view data
     * @return  void
     */
    public function load_view($view, $data = array())
    {
        $html = $this->ci()->load->view($view, $data, TRUE);
        $this->load_html($html);
    }
}

But i will this error.

Message: Class 'DOMPDF' not found

Filename: libraries/Dompdf.php

Line Number: 16

I am  using latest DOMPDF

Body:
in my case. i use this

$dompdf = new Dompdf\DOMPDF();

require_once(_MAP."libraries/dompdf/autoload.inc.php");
$dompdf = new Dompdf\DOMPDF();
$html = 'rats :)';
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");


问:
Custom iterator on a namedtuple
Is there a pythonic way to have a custom iterator on a namedtuple?

A custom iterator appears to require an index attribute. Normally a namedtuple has a "__slots__ = ()" declaration, which avoids the overhead of a dynamic dict and reduces latency in attribute lookup. However, this breaks the iterator (AttributeError: 'Path' object has no attribute '_iidx'). Adding _iidx to the slots results in nonempty __slots__ not supported

Context: I will be working with a large number of Bezier splines. Each spline consists of a list of 'knot' points, and list of pairs of control points. By commenting out the __slots__ = () declaration, my code works. But, at the cost of having a per-instance dynamic dict. The overhead from the dict in attribute lookup is probably negligible compared to everything else, but it doesn't seem pythonic.

```<code>class Path(namedtuple('Path', "knots ctrl_pts")):
#    __slots__ = ()

    @property
    def SVG(self):
        s = 'M %s' % self.knots[0].bare
        for cps, k in self:
            s += ' C %s %s' % (cps.bare, k.bare)
        return s

    def __iter__(self):
        self._iidx = 0
        return self

    def __next__(self):
        if self._iidx == len(self.ctrl_pts):
            raise StopIteration
        i = self._iidx
        self._iidx += 1
        return (self.ctrl_pts[i], self.knots[i+1])
</code>```

The SVG method uses the iterator to make SVG formating trivial. This:

```<code>print('<path d="%s" stroke="black" stroke-width="1" fill="blue" />'
       % path.SVG)
</code>```

Results in:

```<code><path d="M 318.9 179.4 C 279.1 177.6 199.2 270.3 222.4 298.1 C 245.5
326.0 371.6 289.1 420.4 297.0 C 469.2 304.9 440.6 357.6 399.6 352.4
C 388.5 350.9 389.7 345.0 400.4 347.6 C 440.1 357.4 469.4 309.2 419.6
303.0 C 369.8 296.7 240.9 332.5 217.6 301.9 C 194.4 271.2 276.9 174.1
319.1 174.6 C 330.3 174.7 329.9 179.9 318.9 179.4" stroke="black"
stroke-width="1" fill="blue" />
</code>```

But it also is trivial to use in the on_draw(self, wid, cr): of a Gtk.DrawingArea:

```<code>        path = self.coords.outline_path
        cr.set_source_rgb(*LT_BLUE)
        cr.move_to(*path.knots[0])
        for (c,k) in path:
            cr.curve_to(*c.P1, *c.P2, *k)
        cr.fill_preserve()
        cr.set_source_rgb(*BLACK)
        cr.stroke()
</code>```

Note: the 'knots' is a List[Point] and 'ctrl_pts' is a List[ControlPoints]:

```<code>class Point(namedtuple('Point', "x y")):
    __slots__ = ()
    """<bunch of stuff not shown>"""
    @property
    def bare(self):
        return '%.1f %.1f' % (self.x, self.y)

class ControlPoints(namedtuple('ControlPoints', "P1 P2")):
    __slots__ = ()
    @property
    def bare(self):
        return '%s %s' % (self.P1.bare, self.P2.bare)
</code>```

I am very new to python and I am certain this can be done in a more pythonic way.

答:
Rather than implementing the iterator protocol manually, make __iter__ a generator for the values you want.  The generator object implements the iterator protocol for you.

```<code>class Path(namedtuple('Path', "knots ctrl_pts")):

    @property
    def SVG(self):
        s = 'M %s' % self.knots[0].bare
        for cps, k in self:
            s += ' C %s %s' % (cps.bare, k.bare)
        return s

    def __iter__(self):
        for t in zip(self.ctrl_pts, self.knots[1:]):
            yield t
</code>```

If you only expect __iter__ to be used as part of SVG, you really don't need it, and can use something like this:

```<code>class Path(namedtuple('Path', "knots ctrl_pts")):

    @property
    def SVG(self):
        return 'M %s%s' % (self.knots[0].bare,
                           ''.join([' C %s %s' % (cps.bare, k.bare)
                                    for cps, k in zip(self.ctrl_pts, self.knots[1:])]))
</code>```

Title: Custom iterator on a namedtuple

Body:
Is there a pythonic way to have a custom iterator on a namedtuple?

A custom iterator appears to require an index attribute. Normally a namedtuple has a "__slots__ = ()" declaration, which avoids the overhead of a dynamic dict and reduces latency in attribute lookup. However, this breaks the iterator (AttributeError: 'Path' object has no attribute '_iidx'). Adding _iidx to the slots results in nonempty __slots__ not supported

Context: I will be working with a large number of Bezier splines. Each spline consists of a list of 'knot' points, and list of pairs of control points. By commenting out the __slots__ = () declaration, my code works. But, at the cost of having a per-instance dynamic dict. The overhead from the dict in attribute lookup is probably negligible compared to everything else, but it doesn't seem pythonic.

class Path(namedtuple('Path', "knots ctrl_pts")):
#    __slots__ = ()

    @property
    def SVG(self):
        s = 'M %s' % self.knots[0].bare
        for cps, k in self:
            s += ' C %s %s' % (cps.bare, k.bare)
        return s

    def __iter__(self):
        self._iidx = 0
        return self

    def __next__(self):
        if self._iidx == len(self.ctrl_pts):
            raise StopIteration
        i = self._iidx
        self._iidx += 1
        return (self.ctrl_pts[i], self.knots[i+1])

The SVG method uses the iterator to make SVG formating trivial. This:

print('<path d="%s" stroke="black" stroke-width="1" fill="blue" />'
       % path.SVG)

Results in:

<path d="M 318.9 179.4 C 279.1 177.6 199.2 270.3 222.4 298.1 C 245.5
326.0 371.6 289.1 420.4 297.0 C 469.2 304.9 440.6 357.6 399.6 352.4
C 388.5 350.9 389.7 345.0 400.4 347.6 C 440.1 357.4 469.4 309.2 419.6
303.0 C 369.8 296.7 240.9 332.5 217.6 301.9 C 194.4 271.2 276.9 174.1
319.1 174.6 C 330.3 174.7 329.9 179.9 318.9 179.4" stroke="black"
stroke-width="1" fill="blue" />

But it also is trivial to use in the on_draw(self, wid, cr): of a Gtk.DrawingArea:

        path = self.coords.outline_path
        cr.set_source_rgb(*LT_BLUE)
        cr.move_to(*path.knots[0])
        for (c,k) in path:
            cr.curve_to(*c.P1, *c.P2, *k)
        cr.fill_preserve()
        cr.set_source_rgb(*BLACK)
        cr.stroke()

Note: the 'knots' is a List[Point] and 'ctrl_pts' is a List[ControlPoints]:

class Point(namedtuple('Point', "x y")):
    __slots__ = ()
    """<bunch of stuff not shown>"""
    @property
    def bare(self):
        return '%.1f %.1f' % (self.x, self.y)

class ControlPoints(namedtuple('ControlPoints', "P1 P2")):
    __slots__ = ()
    @property
    def bare(self):
        return '%s %s' % (self.P1.bare, self.P2.bare)

I am very new to python and I am certain this can be done in a more pythonic way.

Body:
Rather than implementing the iterator protocol manually, make __iter__ a generator for the values you want.  The generator object implements the iterator protocol for you.

class Path(namedtuple('Path', "knots ctrl_pts")):

    @property
    def SVG(self):
        s = 'M %s' % self.knots[0].bare
        for cps, k in self:
            s += ' C %s %s' % (cps.bare, k.bare)
        return s

    def __iter__(self):
        for t in zip(self.ctrl_pts, self.knots[1:]):
            yield t

If you only expect __iter__ to be used as part of SVG, you really don't need it, and can use something like this:

class Path(namedtuple('Path', "knots ctrl_pts")):

    @property
    def SVG(self):
        return 'M %s%s' % (self.knots[0].bare,
                           ''.join([' C %s %s' % (cps.bare, k.bare)
                                    for cps, k in zip(self.ctrl_pts, self.knots[1:])]))


问:
Getting ORA-00001 and ORA-01438 errors when inserting data into a table
I have a problem trying to run this script where I got the error:

ORA-00001: unique constraint (constraint_name) violated

So, the thing is can't insert date into the table, and other error is:

ORA-01438: value larger than specified precision allowed for this column

```<code>CREATE TABLE TEST
(    TEST_ID        INT NOT NULL,
    COMPONENTS     VARCHAR2(30) NOT NULL,
    MATTER        VARCHAR2(2) NOT NULL,
    LIC            NUMBER(9, 2),
    MIC            NUMBER(9, 2),
    UIP            NUMBER(9, 2),
    CONSTRAINT TEST_pk PRIMARY KEY (TEST_ID));

--SEQUENCE TEST_ID

CREATE SEQUENCE SEQ_TEST_ID
 START WITH     1
 INCREMENT BY   1
 MINVALUE 1
 MAXVALUE 9999;

 --INSERTING VALUE TO TABLE

INSERT ALL

INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Food waste','OG','50.50','39.00','13.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Paper'     ,'OG','05.50','19.00','32.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Cardboard' ,'OG','00.00','00.00','10.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Plastic'       ,'OG','03.00','04.00','00.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Textiles'      ,'OG','03.00','06.00','04.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Ruber'     ,'OG','03.00','00.00','01.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Leather'       ,'OG','03.00','02.50','01.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Yard waste' ,'OG','00.00','00.00','15.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Wood'           ,'OG','03.00','05.50','02.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Misc. Organic','OG','03.00','04.00','00.00')

INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Glass'      ,'IG','05.50','05.50','08.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Tin Cans'       ,'IG','00.50','00.50','05.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Aluminum'       ,'IG','03.00','03.00','00.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Other metals'   ,'IG','00.00','00.00','02.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Drit,ash,etc'   ,'IG','20.50','15.50','05.00')
SELECT * FROM DUAL;
</code>```

答:
you can increaseur sequence cache size to 200,the default is 20.

```<code>alter sequence SEQ_TEST_ID cache 200;
</code>```

try agian.

ContentLicense: CC BY-SA 4.0

Body:
I have a problem trying to run this script where I got the error:

ORA-00001: unique constraint (constraint_name) violated

So, the thing is can't insert date into the table, and other error is:

ORA-01438: value larger than specified precision allowed for this column

CREATE TABLE TEST
(    TEST_ID        INT NOT NULL,
    COMPONENTS     VARCHAR2(30) NOT NULL,
    MATTER        VARCHAR2(2) NOT NULL,
    LIC            NUMBER(9, 2),
    MIC            NUMBER(9, 2),
    UIP            NUMBER(9, 2),
    CONSTRAINT TEST_pk PRIMARY KEY (TEST_ID));

--SEQUENCE TEST_ID

CREATE SEQUENCE SEQ_TEST_ID
 START WITH     1
 INCREMENT BY   1
 MINVALUE 1
 MAXVALUE 9999;

 --INSERTING VALUE TO TABLE

INSERT ALL

INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Food waste','OG','50.50','39.00','13.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Paper'     ,'OG','05.50','19.00','32.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Cardboard' ,'OG','00.00','00.00','10.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Plastic'       ,'OG','03.00','04.00','00.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Textiles'      ,'OG','03.00','06.00','04.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Ruber'     ,'OG','03.00','00.00','01.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Leather'       ,'OG','03.00','02.50','01.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Yard waste' ,'OG','00.00','00.00','15.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Wood'           ,'OG','03.00','05.50','02.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Misc. Organic','OG','03.00','04.00','00.00')

INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Glass'      ,'IG','05.50','05.50','08.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Tin Cans'       ,'IG','00.50','00.50','05.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Aluminum'       ,'IG','03.00','03.00','00.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Other metals'   ,'IG','00.00','00.00','02.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Drit,ash,etc'   ,'IG','20.50','15.50','05.00')
SELECT * FROM DUAL;

Body:
you can increaseur sequence cache size to 200,the default is 20.

alter sequence SEQ_TEST_ID cache 200;

try agian.


问:
Get scope from DOM element with $compileProvider.debugInfoEnabled(false);
I'm trying to take advantage of AngularJS new fetures. One of them is :

```<code>$compileProvider.debugInfoEnabled(false);
</code>```

The thing is that some pieces of my code rely on angular.element(el).scope() calls. So they won't work any longer.

Is there a way to rewrite angular.element(el).scope() expression to somehow get element's scope without debug info enabled?

答:
type in console:</p>

```<code>angular.reloadWithDebugInfo();
</code>```

Body:
I'm trying to take advantage of AngularJS new fetures. One of them is :

$compileProvider.debugInfoEnabled(false);

The thing is that some pieces of my code rely on angular.element(el).scope() calls. So they won't work any longer.

Is there a way to rewrite angular.element(el).scope() expression to somehow get element's scope without debug info enabled?

Body:
type in console:

angular.reloadWithDebugInfo();


问:
How to get value from JSON php
This is my JSON.

```<code>{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}
</code>```

My Questions are:

1. How to get OUT_STAT value?

2. How to get id_doc_proj value?

I am sorry if my questions are silly because i am new at get value from JSON.

Thanks in advance.

UPDATE

I am sorry if you are saying i duplicated Parsing JSON file with PHP. I have tried code from there but i don't get any JSON from my response. I don't know where is the mistake. If you want to help, this is my php script.

```<code><?php
    $file_path = "";
    $id_project = "16";
    $p_id_doc_proj = "50";
    $id_doc_type = "1";
    $id_user = "4";

    $url = $file_path.basename($_FILES['uploaded_file']['name']);

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url)){
        $ws = "http://172.xx.x.xx:xxxx/rest/com/acc/uw/in/httprest/apponline/uploadtrough/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";

        $opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));

        $context = stream_context_create($opts);

        $arrayLog=array();
        $data1 = file_get_contents($ws, false, $context);
        $result = json_decode($data1, true);;

        //$result = array("result" => "success");
    }else{
        $result = array("result" => "error");
    }

    echo json_encode($result);
?>
</code>```

The result should show my JSON above but it was null. Any answers will help me. Thanks in advance.

答:
```<code>$data="{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}";

$op=json_decode($data, true);

echo $op['OUT_STAT'];
echo $op['OUT_DATA'][0]['id_doc_proj'];
</code>```

http://php.net/json_deocde. it will make output as associative array. you can then use the result as you would do with an assoc array. you can also use var_dump() to introspect the structure.

Title: How to get value from JSON php

Body:
This is my JSON.

{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}

My Questions are:

1. How to get OUT_STAT value?

2. How to get id_doc_proj value?

I am sorry if my questions are silly because i am new at get value from JSON.

Thanks in advance.

UPDATE

I am sorry if you are saying i duplicated Parsing JSON file with PHP. I have tried code from there but i don't get any JSON from my response. I don't know where is the mistake. If you want to help, this is my php script.

<?php
    $file_path = "";
    $id_project = "16";
    $p_id_doc_proj = "50";
    $id_doc_type = "1";
    $id_user = "4";

    $url = $file_path.basename($_FILES['uploaded_file']['name']);

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url)){
        $ws = "http://172.xx.x.xx:xxxx/rest/com/acc/uw/in/httprest/apponline/uploadtrough/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";

        $opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));

        $context = stream_context_create($opts);

        $arrayLog=array();
        $data1 = file_get_contents($ws, false, $context);
        $result = json_decode($data1, true);;

        //$result = array("result" => "success");
    }else{
        $result = array("result" => "error");
    }

    echo json_encode($result);
?>

The result should show my JSON above but it was null. Any answers will help me. Thanks in advance.

Body:
$data="{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}";

$op=json_decode($data, true);

echo $op['OUT_STAT'];
echo $op['OUT_DATA'][0]['id_doc_proj'];

http://php.net/json_deocde. it will make output as associative array. you can then use the result as you would do with an assoc array. you can also use var_dump() to introspect the structure.


问:
How to use Eigen, the C++ template library for linear algebra?
I have an image processing algorithm which makes of matrices, I have my own matrix operation codes (Multiplication, Inverse...) with me. But the processor I use is ARM Cortex-A8 processor, which has NEON co-processor for vectorization, as matrix operations are ideal cases for SIMD operations, I asked the compiler (-mfpu=neon -mfloat-abi=softfp) to generate NEON instructions  for my code, but the compiler fails to do so and then I also attempted to write my own NEON intrinsics code for the Matrix operations, but I found it very hard to do so.

So, I thought of making use of Eigen library which promises vectorization of matrix operations. So I promptly downloaded the Eigen C++ library and tried using it as given in their tutorials but, unfortunately I get compilation errors when I run their example programs.

Anyone out there who has experience using Eigen, any examples will be really helpful? Kindly help me how to go about it.

Help!

Thanks

I have the Eigen folder at: /home/ubuntu/Documents/eigen I set this path in my Eclipse's  C++ project's additional directories. Then I run the following program (Example)-

```<code>#include <Eigen/Core>

// import most common Eigen types
USING_PART_OF_NAMESPACE_EIGEN

int main(int, char *[])
{
  Matrix3f m3;
  m3 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  Matrix4f m4 = Matrix4f::Identity();
  Vector4i v4(1, 2, 3, 4);

  std::cout << "m3\n" << m3 << "\nm4:\n"
    << m4 << "\nv4:\n" << v4 << std::endl;
}
</code>```

Errors I get -

Build of configuration Debug for project Test_Eigen ****

make all

Building file: ../main.cpp

Invoking: Sourcery G++ C++ Compiler

arm-none-linux-gnueabi-g++ -I/home/ubuntu/Documents/eigen -O0 -g3 -Wall -c -fmessage-length=0 -fcommon -MMD -MP -MF"main.d" -MT"main.d" -mcpu=cortex-a8 -marm -o"main.o"

"../main.cpp"

../main.cpp:6: error: expected constructor, destructor, or type conversion before 'int'
make: *** [main.o] Error 1

答:
I am using the Ubuntu 17.04, and this is work for me

First:

I download the egien3.3.3 at  eigen official site. Extracted in a directory called eigen, cd into it.

Second:

run the command bellow one by one or make them a xxx.sh file to run at a time.

```<code>#!/bin/bash
#eigen3 install
#from: http://eigen.tuxfamily.org/index.php?title=Main_Page
#download the package like eigen-eigen-67e894c6cd8f.tar.gz

mkdir build
cd build
cmake -DEIGEN_TEST_NO_OPENGL=1 ..
make
sudo make install
</code>```

Finally:

make a test

```<code>#include <eigen3/Eigen/Core>
#include <iostream>

// import most common Eigen types
//USING_PART_OF_NAMESPACE_EIGEN
using namespace Eigen;
using namespace std;
int main(int, char *[])
{
  Matrix3f m3;
  m3 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  Matrix4f m4 = Matrix4f::Identity();
  Vector4i v4(1, 2, 3, 4);

  cout << "m3\n" << m3 << "\nm4:\n"
    << m4 << "\nv4:\n" << v4 << endl;
}
</code>```

Note:

To find your installed results, please see /usr/local/include/eigen3/

If any thing change, please see mytinx

Body:
I have an image processing algorithm which makes of matrices, I have my own matrix operation codes (Multiplication, Inverse...) with me. But the processor I use is ARM Cortex-A8 processor, which has NEON co-processor for vectorization, as matrix operations are ideal cases for SIMD operations, I asked the compiler (-mfpu=neon -mfloat-abi=softfp) to generate NEON instructions  for my code, but the compiler fails to do so and then I also attempted to write my own NEON intrinsics code for the Matrix operations, but I found it very hard to do so.

So, I thought of making use of Eigen library which promises vectorization of matrix operations. So I promptly downloaded the Eigen C++ library and tried using it as given in their tutorials but, unfortunately I get compilation errors when I run their example programs.

Anyone out there who has experience using Eigen, any examples will be really helpful? Kindly help me how to go about it.

Help!

Thanks

I have the Eigen folder at: /home/ubuntu/Documents/eigen I set this path in my Eclipse's  C++ project's additional directories. Then I run the following program (Example)-

#include <Eigen/Core>

// import most common Eigen types
USING_PART_OF_NAMESPACE_EIGEN

int main(int, char *[])
{
  Matrix3f m3;
  m3 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  Matrix4f m4 = Matrix4f::Identity();
  Vector4i v4(1, 2, 3, 4);

  std::cout << "m3\n" << m3 << "\nm4:\n"
    << m4 << "\nv4:\n" << v4 << std::endl;
}

Errors I get -

Build of configuration Debug for project Test_Eigen ****

make all

Building file: ../main.cpp

Invoking: Sourcery G++ C++ Compiler

arm-none-linux-gnueabi-g++ -I/home/ubuntu/Documents/eigen -O0 -g3 -Wall -c -fmessage-length=0 -fcommon -MMD -MP -MF"main.d" -MT"main.d" -mcpu=cortex-a8 -marm -o"main.o"

"../main.cpp"

../main.cpp:6: error: expected constructor, destructor, or type conversion before 'int'
make: *** [main.o] Error 1

Body:
I am using the Ubuntu 17.04, and this is work for me

First:

I download the egien3.3.3 at  eigen official site. Extracted in a directory called eigen, cd into it.

Second:

run the command bellow one by one or make them a xxx.sh file to run at a time.

#!/bin/bash
#eigen3 install
#from: http://eigen.tuxfamily.org/index.php?title=Main_Page
#download the package like eigen-eigen-67e894c6cd8f.tar.gz

mkdir build
cd build
cmake -DEIGEN_TEST_NO_OPENGL=1 ..
make
sudo make install

Finally:

make a test

#include <eigen3/Eigen/Core>
#include <iostream>

// import most common Eigen types
//USING_PART_OF_NAMESPACE_EIGEN
using namespace Eigen;
using namespace std;
int main(int, char *[])
{
  Matrix3f m3;
  m3 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  Matrix4f m4 = Matrix4f::Identity();
  Vector4i v4(1, 2, 3, 4);

  cout << "m3\n" << m3 << "\nm4:\n"
    << m4 << "\nv4:\n" << v4 << endl;
}

Note:

To find your installed results, please see /usr/local/include/eigen3/

If any thing change, please see mytinx


问:
Algorithm to find subset within two sets of integers whose sums match
I'm looking for an algorithm which can take two sets of integers (both positive and negative) and find subsets within each that have the same sum.

The problem is similar to the subset sum problem except that I'm looking for subsets on both sides.

Here's an example:

List A {4, 5, 9, 10, 1}

List B {21, 7, -4, 180}

So the only match here is:
{10, 1, 4, 9} <=> {21, 7, -4}

Does anyone know if there are existing algorithms for this kinda problems?

So far, the only solution I have is a brute force approach which tries every combination but it performs in Exponential time and I've had to put a hard limit on the number of elements to consider to avoid it from taking too long.

The only other solution I can think of is to run a factorial on both lists and look for equalities there but that is still not very efficient and takes exponentially longer as the lists get bigger.

答:
Like the subset sum problem, this problem is weakly NP-complete, so it has a solution that runs in time polynomial(M), where M is the sum of all numbers appearing in the problem instance. You can achieve that with dynamic programming. For each set you can generate all possible sums by filling a 2-dimensional binary table, where "true" at (k,m) means that a subset sum m can be achieved by picking some elements from the first k elements of the set.

You fill it iteratively - you set (k,m) to "true" if (k-1,m) is set to "true" (obviously, if you can get m from k-1 elements, you can get it from k elements by not picking the k-th) or if (k-1,m-d) is set to "true" where d is the value of k-th element in the set (the case where you pick the k-th element).

Filling the table gets you all the possible sums in the last column (the one representing the whole set). Do this for both sets and find common sums. You can backtrack the actual subsets representing the solutions by reversing the process which you used to fill the tables.

OwnerDisplayName: theburningmonk

LastEditorDisplayName: Andrew Rollings

OwnerDisplayName: Rafał Dowgird


问:
factorial of a number
I have the following code but it is not giving perfect result for factorial can u find it out plz</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
</code>```

答: You need to have a return in your function in the first place. ;)

Title: factorial of a number

Body:
I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1">

  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>


问:
Where does the browser store global variables defined with let or const?
If global variables defined with const or let are not stored on window, where are they being stored?</p>

```<code>var varTest = 'var test';
const constTest = 'const test';
let letTest = 'let test';

varTest            //"var test"
letTest            //"let test"
constTest          //"const test"
window.varTest     //"var test"
window.constTest   //undefined
window.letTest     //undefined
</code>```

答:
A global environment record consists of two parts

an object environment record

and a declarative environment record

Environment records are conceptional data structures for storing the identifier name -> value mappings.

As you might suspect, object environment records are backed by actual user space objects, such as the global object or an arbitrary object when you use with. That's what makes global bindings become properties of the global object.

let, const and other declarations are store in the declarative environment record part which is backed by some implementation specific data structure. You have encountered declarative environments before because every function environment is a declarative environment. So one could also say "let and const are stored in the global scope the same way as any binding is stored in a function".

From the spec:

A global Environment Record is logically a single record but it is specified as a composite encapsulating an object Environment Record and a declarative Environment Record. The object Environment Record has as its base object the global object of the associated Realm. This global object is the value returned by the global Environment Record’s GetThisBinding concrete method. The object Environment Record component of a global Environment Record contains the bindings for all built-in globals (clause 18) and all bindings introduced by a FunctionDeclaration, GeneratorDeclaration, or VariableStatement contained in global code. The bindings for all other ECMAScript declarations in global code are contained in the declarative Environment Record component of the global Environment Record.

Body:
If global variables defined with const or let are not stored on window, where are they being stored?

var varTest = 'var test';
const constTest = 'const test';
let letTest = 'let test';

varTest            //"var test"
letTest            //"let test"
constTest          //"const test"
window.varTest     //"var test"
window.constTest   //undefined
window.letTest     //undefined


问:
aggregate / count rows grouped by geography (or geometry)
I have a table such as:

```<code>Create Table SalesTable
( StuffID int identity not null,
  County geography not null,
  SaleAmount decimal(12,8) not null,
  SaleTime datetime not null )
</code>```

It has a recording of every sale with amount, time, and a geography of the county that the sale happened in.

I want to run a query like this:

```<code>Select sum(SaleAmount), County from SalesTable group by County
</code>```

But if I try to do that, I get:

```<code>The type "geography" is not comparable. It cannot be used in the GROUP BY clause.
</code>```

But I'd like to know how many sales happened per county. Annoyingly, if I had the counties abbreviated (SDC,LAC,SIC, etc) then I could group them because it would simply be a varchar. But then I use the geography datatype for other reasons.

答:
I would propose a slightly different structure:

```<code>create table dbo.County (
  CountyID int identity not null
    constraint [PK_County] primary key clustered (CountyID),
  Name varchar(200) not null,
  Abbreviation varchar(10) not null,
  geo geography not null
);
Create Table SalesTable
(
  StuffID int identity not null,
  CountyID int not null
     constraint FK_Sales_County foreign key (CountyID)
     references dbo.County (CountyID),
  SaleAmount decimal(12,8) not null,
  SaleTime datetime not null
);
</code>```

From there, your aggregate looks something like:

```<code>Select c.Abbreviation, sum(SaleAmount)
from SalesTable as s
join dbo.County as c
   on s.CountyID = c.CountyID
group by c.Abbreviation;
</code>```

If you really need the geography column in the aggregate, you're a sub-query or a common table expression away:

```<code>with s as (
    Select c.CountyID, c.Abbreviation,
        sum(s.SaleAmount) as [TotalSalesAmount]
    from SalesTable as s
    join dbo.County as c
        on s.CountyID = c.CountyID
    group by c.Abbreviation
)
select s.Abbreviation, s.geo, s.TotalSalesAmount
from s
join dbo.County as c
    on s.CountyID = s.CountyID;
</code>```

Body:
I have a table such as:

Create Table SalesTable
( StuffID int identity not null,
  County geography not null,
  SaleAmount decimal(12,8) not null,
  SaleTime datetime not null )

It has a recording of every sale with amount, time, and a geography of the county that the sale happened in.

I want to run a query like this:

Select sum(SaleAmount), County from SalesTable group by County

But if I try to do that, I get:

The type "geography" is not comparable. It cannot be used in the GROUP BY clause.

But I'd like to know how many sales happened per county. Annoyingly, if I had the counties abbreviated (SDC,LAC,SIC, etc) then I could group them because it would simply be a varchar. But then I use the geography datatype for other reasons.

Body:
I would propose a slightly different structure:

create table dbo.County (
  CountyID int identity not null
    constraint [PK_County] primary key clustered (CountyID),
  Name varchar(200) not null,
  Abbreviation varchar(10) not null,
  geo geography not null
);
Create Table SalesTable
(
  StuffID int identity not null,
  CountyID int not null
     constraint FK_Sales_County foreign key (CountyID)
     references dbo.County (CountyID),
  SaleAmount decimal(12,8) not null,
  SaleTime datetime not null
);

From there, your aggregate looks something like:

Select c.Abbreviation, sum(SaleAmount)
from SalesTable as s
join dbo.County as c
   on s.CountyID = c.CountyID
group by c.Abbreviation;

If you really need the geography column in the aggregate, you're a sub-query or a common table expression away:

with s as (
    Select c.CountyID, c.Abbreviation,
        sum(s.SaleAmount) as [TotalSalesAmount]
    from SalesTable as s
    join dbo.County as c
        on s.CountyID = c.CountyID
    group by c.Abbreviation
)
select s.Abbreviation, s.geo, s.TotalSalesAmount
from s
join dbo.County as c
    on s.CountyID = s.CountyID;


问:
Get data from link in Ionic 3 Web App
Scenario:

I have an Ionic 3 Web app, which opens for this link http://localhost:8100. I need to pass a value with the link (i.e http://localhost:8100/index.html?cell=1234567890) and the ionic app while loading the app, fetches the cell value.

What i have done:

Seriously I have no idea, where to start. I used NavParams like this,

```<code>this.cell = this.navParams.get('cell');
</code>```

and opened the app like http://localhost:8100/index.html?cell=1234567890, the app is opened successfully, but i'm getting an undefined value.

Any advice would be appreciated.

答:
Finally found the answer from the official documentation, IonicPage Documentation.

so i have used

```<code>@IonicPage({
  segment: 'feedback/:cell'
})
</code>```

and in constructor,

```<code>this.cell = this.navParams.get('cell');
</code>```

now when i called this link http://localhost:8100/#/feedback/1234567890
and i get the number. everything is working fine now.

Thank you for your responses, i appreciate it.

Title: Get data from link in Ionic 3 Web App

Body:
Scenario:

I have an Ionic 3 Web app, which opens for this link http://localhost:8100. I need to pass a value with the link (i.e http://localhost:8100/index.html?cell=1234567890) and the ionic app while loading the app, fetches the cell value.

What i have done:

Seriously I have no idea, where to start. I used NavParams like this,

this.cell = this.navParams.get('cell');

and opened the app like http://localhost:8100/index.html?cell=1234567890, the app is opened successfully, but i'm getting an undefined value.

Any advice would be appreciated.

Body:
Finally found the answer from the official documentation, IonicPage Documentation.

so i have used

@IonicPage({
  segment: 'feedback/:cell'
})

and in constructor,

this.cell = this.navParams.get('cell');

now when i called this link http://localhost:8100/#/feedback/1234567890
and i get the number. everything is working fine now.

Thank you for your responses, i appreciate it.


问:
VBScript Replace for character string of unknown length
I am working in Excel to take a faulty URL and replace the incorrect characters.  The characters I want to replace are "%20" BUT there is no way to know how many of those characters will be in the string.  There might be just one "%20" or 5 "%20%20%20%20%20" or any other number of them in between but no matter how many "%20" characters there are I want to replace with only ONE forward slash "/".

I know I can use something like below, but don't want to end up with more than one forward slash if there are more than one "%20"

```<code>Sub fixURL()

Worksheets("Google Feed Original").Activate

 Worksheets("Google Feed Original").Columns("N").Replace _
        What:="%20", replacement:="/", LookAt:=xlPart

End Sub
</code>```

For example the starting URL might look like:

http://domainname.com/products/prodName%20%20%20ProdNumber

and no matter how many "%20" are in the middle, I am trying to get it to format like this instead:

http://domainname.com/products/prodName/ProdNumber

Is there some way I can replace all of them with just one "/" no matter how many "%20" are in the string?

Thanks.

答:
The following code will replace all the consecutive %20 with a single /. It does not make use of any regular expression. It first splits the string using the delimiter %20 and then if the length of each of the array element is greater than 0, it joins them with the delimiter /.

```<code>str = "http://domainname.com/products/prodName%20%20%20ProdNumber"
a=Split(str,"%20")
For i=0 To UBound(a)
    If Len(a(i))>0 Then
        requiredStr = requiredStr & a(i)&"/"
    End If
Next
requiredStr=Left(requiredStr,Len(requiredStr)-1)
MsgBox requiredStr
</code>```

Let me know if it works for you.

Output:

Body:
I am working in Excel to take a faulty URL and replace the incorrect characters.  The characters I want to replace are "%20" BUT there is no way to know how many of those characters will be in the string.  There might be just one "%20" or 5 "%20%20%20%20%20" or any other number of them in between but no matter how many "%20" characters there are I want to replace with only ONE forward slash "/".

I know I can use something like below, but don't want to end up with more than one forward slash if there are more than one "%20"

Sub fixURL()

Worksheets("Google Feed Original").Activate

 Worksheets("Google Feed Original").Columns("N").Replace _
        What:="%20", replacement:="/", LookAt:=xlPart

End Sub

For example the starting URL might look like:

http://domainname.com/products/prodName%20%20%20ProdNumber

and no matter how many "%20" are in the middle, I am trying to get it to format like this instead:

http://domainname.com/products/prodName/ProdNumber

Is there some way I can replace all of them with just one "/" no matter how many "%20" are in the string?

Thanks.

Body:
The following code will replace all the consecutive %20 with a single /. It does not make use of any regular expression. It first splits the string using the delimiter %20 and then if the length of each of the array element is greater than 0, it joins them with the delimiter /.

str = "http://domainname.com/products/prodName%20%20%20ProdNumber"
a=Split(str,"%20")
For i=0 To UBound(a)
    If Len(a(i))>0 Then
        requiredStr = requiredStr & a(i)&"/"
    End If
Next
requiredStr=Left(requiredStr,Len(requiredStr)-1)
MsgBox requiredStr

Let me know if it works for you.

Output:


问:
bytearray from a webcam
i try to get a bytearray from a webcam. i can get the image of the webcam, copy it to bitmapdata and get the bytearray. but is it possible to get the bytearray from the image and sound from the client's webcam ?</p>

答:
audio data to ByteArray:

 * Microphone.sampleData Event

 * SoundMixer.computeSpectrum() method

i know only the following way to get a ByteArray from Video instance:

 * to draw a BitmapData each time the screen is updated and then BitmapData.getPixels(new Rectangle(0, 0, BitmapData.width, BitmapData.height))

it's also possible to join ByteArrays with video and audio data but it depends on how it'll be treated on the server side

Title: bytearray from a webcam


问:
Why can't I check if an array is empty with array == []?
This is a question from CodeWars that is named "Count of positives/sum of negatives". It says:

If the input array is empty or null, return an empty array

To check if the array is empty, I decided to check if it was an empty array. When I try to do:

```<code>if(input == [])
</code>```

I fail the test, but if I do:

```<code>if(input.length == 0)
</code>```

I pass the test. An empty array should be equal to [] right? Why is there a difference, and what is the difference between these two checks?

My code is as follows:

```<code>function countPositivesSumNegatives(input) {
   var a = 0;
   var b = 0;
   if (input == null) {
      return []
   }
   if (input.length == 0) {
      return []
   }
   for (var i = 0; i < input.length; i++) {
      if (input[i] > 0) {
         a++;
      }
      if (input[i] < 0) {
         b += input[i];
      }
   }
   return [a, b]
}
</code>```

答:
The problem is that arrays are objects. When you compare two objects, you compare their references. Per the MDN documentation:

Equality (==)

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Since two instances of arrays don't necessarily have the same reference, the check fails. Just try this in the console:

```<code>> [] == []
false
</code>```

Two arrays seemingly with the same content (or lack thereof) are not equal. That's because content is not checked, but reference. These two arrays are separate instances and refer to different places in memory, thus the check evaluates to false.

On the other hand, just checking the length, and if it is zero checks if the array is empty or not. The length property signifies the amount of content in an array1 and is part of every array. Since it is part of every array and reflects the amount of data in the array, you can use it to check if the array is empty or not.

1 Beware, though, of sparse arrays as mentioned by RobG in the comments. Such arrays can be created with new Array(N) which will give you an empty array, but with length N.

Body:
This is a question from CodeWars that is named "Count of positives/sum of negatives". It says:

If the input array is empty or null, return an empty array

To check if the array is empty, I decided to check if it was an empty array. When I try to do:

if(input == [])

I fail the test, but if I do:

if(input.length == 0)

I pass the test. An empty array should be equal to [] right? Why is there a difference, and what is the difference between these two checks?

My code is as follows:

function countPositivesSumNegatives(input) {
   var a = 0;
   var b = 0;
   if (input == null) {
      return []
   }
   if (input.length == 0) {
      return []
   }
   for (var i = 0; i < input.length; i++) {
      if (input[i] > 0) {
         a++;
      }
      if (input[i] < 0) {
         b += input[i];
      }
   }
   return [a, b]
}

Body:
The problem is that arrays are objects. When you compare two objects, you compare their references. Per the MDN documentation:

Equality (==)

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Since two instances of arrays don't necessarily have the same reference, the check fails. Just try this in the console:

> [] == []
false

Two arrays seemingly with the same content (or lack thereof) are not equal. That's because content is not checked, but reference. These two arrays are separate instances and refer to different places in memory, thus the check evaluates to false.

On the other hand, just checking the length, and if it is zero checks if the array is empty or not. The length property signifies the amount of content in an array1 and is part of every array. Since it is part of every array and reflects the amount of data in the array, you can use it to check if the array is empty or not.

1 Beware, though, of sparse arrays as mentioned by RobG in the comments. Such arrays can be created with new Array(N) which will give you an empty array, but with length N.


问:
Multiple Row to single row query result
```<code>SELECT DISTINCT
    'XXXXXXXXXXX',
    APP_ID,
    COND_ID,
    GMTDATE,
FROM TABLE_NAME
WHERE COND_ID = 'XXXXXXXXXXXXXXXXX';
</code>```

Above query has more then 100,000 data. I want a single row result where has It is giving multiple row because it take more than a second to process the data.

AS result is: (Two row )

```<code>XXXXXXXXXXX    APP_ID      COND_ID         GMTDATE
XXXXXXXXXXX    11091000000  20170601010765  06-JUN-17
XXXXXXXXXXX    11091000000  20170601010765  06-JUN-17
</code>```

Desired result is: (One row)

```<code>XXXXXXXXXXX    APP_ID      COND_ID         GMTDATE
XXXXXXXXXXX    11091000000  20170601010765  06-JUN-17
</code>```

答:
```<code>SELECT DISTINCT
'XXXXXXXXXXX',
APP_ID,
COND_ID,
GMTDATE,
FROM TABLE_NAME
WHERE COND_ID = 'XXXXXXXXXXXXXXXXX'
GROUP BY 1,2,3,4 ;    --I have assumed 'XXXXXXXXXXX' is a column name
</code>```

Title: Multiple Row to single row query result

Body:
SELECT DISTINCT
    'XXXXXXXXXXX',
    APP_ID,
    COND_ID,
    GMTDATE,
FROM TABLE_NAME
WHERE COND_ID = 'XXXXXXXXXXXXXXXXX';

Above query has more then 100,000 data. I want a single row result where has It is giving multiple row because it take more than a second to process the data.

AS result is: (Two row )

XXXXXXXXXXX    APP_ID      COND_ID         GMTDATE
XXXXXXXXXXX    11091000000  20170601010765  06-JUN-17
XXXXXXXXXXX    11091000000  20170601010765  06-JUN-17

Desired result is: (One row)

XXXXXXXXXXX    APP_ID      COND_ID         GMTDATE
XXXXXXXXXXX    11091000000  20170601010765  06-JUN-17


问:
Upgrading Django Version: Best Practice
I've pretty big code base written on Django 1.5, it's about time to upgrade to the newest version (1.11.2) as many stuff don't work well.

I'm wondering if it's best to upgrade step by step: 1.5->1.6->1.7...
or just jump to 1.11.2

what method should be better and make the (hard) process easier? as my project has many dependencies?

Also what are good practices to do? I'm using virtualenv and aware of this Django article about upgrading

答:
The document you found (“Upgrading Django to a newer version”) has a good guide.

An important part, before upgrading, is to have full branch coverage by the automated test suite for your application, before upgrading.

You want to be able to run a full automated test suite, see everything pass and know that all branches are exercised by the test suite.

This means that when you break something by porting to the new Django version, you'll be able to see which parts of your app are not behaving correctly any more.

Read about what changes you need to make by reading the release notes and deprecation timeline, for all of the relevant releases between your current and target Django versions.

See what dependencies you'll need to upgrade for Django; you might need to correct your code if it relies on incompatible features in an outdated third-party library.

All of those should be done before upgrading a single thing, in my opinion.

Title: Upgrading Django Version: Best Practice