问:
Conversion between Cartesian vs. Polar Coordinates. Hoping the result is positive
I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.

For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I wish the angle is 189.92624551. (I hope all of the angles after conversion are between 0~360 degree)

How I fix this?

Thanks!!!

```<code>import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
    return np.angle(complex_format, deg=deg).squeeze()

print(cart_to_pol(points))
</code>```

答:
If you need to convert [-180; 180] angle to [0; 360] you can use this code:</p>

```<code>def convert_angle(angle):
    return (angle + 360) % 360
</code>```

Body:
I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.

For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I wish the angle is 189.92624551. (I hope all of the angles after conversion are between 0~360 degree)

How I fix this?

Thanks!!!

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
    return np.angle(complex_format, deg=deg).squeeze()

print(cart_to_pol(points))

Body:
If you need to convert [-180; 180] angle to [0; 360] you can use this code:

def convert_angle(angle):
    return (angle + 360) % 360


来源: stackexchange

问:
Can someone explain what is happening with this piece of micro python
Just started playing with a BBC micro:bit. One of the examples has this line of code

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

It generates set of images. In trying to figure out what is going on I wrote this piece of code

```<code>class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )
</code>```

which produces

```<code>python3 test.py
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
</code>```

Thanks

答:
In invert() You need to pass some int values and return any int value. In your code you are not returning any int or float value in your invert() function. Try this

```<code>class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            return a
flash = [Image().invert(1,)*(i/9) for i in range(9, -1, -1)]
print (flash)
</code>```

This will work

ContentLicense: CC BY-SA 4.0

Body:
Just started playing with a BBC micro:bit. One of the examples has this line of code

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

It generates set of images. In trying to figure out what is going on I wrote this piece of code

class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )

which produces

python3 test.py
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

Thanks

Body:
In invert() You need to pass some int values and return any int value. In your code you are not returning any int or float value in your invert() function. Try this

class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            return a
flash = [Image().invert(1,)*(i/9) for i in range(9, -1, -1)]
print (flash)

This will work


问:
React native app giving blank screen when rendering two RNCamera components
I am trying to use two RNCamera components in a screen, so that each component takes half of the screen and I can show back and front camera at the same time.

But unfortunately, the app is giving just a blank screen as soon as I add the second RNCamera component. Can someone help me with this.

Below is my code.

```<code><View style={styles.container}>
        <View style={{ flex: 1 }}>
          <RNCamera
            ref={ref => {
              this.camera1 = ref;
            }}
            style={styles.preview}
            type={RNCamera.Constants.Type.back}
            flashMode={RNCamera.Constants.FlashMode.off}
            androidCameraPermissionOptions={{
              title: 'Permission to use camera',
              message: 'We need your permission to use your camera',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            androidRecordAudioPermissionOptions={{
              title: 'Permission to use audio recording',
              message: 'We need your permission to use your audio',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            onGoogleVisionBarcodesDetected={({ barcodes }) => {
              console.log(barcodes);
            }}
          />
        </View>
        <View style={{ flex: 1 }}>
          <RNCamera
            ref={ref => {
              this.camera2 = ref;
            }}
            style={styles.preview}
            type={RNCamera.Constants.Type.back}
            flashMode={RNCamera.Constants.FlashMode.off}
            androidCameraPermissionOptions={{
              title: 'Permission to use camera',
              message: 'We need your permission to use your camera',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            androidRecordAudioPermissionOptions={{
              title: 'Permission to use audio recording',
              message: 'We need your permission to use your audio',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            onGoogleVisionBarcodesDetected={({ barcodes }) => {
              console.log(barcodes);
            }}
          />
        </View>
        <View style={{ flex: 1, flexDirection: 'row', backgroundColor: 'yellow', justifyContent: 'center' }}>
          <TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.capture}>
            <Text style={{ fontSize: 14 }}> SNAP </Text>
          </TouchableOpacity>
        </View>
</code>```

答:
I had the same issue using two camera instances in a single view. As it turns out the implementation of react-native-camera doesn't support it. So the only option I found was to use this fork from github

Here is an issue with a good explanation of this case.

Body:
I am trying to use two RNCamera components in a screen, so that each component takes half of the screen and I can show back and front camera at the same time.

But unfortunately, the app is giving just a blank screen as soon as I add the second RNCamera component. Can someone help me with this.

Below is my code.

<View style={styles.container}>
        <View style={{ flex: 1 }}>
          <RNCamera
            ref={ref => {
              this.camera1 = ref;
            }}
            style={styles.preview}
            type={RNCamera.Constants.Type.back}
            flashMode={RNCamera.Constants.FlashMode.off}
            androidCameraPermissionOptions={{
              title: 'Permission to use camera',
              message: 'We need your permission to use your camera',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            androidRecordAudioPermissionOptions={{
              title: 'Permission to use audio recording',
              message: 'We need your permission to use your audio',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            onGoogleVisionBarcodesDetected={({ barcodes }) => {
              console.log(barcodes);
            }}
          />
        </View>
        <View style={{ flex: 1 }}>
          <RNCamera
            ref={ref => {
              this.camera2 = ref;
            }}
            style={styles.preview}
            type={RNCamera.Constants.Type.back}
            flashMode={RNCamera.Constants.FlashMode.off}
            androidCameraPermissionOptions={{
              title: 'Permission to use camera',
              message: 'We need your permission to use your camera',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            androidRecordAudioPermissionOptions={{
              title: 'Permission to use audio recording',
              message: 'We need your permission to use your audio',
              buttonPositive: 'Ok',
              buttonNegative: 'Cancel',
            }}
            onGoogleVisionBarcodesDetected={({ barcodes }) => {
              console.log(barcodes);
            }}
          />
        </View>
        <View style={{ flex: 1, flexDirection: 'row', backgroundColor: 'yellow', justifyContent: 'center' }}>
          <TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.capture}>
            <Text style={{ fontSize: 14 }}> SNAP </Text>
          </TouchableOpacity>
        </View>


问:
Property X does not exist on type X while mocking a function
```<code>import { IListItem } from './IListItem';

export default class SPHttpClient  {

    private static _items: IListItem[] = [{ Title: 'Mock List', PercentComplete: 11, Id: 1 },
                                        { Title: 'Mock List 2', PercentComplete: 61, Id: 2 },
                                        { Title: 'Mock List 3', PercentComplete: 36, Id: 3 }];

    public static readonly configurations: mockConfig = {v1: 'value'};

    public static get(restUrl: string, options?: any): Promise<IListItem[]> {
    return new Promise<IListItem[]>((resolve) => {
            resolve(SPHttpClient._items);
        });
    }
}

export class mockConfig {
    public static readonly v1: any = '1';
}
</code>```

I need to mock SPHttpClient and for some reason I am getting: Property 'v1' does not exist on type 'mockConfig'.

Is there anything I am doing wrong? I thought assigning mockConfig the value of an object with the property v1 would have solved the issue, but I am still getting the same error.

```<code>private async getToDosAsync():Promise<any> {
    let items=[];
    await this.props.spHttpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('ToDo')/items`,
    SPHttpClient.configurations.v1).then(async(response)=>{
      if(response.ok)
      {
        await response.json().then((data)=>{
          items = data.value;
        });
      }
    });

    this.setState({items:items});
    return items;
}
</code>```

This is where I am calling it.

答:
```<code>public static readonly v1: any = '1';
</code>```

The problem is that you've defined v1 to be a static property. In other words, it's a property of a class, not a property of an instance of the class. Then you define SPHttpClient as having an instance of that class. You did sneak a v1 onto that instance, but as this is not part of the type, you get an error when you try to access it.

Instead, make the property non static, either like this:

```<code>export class mockConfig {
    public readonly v1: any = '1';
}
</code>```

or like this

```<code>export interface mockConfig {
  v1: any,
}
</code>```

P.S. This isn't directly related to your question, but i have to comment on your getToDosAsync function. You're getting no benefit out of your use of async/await. You keep calling .then to create a promise, then awaiting the promise you just created, then not using the value that would have been returned from await. Your exact same code, adjusted to use async/await as intended, looks like this:

```<code>private async getToDosAsync():Promise<any> {
  let items = [];
  const response = await this.props.spHttpClient.get(
    `${this.props.siteUrl}/_api/web/lists/getbytitle('ToDo')/items`,
    SPHttpClient.configurations.v1
  );
  if (response.ok) {
    const data = await response.json();
    items = data.value;
  }

  this.setState({items:items});
  return items;
}
</code>```

Body:
import { IListItem } from './IListItem';

export default class SPHttpClient  {

    private static _items: IListItem[] = [{ Title: 'Mock List', PercentComplete: 11, Id: 1 },
                                        { Title: 'Mock List 2', PercentComplete: 61, Id: 2 },
                                        { Title: 'Mock List 3', PercentComplete: 36, Id: 3 }];

    public static readonly configurations: mockConfig = {v1: 'value'};

    public static get(restUrl: string, options?: any): Promise<IListItem[]> {
    return new Promise<IListItem[]>((resolve) => {
            resolve(SPHttpClient._items);
        });
    }
}

export class mockConfig {
    public static readonly v1: any = '1';
}

I need to mock SPHttpClient and for some reason I am getting: Property 'v1' does not exist on type 'mockConfig'.

Is there anything I am doing wrong? I thought assigning mockConfig the value of an object with the property v1 would have solved the issue, but I am still getting the same error.

private async getToDosAsync():Promise<any> {
    let items=[];
    await this.props.spHttpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('ToDo')/items`,
    SPHttpClient.configurations.v1).then(async(response)=>{
      if(response.ok)
      {
        await response.json().then((data)=>{
          items = data.value;
        });
      }
    });

    this.setState({items:items});
    return items;
}

This is where I am calling it.

Body:
public static readonly v1: any = '1';

The problem is that you've defined v1 to be a static property. In other words, it's a property of a class, not a property of an instance of the class. Then you define SPHttpClient as having an instance of that class. You did sneak a v1 onto that instance, but as this is not part of the type, you get an error when you try to access it.

Instead, make the property non static, either like this:

export class mockConfig {
    public readonly v1: any = '1';
}

or like this

export interface mockConfig {
  v1: any,
}

P.S. This isn't directly related to your question, but i have to comment on your getToDosAsync function. You're getting no benefit out of your use of async/await. You keep calling .then to create a promise, then awaiting the promise you just created, then not using the value that would have been returned from await. Your exact same code, adjusted to use async/await as intended, looks like this:

private async getToDosAsync():Promise<any> {
  let items = [];
  const response = await this.props.spHttpClient.get(
    `${this.props.siteUrl}/_api/web/lists/getbytitle('ToDo')/items`,
    SPHttpClient.configurations.v1
  );
  if (response.ok) {
    const data = await response.json();
    items = data.value;
  }

  this.setState({items:items});
  return items;
}


问:
Refresh page with Jquery Connected Sortable if item is dropped into certain container
My connected sortables work great but I'm trying to make one improvement:

If a user drags in item into the "#buttonmaker" sortable, I want the entire page to refresh.

What's happening is if a user drags an item into the buttonmaker sortable, my ajax sorting.php page updates the database with a new menu button based off the item the user dropped in. After that, the page needs to be refreshed so the user can see the new menu button that they just created.

95% of the time though users will not be using the #buttonmaker and I don't need a page refresh... ajax does it's thing. It's just for this one #buttonmaker container that I need a page refresh. Thanks for any help.

```<code>$(function() {
    $("#draft, #trash, #a_bunch_more_divs, #buttonmaker").sortable({
        connectWith: '.connectedSortable',
        placeholder: 'ui-state-highlight',
        opacity: 0.6,
        scroll: true,
        update : function ()
        {
            $.ajax(
            {
                type: "POST",
                url: "sorting.php",
                data:
                {
                    draft_sort:$("#draft").sortable('serialize'),
                    trash_sort:$("#trash").sortable('serialize'),
                    other_sort:$("#a_bunch_more_divs").sortable('serialize'),
                    buttonmaker_sort:$("#buttonmaker").sortable('serialize')
                }
            });
        }
    }).disableSelection();
});
</code>```

Updated Code (I've changed a few cosmetic things since the original post):

```<code>$(function() {
    var refreshNeeded = false;
    $("#draft, #published, #trash").sortable({
        connectWith: '.connectedSortable',
        placeholder: 'ui-state-highlight',
        opacity: 0.6,
        scroll: true,
        update : function (event, ui)
        {
            var $sortable = $(this);
            if(ui.item.parent()[0] != this) return;
            var postData = {};
            postData[$sortable.attr('id') + '_sort'] = $sortable.sortable('serialize');
            if(ui.sender){
                postData[$sortable.attr('id') + '_sort'] = ui.sender.sortable('serialize');
            }
            $.ajax(
            {
                type: "POST",
                url: "js/post_sorting.php",
                data: postData,
                success: function() {
                    if(($sortable.attr('id') == "published")) refreshNeeded = true;
                    /*window.location.reload(true);*/
                }
            });
        }
    }).disableSelection();
    $(document).ajaxStop(function(){
        if(refreshNeeded){
            window.location.reload();
        }
    });
});
</code>```

答:
It is always a good idea to check for the outcome of your ajax call. Also, sending the whole thing on every update is a waste of resources, as the update event gets called for both the source and the target sortable.

As for the refresh, you just need to set a boolean variable whenever you think a refresh is needed, then bind an event to .ajaxStop() to run when all ajax requests have completed.

```<code>$(function(){
    var refreshNeeded = false;

    $("#draft, #trash, #a_bunch_more_divs, #buttonmaker").sortable({
        connectWith: '.connectedSortable',
        placeholder: 'ui-state-highlight',
        opacity: 0.6,
        scroll: true,
        update : function(event, ui){
            var $sortable = $(this);

            // To avoid double-firing the event, return if it's not the sortable
            // where the item was dropped into.
            if(ui.item.parent()[0] != this) return;

            // Create object from the current sortable to post
            var postData = {};
            postData[$sortable.attr('id') + '_sort'] = $sortable.sortable('serialize');

            // If the item came from a connected sortable, include that in the post too
            if(ui.sender){
                postData[ui.sender.attr('id') + '_sort'] = ui.sender.sortable('serialize');
            }

            $.ajax(
            {
                type: "POST",
                url: "sorting.php",
                data: postData,
                success: function(){
                    // What if we're all happy?

                    // If the triggering sortable was the buttonmaker, set the refresh flag
                    if($sortable.attr('id') == "buttonmaker")) RefreshNeeded = true;
                },
                error: function(){
                    // What if there is an error?
                }
            });
        }
    }).disableSelection();

    $(document).ajaxStop(function(){
        // All requests have completed, check if we need to refresh
        if(refreshNeeded){
            // Refresh the page (just a simple reload for now)
            window.location.reload();
        }
    });
});
</code>```

Edit: Added bit of code to only send current sortable in the post data. It assumes that the name of the data will always be id_sort, where id is the id of your sortable.

Edit 2: Added some more bits to avoid double-firing the event, so it will only submit once per move. If item came from a connected sortable, it will include both sortables in the request.

ContentLicense: CC BY-SA 3.0

Body:
My connected sortables work great but I'm trying to make one improvement:

If a user drags in item into the "#buttonmaker" sortable, I want the entire page to refresh.

What's happening is if a user drags an item into the buttonmaker sortable, my ajax sorting.php page updates the database with a new menu button based off the item the user dropped in. After that, the page needs to be refreshed so the user can see the new menu button that they just created.

95% of the time though users will not be using the #buttonmaker and I don't need a page refresh... ajax does it's thing. It's just for this one #buttonmaker container that I need a page refresh. Thanks for any help.

$(function() {
    $("#draft, #trash, #a_bunch_more_divs, #buttonmaker").sortable({
        connectWith: '.connectedSortable',
        placeholder: 'ui-state-highlight',
        opacity: 0.6,
        scroll: true,
        update : function ()
        {
            $.ajax(
            {
                type: "POST",
                url: "sorting.php",
                data:
                {
                    draft_sort:$("#draft").sortable('serialize'),
                    trash_sort:$("#trash").sortable('serialize'),
                    other_sort:$("#a_bunch_more_divs").sortable('serialize'),
                    buttonmaker_sort:$("#buttonmaker").sortable('serialize')
                }
            });
        }
    }).disableSelection();
});

Updated Code (I've changed a few cosmetic things since the original post):

$(function() {
    var refreshNeeded = false;
    $("#draft, #published, #trash").sortable({
        connectWith: '.connectedSortable',
        placeholder: 'ui-state-highlight',
        opacity: 0.6,
        scroll: true,
        update : function (event, ui)
        {
            var $sortable = $(this);
            if(ui.item.parent()[0] != this) return;
            var postData = {};
            postData[$sortable.attr('id') + '_sort'] = $sortable.sortable('serialize');
            if(ui.sender){
                postData[$sortable.attr('id') + '_sort'] = ui.sender.sortable('serialize');
            }
            $.ajax(
            {
                type: "POST",
                url: "js/post_sorting.php",
                data: postData,
                success: function() {
                    if(($sortable.attr('id') == "published")) refreshNeeded = true;
                    /*window.location.reload(true);*/
                }
            });
        }
    }).disableSelection();
    $(document).ajaxStop(function(){
        if(refreshNeeded){
            window.location.reload();
        }
    });
});

Body:
It is always a good idea to check for the outcome of your ajax call. Also, sending the whole thing on every update is a waste of resources, as the update event gets called for both the source and the target sortable.

As for the refresh, you just need to set a boolean variable whenever you think a refresh is needed, then bind an event to .ajaxStop() to run when all ajax requests have completed.

$(function(){
    var refreshNeeded = false;

    $("#draft, #trash, #a_bunch_more_divs, #buttonmaker").sortable({
        connectWith: '.connectedSortable',
        placeholder: 'ui-state-highlight',
        opacity: 0.6,
        scroll: true,
        update : function(event, ui){
            var $sortable = $(this);

            // To avoid double-firing the event, return if it's not the sortable
            // where the item was dropped into.
            if(ui.item.parent()[0] != this) return;

            // Create object from the current sortable to post
            var postData = {};
            postData[$sortable.attr('id') + '_sort'] = $sortable.sortable('serialize');

            // If the item came from a connected sortable, include that in the post too
            if(ui.sender){
                postData[ui.sender.attr('id') + '_sort'] = ui.sender.sortable('serialize');
            }

            $.ajax(
            {
                type: "POST",
                url: "sorting.php",
                data: postData,
                success: function(){
                    // What if we're all happy?

                    // If the triggering sortable was the buttonmaker, set the refresh flag
                    if($sortable.attr('id') == "buttonmaker")) RefreshNeeded = true;
                },
                error: function(){
                    // What if there is an error?
                }
            });
        }
    }).disableSelection();

    $(document).ajaxStop(function(){
        // All requests have completed, check if we need to refresh
        if(refreshNeeded){
            // Refresh the page (just a simple reload for now)
            window.location.reload();
        }
    });
});

Edit: Added bit of code to only send current sortable in the post data. It assumes that the name of the data will always be id_sort, where id is the id of your sortable.

Edit 2: Added some more bits to avoid double-firing the event, so it will only submit once per move. If item came from a connected sortable, it will include both sortables in the request.


问:
MongoDB text search using c# Driver 2.4.4
I am using MongoDB in c#. To search a 'question' in the 'knowledge' collection, this is my code.

```<code> var collection = _database.GetCollection<BsonDocument>("knowledge");
 var filter = Builders<BsonDocument>.Filter.Eq("question", question);
 var results = await collection.Find(filter).ToListAsync();
</code>```

Instead of this I want to search a 'question' that contains the given words. I want to search a pattern simply like following in MongoDB.

```<code> db.stores.find( { $text: { $search: "java \"coffee shop\"" } } )
</code>```

I found this in the Stack.

```<code>  collection.Indexes.CreateOne(Builders<searchFileByAuthor>.IndexKeys.Text(x=>x.subject));
 collection.Find(Builders<searchFileByAuthor>.Filter.Text("coffe")).ToList();
</code>```

Full text search in mongodb in .net

I am not familiar with using MongoDB in c# though. How should I modify my code to create a text index and search a pattern? How to do this in MongoDB .NET Driver version 2.4.4?

答:
you can using full-text search

```<code>Collection.Indexes.CreateOne(new CreateIndexModel<T>(Builders<T>.IndexKeys.Text("$**")));
</code>```

//build filter and query

```<code>var key = txtSearchKey.Text.ToLower().Trim();
var filter = Builders<EntityObject>.Filter.Text(key);
</code>```

Body:
I am using MongoDB in c#. To search a 'question' in the 'knowledge' collection, this is my code.

 var collection = _database.GetCollection<BsonDocument>("knowledge");
 var filter = Builders<BsonDocument>.Filter.Eq("question", question);
 var results = await collection.Find(filter).ToListAsync();

Instead of this I want to search a 'question' that contains the given words. I want to search a pattern simply like following in MongoDB.

 db.stores.find( { $text: { $search: "java \"coffee shop\"" } } )

I found this in the Stack.

  collection.Indexes.CreateOne(Builders<searchFileByAuthor>.IndexKeys.Text(x=>x.subject));
 collection.Find(Builders<searchFileByAuthor>.Filter.Text("coffe")).ToList();

Full text search in mongodb in .net

I am not familiar with using MongoDB in c# though. How should I modify my code to create a text index and search a pattern? How to do this in MongoDB .NET Driver version 2.4.4?

Body:
you can using full-text search

Collection.Indexes.CreateOne(new CreateIndexModel<T>(Builders<T>.IndexKeys.Text("$**")));

//build filter and query

var key = txtSearchKey.Text.ToLower().Trim();
var filter = Builders<EntityObject>.Filter.Text(key);


问:
AngularJS get value from API only if not already set
I have service to get some data from API and serve them to application.
Simple function like this:

```<code>getEnvironmentStatus() {
    var _this = this;
    var req = {
        method: "GET",
        url: "/api/system/hosting",
        headers: {},
        data: {}
    }
    return _this.$http(req);
}
</code>```

In some other place I have:

```<code>determineHostingEnv() {
    var _this = this;
    this.$env.getEnvironmentStatus()
    .then(function(response){
        _this.EnvHositng = response.data.cloud_hosted;
     }, function(error) {
    });
}
</code>```

If I need the same information in other place (other controller), I would need to call api again.

How can I make getEnvironmentStatus() function to call API only once and store data in local variable, so it can serve that variable next time it is asked for it, instead of calling API?
Also, what if that value will get requested a few times before the first API will return value? Can I prevent calling that API a few times?

答:
One can cache the promise:

```<code>httpPromiseCache = null;

getEnvironmentStatus() {
    var _this = this;
    var req = {
        method: "GET",
        url: "/api/system/hosting",
        headers: {},
        data: {}
    }
    if (!_this.httpPromiseCache) _this.httpPromiseCache = _this.$http(req);
    return _this.httpPromiseCache;
}
</code>```

The service will only execute the HTTP request once.

Body:
I have service to get some data from API and serve them to application.
Simple function like this:

getEnvironmentStatus() {
    var _this = this;
    var req = {
        method: "GET",
        url: "/api/system/hosting",
        headers: {},
        data: {}
    }
    return _this.$http(req);
}

In some other place I have:

determineHostingEnv() {
    var _this = this;
    this.$env.getEnvironmentStatus()
    .then(function(response){
        _this.EnvHositng = response.data.cloud_hosted;
     }, function(error) {
    });
}

If I need the same information in other place (other controller), I would need to call api again.

How can I make getEnvironmentStatus() function to call API only once and store data in local variable, so it can serve that variable next time it is asked for it, instead of calling API?
Also, what if that value will get requested a few times before the first API will return value? Can I prevent calling that API a few times?

Body:
One can cache the promise:

httpPromiseCache = null;

getEnvironmentStatus() {
    var _this = this;
    var req = {
        method: "GET",
        url: "/api/system/hosting",
        headers: {},
        data: {}
    }
    if (!_this.httpPromiseCache) _this.httpPromiseCache = _this.$http(req);
    return _this.httpPromiseCache;
}

The service will only execute the HTTP request once.


问:
How to write a dynamic django orm queryset based on the filters passed?
i need to apply filters dynamically on a queryset depending on the filters passed as a json from the front end.

for ex.

if json passed is : { id:[1,2,3] }
then queryset will be : Model.objects.filter(id__in=id)

if json is passed as: { id:[1,2,3],country:['india','australia'] }

then queryset will be : Model.objects.filter(id__in=id,country__in=country)

how to achieve this dynamically?

答:
Just use a django_filters

```<code>from django_filters import rest_framework as filters

class ContentFilter(filters.FilterSet):
    id = filters.NumberFilter(lookup_expr="in")
    country = filters.CharFilter(lookup_expr="in")

    class Meta:
        model = <your_model>
        fields = ['id', 'country']
</code>```

Then add to your view class

```<code>filterset_class = ContentFilter
</code>```

Body:
Just use a django_filters

from django_filters import rest_framework as filters

class ContentFilter(filters.FilterSet):
    id = filters.NumberFilter(lookup_expr="in")
    country = filters.CharFilter(lookup_expr="in")

    class Meta:
        model = <your_model>
        fields = ['id', 'country']

Then add to your view class

filterset_class = ContentFilter


问:
Issue with a skiping of first row
I understand that it skips the first row in the file because of header, but how can I avoid it? The syntax must be exactly the same as it is below.

File contains: Rabbit, Pig, Dog, Horse, Bird

```<code>try:
    file = open("file.txt")
    line = file.readline()

    animals = []
    for line in file:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    file.close()
</code>```

Output is ['Bird', 'Dog', 'Horse', 'Pig']

答:
you are reading the first line and  you are not doing something, you can include the first line in your output list: animals = [line.rstrip()]

or you can use the context manager:

```<code>with open('file.txt') as fp:
    animals = sorted(l.rstrip() for l in fp)
</code>```

Title: Issue with a skiping of first row

Body:
I understand that it skips the first row in the file because of header, but how can I avoid it? The syntax must be exactly the same as it is below.

File contains: Rabbit, Pig, Dog, Horse, Bird

try:
    file = open("file.txt")
    line = file.readline()

    animals = []
    for line in file:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    file.close()

Output is ['Bird', 'Dog', 'Horse', 'Pig']

Body:
you are reading the first line and  you are not doing something, you can include the first line in your output list: animals = [line.rstrip()]

or you can use the context manager:

with open('file.txt') as fp:
    animals = sorted(l.rstrip() for l in fp)


问:
Store two values from Dropdown Option Laravel 5.7
I am using dropdown and it's option value is $account->code but it shows code and name

so i want to store code in its column and name in another column

here is my blade code :

```<code><div class="form-group col-md-4">
    <label>@lang('site.from_account_number')</label>
    <select class="form-control select2" style="width: 100%;" name="from_account_number" id="from_account_number">
        @foreach ($accounts as $account)
            <option value="{{ $account->code }}">
                {{ $account->code }} - {{ $account->name }}
            </option>
        @endforeach
    </select>
</div>
</code>```

and here is my controller code :

```<code>$depositaction->from_account_number = $request->get('from_account_number');
$record_from_acc_name = Account::find($request->get('from_account_number'));
$depositaction->from_account_name = $record_from_acc_name->name;
</code>```

but i get error said :

```<code>ErrorException (E_NOTICE) Trying to get property 'name' of non-object
</code>```

答:
You should query in code. Please check the below code. </p>

```<code>$record_from_acc_name = Account::where('code', $request->get('from_account_number'))->first();
</code>```

Body:
I am using dropdown and it's option value is $account->code but it shows code and name

so i want to store code in its column and name in another column

here is my blade code :

    @lang('site.from_account_number')
    <select class="form-control select2" style="width: 100%;" name="from_account_number" id="from_account_number">
        @foreach ($accounts as $account)
            <option value="{{ $account->code }}">
                {{ $account->code }} - {{ $account->name }}
            </option>
        @endforeach
    </select>

and here is my controller code :

$depositaction->from_account_number = $request->get('from_account_number');
$record_from_acc_name = Account::find($request->get('from_account_number'));
$depositaction->from_account_name = $record_from_acc_name->name;

but i get error said :

ErrorException (E_NOTICE) Trying to get property 'name' of non-object

Body:
You should query in code. Please check the below code.

$record_from_acc_name = Account::where('code', $request->get('from_account_number'))->first();


问:
TypeError: undefined is not an object (evaluating 'event.target.value')
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

```<code>export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}
</code>```

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

答:
You can use this method :</p>

```<code>this.state = {
  email: '13119165220',
}
onChangeText={text => this.setState({ email: text })}
</code>```

Body:
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

Body:
You can use this method :

this.state = {
  email: '13119165220',
}
onChangeText={text => this.setState({ email: text })}


问:
Wrap log4j or create custom logger?
I have an application that needs to log two different types of messages: application log messages and audit messages. Application log messages match the standard lo4j Logger perfectly, but there are several required parameters for the audit log.

I think I need to wrap log4j to add the additional required parameters to the debug(), info(), etc methods, but I hate the idea of wrapping log4j. Should I:

Wrap log4j completely and provide my own Logger class that calls a log4j logger behind the scenese?

Extend the log4j Logger class and add "audit log" methods with my required parameters?

Do something even more elegant so I'm not wrapping a logging library...

答: The "message" of the error, warn, etc. methods of a log4j Logger is an arbitrary object; it doesn't need to be a string. You can create your own "message" class to contain the different parameters. Loggers can append the data differently by using a custom Layout class for the appender of the audit logger.

Title: Wrap log4j or create custom logger?


问:
Sum of all rows of all columns - Bash
I have a file like this

```<code>1 4 7 ...
2 5 8
3 6 9
</code>```

And I would like to have as output

```<code>6 15 24 ...
</code>```

That is the sum of all the lines for all the columns. I know that to sum all the lines of a certain column (say column 1) you can do like this:

```<code>awk '{sum+=$1;}END{print $1}' infile > outfile
</code>```

But I can't do it automatically for all the columns.

答:
Your answer is correct. It is just missed to print "sum". Try this:</p>

```<code>awk '{sum+=$1;} END{print sum;}' infile > outfile
</code>```

Title: Sum of all rows of all columns - Bash

Body:
I have a file like this

1 4 7 ...
2 5 8
3 6 9

And I would like to have as output

6 15 24 ...

That is the sum of all the lines for all the columns. I know that to sum all the lines of a certain column (say column 1) you can do like this:

awk '{sum+=$1;}END{print $1}' infile > outfile

But I can't do it automatically for all the columns.

Body:
Your answer is correct. It is just missed to print "sum". Try this:

awk '{sum+=$1;} END{print sum;}' infile > outfile


问:
Mac terminal says: "Cannot open display...aborting"
When I'm using XFoil (for Mac, XQuartz installed) and I'm trying to plot something, the above message comes out. Another thing, I've used the instructions of the following link to install Gnuplot and I'm worried I did some damage... it's all ok with this?
http://macappstore.org/gnuplot/</p>

答:
You have to install an xserver first. On a MAC you would use XQuartz. You need to download and install XQuartz and from within XQuartz (right click on the logo after start) start a terminal. In this terminal navigate to the location where xfoil is installed and run it. The DISPLAY variable (as shown in another answer) is automatically preset in this terminal. So no need to do this if you run as described here.

For the installation of xfoil (macOS Catalina) I had to compile the code. I followed these instructions which worked like a charm.


问:
How to implement the jaccard distance in kproto function
I am trying to implement the distance of jaccard in the kproto function (package clustMixType in R), but without any success. The aim is to do a cluster analysis of my dataset.

The distance of jaccard that I want to use is the complement of the similarity coefficient of jaccard, so

```<code>distance of jaccard = 1-[a/(a+b+c)] = [(b+c)/(a+b+c)], or
distance of jaccard = 1-[M11/(M01+M10+M11)] = [(M01+M10)/(M01+M10+M11)].
</code>```

The source code of the kproto function is presented bellow. The variable d1 is the euclidean distance for the numeric variables and the variable d2 is the distance from the simple matching coefficient for the categorical variables (as factors).

It computes the distances between the observations and the prototypes, not between observations. Prototypes are calculated, and not an observation of the data set it self.

So my twoo questions are
1) d2 is what I want to modify, but how?
2) should d1 be the sqrt of what is being calculated?

Thank you for all your help. It will be much apreciated.

Here is an excerpt of the dataset i'm working on, where V1 to V4 are factor (binary) variables (to use the jaccard distance) and V5 to V8 are numeric variables (to use the euclidean distance):

```<code>V1;V2;V3;V4;V5;V6;V7;V8
1;1;0;0;6;2;3;3
0;1;0;1;3;5;2;1
1;1;0;0;1;3;2;1
1;1;0;0;4;3;3;1
1;1;1;0;1;4;1;1
1;0;1;0;4;3;1;1
1;1;0;0;2;4;2;1
1;1;0;0;2;4;2;1
1;1;0;0;6;2;1;1
1;1;0;0;6;2;2;1
1;1;0;0;5;2;3;1
1;1;0;0;4;3;3;1
1;1;0;0;4;4;2;1
1;1;0;0;4;3;3;1
1;1;0;0;4;3;3;1
1;1;0;0;3;4;2;1
1;1;0;0;4;3;2;1
1;1;0;0;5;2;3;1
1;1;0;0;4;3;4;1
1;1;0;0;4;3;2;1
1;1;0;0;4;3;2;1
1;1;0;0;3;3;2;1
1;1;0;0;3;3;3;1
1;1;0;0;5;2;3;1
1;1;0;0;5;2;3;1
1;1;0;0;5;2;2;1
1;1;0;0;3;3;2;1
1;1;0;0;5;2;3;1
1;1;0;0;5;2;2;1
1;0;0;0;3;4;2;1
1;1;0;0;7;2;4;1
1;1;0;0;7;2;2;1
1;1;0;0;5;2;4;1
1;1;0;0;5;3;4;1
1;1;0;0;5;3;2;1
1;1;0;0;5;3;4;1
1;0;0;0;3;5;3;1
0;1;0;0;6;2;4;1
1;1;0;0;6;2;3;1
1;1;0;0;6;2;4;1
</code>```

Lets take the first twoo observations from the dataset provided above as an example:

```<code>V1;V2;V3;V4;V5;V6;V7;V8
1;1;0;0;6;2;3;3
0;1;0;1;3;5;2;1
</code>```

The algorithm first select the k prototypes from the data set randomly, so lets supose that the second observation is one of the inicial prototypes. As I understood the algorithm creates a data frame called "protos" initially with k random observations from the data set provided, so the second observation would be one of the lines of the "proto" dataframe.

The combined distance used to cluster the observations would be d=d1+lambda*d2. Lambda can also be a vector of individual weights to each variable. d is the distance between the observations in the data set provided and the "proto" matrix created initially with k random observations.

In this case, considering the first twoo observations presented, the calculated distances, between the observation (yi) and the prototype (yk), would be as follow:

```<code>Euclidian for the numeric variables (V5 to V8):
 d1=sum[(yij-ykj)^2]^0,5
 where,
    k=1 to k clusters
    i=1 to n observations
    j=5 to 8 th variable
 d1=[[(6-3)^2]+[(2-5)^2]+[(3-2)^2]+[(3-1)^2]]^0,5
 d1=[9+9+1+4]^0,5
 d1=4.796

Jaccard, for the set of binary variables (V1 to V4):
 d2=[(b+c)/(a+b+c)]
 where,
    a=1
    b=1
    c=1
    are correspondences counts between the n observations and the k prototypes, for variables 1 to 4.
 d2=[(1+1)/(1+1+1)]
 d2=2/3
 d2=0.667
</code>```

So the combined distance between this especific observation and the initial prototype of that cluster is:

```<code>d=d1+d2
d=4.796+0.667
d=5.463
</code>```

The results, as I understood, are then stored in a matrix called "d", line by line, the size of [number of lines=number of observations, number of columns = number of clusters k].

I'm expecting to correctly calculate the euclidian and jaccard distances, modifiyng the kproto function, maintaining the steps and results provided by the original function.

NOTE: the final function should work on any number of observations, variables and prototypes, and not only to my specific dataset.

I've also tried to mix the codes from kproto (clustMixType package) and dist.binary (ade4 package), but they work in different ways.

```<code>#K-Prototypes algorithm
kproto.default <- function(x, k, lambda = NULL, iter.max = 100, nstart = 1, na.rm = TRUE, keep.data = TRUE, verbose = TRUE, ...){

  # initial error checks
  if(!is.data.frame(x)) stop("x should be a data frame!")
  if(ncol(x) < 2) stop("For clustering x should contain at least two variables!")
  if(iter.max < 1 | nstart < 1) stop("iter.max and nstart must not be specified < 1!")
  if(!is.null(lambda)){
    if(any(lambda < 0)) stop("lambda must be specified >= 0!")
    if(!any(lambda > 0)) stop("lambda must be specified > 0 for at least one variable!")
    }
  # check for numeric and factor variables
  numvars <- sapply(x, is.numeric)
  anynum <- any(numvars)
  catvars <- sapply(x, is.factor)
  anyfact <- any(catvars)
  if(!anynum) stop("\n No numeric variables in x! Try using kmodes() from package klaR...\n\n")
  if(!anyfact) stop("\n No factor variables in x! Try using kmeans()...\n\n")

  # treatment of missings
  NAcount <- apply(x, 2, function(z) sum(is.na(z)))
  if(verbose){
    cat("# NAs in variables:\n")
    print(NAcount)
  }
  if(any(NAcount == nrow(x))) stop(paste("Variable(s) have only NAs please remove them:",names(NAcount)[NAcount == nrow(x)],"!"))
  if(na.rm) {
    miss <- apply(x, 1, function(z) any(is.na(z)))
    if(verbose){
      cat(sum(miss), "observation(s) with NAs.\n")
      if(sum(miss) > 0) message("Observations with NAs are removed.\n")
      cat("\n")
    }
    x <- x[!miss,]
    } # remove missings

  if(!na.rm){
    allNAs <- apply(x,1,function(z) all(is.na(z)))
    if(sum(allNAs) > 0){
      if(verbose) cat(sum(allNAs), "observation(s) where all variables NA.\n")
      warning("No meaningful cluster assignment possible for observations where all variables NA.\n")
      if(verbose) cat("\n")

    }
  }

  if(nrow(x) == 1) stop("Only one observation clustering not meaningful.")

  k_input <- k # store input k for nstart > 1 as clusters can be merged

  # initialize prototypes
  if(!is.data.frame(k)){
    if (length(k) == 1){
      if(as.integer(k) != k){k <- as.integer(k); warning(paste("k has been set to", k,"!"))}
      if(nrow(x) < k) stop("Data frame has less observations than clusters!")
      ids <- sample(nrow(x), k)
      protos <- x[ids,]
    }
    if (length(k) > 1){
      if(nrow(x) < length(k)) stop("Data frame has less observations than clusters!")
      ids <- k
      k <- length(ids)
      if(length(unique(ids)) != length(ids)) stop("If k is specified as a vector it should contain different indices!")
      if(any(ids<1)|any(ids>nrow(x))) stop("If k is specified as a vector all elements must be valid indices of x!")
      #check for integer
      protos <- x[ids,]
    }
    rm(ids)
  }
  if(is.data.frame(k)){
    if(nrow(x) < nrow(k)) stop("Data frame has less observations than clusters!")
    if(length(names(k)) != length(names(x))) stop("k and x have different numbers of columns!")
    if(any(names(k) != names(x))) stop("k and x have different column names!")
    if(anynum) {if( any(sapply(k, is.numeric) != numvars)) stop("Numeric variables of k and x do not match!")}
    if(anyfact) {if( any(sapply(k, is.factor) != catvars)) stop("Factor variables of k and x do not match!")}
    protos <- k
    k <- nrow(protos)
  }
  if(k < 1) stop("Number of clusters k must not be smaller than 1!")

  # automatic calculation of lambda
  if(length(lambda) > 1) {if(length(lambda) != sum(c(numvars,catvars))) stop("If lambda is a vector, its length should be the sum of numeric and factor variables in the data frame!")}
  if(is.null(lambda)){
    if(anynum & anyfact){
      vnum <- mean(sapply(x[,numvars, drop = FALSE], var, na.rm = TRUE))
      vcat <- mean(sapply(x[,catvars, drop = FALSE], function(z) return(1-sum((table(z)/sum(!is.na(z)))^2))))
      if (vnum == 0){
        if(verbose) warning("All numerical variables have zero variance.")
        anynum <- FALSE
      }
      if (vcat == 0){
        if(verbose) warning("All categorical variables have zero variance.")
        anyfact <- FALSE
      }
      if(anynum & anyfact){
        lambda <- vnum/vcat
        if(verbose) cat("Estimated lambda:", lambda, "\n\n")
      }else{
        lambda <- 1
      }
    }
  }

  # initialize clusters
  clusters  <- numeric(nrow(x))
  tot.dists <- NULL
  moved   <- NULL
  iter <- 1

  # check for any equal prototypes and reduce cluster number in case of occurence
  if(k > 1){
    keep.protos <- rep(TRUE,k)
    for(l in 1:(k-1)){
      for(m in (l+1):k){
        d1 <- sum((protos[l,numvars, drop = FALSE]-protos[m,numvars, drop = FALSE])^2) # euclidean for numerics
        d2 <- sum(protos[l,catvars, drop = FALSE] != protos[m,catvars, drop = FALSE]) # wtd simple matching for categorics
        if((d1+d2) == 0) keep.protos[m] <- FALSE
      }
    }
    if(!all(keep.protos)){
      protos <- protos[keep.protos,]
      k <- sum(keep.protos)
      if(verbose) message("Equal prototypes merged. Cluster number reduced to:", k, "\n\n")
    }
  }

  # special case only one cluster
  if(k == 1){clusters <- rep(1, nrow(x)); size  <- table(clusters); iter <- iter.max} # REM: named vector size is needed later...

  # start iterations for standard case (i.e. k > 1)
  while(iter < iter.max){

    # compute distances
    nrows <- nrow(x)
    dists <- matrix(NA, nrow=nrows, ncol = k)
    for(i in 1:k){
      #a0 <- proc.time()[3]
      #d1 <- apply(x[,numvars],1, function(z) sum((z-protos[i,numvars])^2)) # euclidean for numerics
      d1 <- (x[,numvars, drop = FALSE] - matrix(rep(as.numeric(protos[i, numvars, drop = FALSE]), nrows), nrow=nrows, byrow=T))^2
      if(length(lambda) == 1) d1 <- rowSums(d1, na.rm = TRUE)
      if(length(lambda) > 1) d1 <- as.matrix(d1) %*% lambda[numvars]
      #a1 <- proc.time()[3]
      #d2 <- lambda * apply(x[,catvars],1, function(z) sum((z != protos[i,catvars]))) # wtd simple matching for categorics
      d2 <- sapply(which(catvars), function(j) return(x[,j] != rep(protos[i,j], nrows)) )
      d2[is.na(d2)] <- FALSE
      if(length(lambda) == 1) d2 <- lambda * rowSums(d2)
      if(length(lambda) > 1) d2 <- as.matrix(d2) %*% lambda[catvars]
      #a2 <- proc.time()[3]
      dists[,i] <- d1 + d2
      #cat(a1-a0, a2-a1, "\n")
    }

    # assign clusters
    old.clusters  <- clusters
    # clusters      <- apply(dists, 1, function(z) which.min(z))
    clusters      <- apply(dists, 1, function(z) {a <- which.min(z); if (length(a)>1) a <- sample(a,1); return(a)}) # sample in case of multiple minima
    size          <- table(clusters)
    min.dists     <- apply(cbind(clusters, dists), 1, function(z) z[z[1]+1])
    within        <- as.numeric(by(min.dists, clusters, sum))
    tot.within    <- sum(within)
    # prevent from empty classes
    #tot.within    <- numeric(k)
    #totw.list     <- by(min.dists, clusters, sum)
    #tot.within[names(totw.list)] <- as.numeric(totw.list)

    # ...check for empty clusters and eventually reduce number of prototypes
    if (length(size) < k){
      k <- length(size)
      protos <- protos[1:length(size),]
      if(verbose) cat("Empty clusters occur. Cluster number reduced to:", k, "\n\n")
    }

    # trace
    tot.dists <- c(tot.dists, sum(tot.within))
    moved <- c(moved, sum(clusters != old.clusters))

    # compute new prototypes
    remids <- as.integer(names(size))
    for(i in remids){
      protos[which(remids == i), numvars] <- sapply(x[clusters==i, numvars, drop = FALSE], mean, na.rm = TRUE)
      protos[which(remids == i), catvars] <- sapply(x[clusters==i, catvars, drop = FALSE], function(z) levels(z)[which.max(table(z))])
    }

    if(k == 1){clusters <- rep(1, length(clusters)); size <- table(clusters); iter <- iter.max; break}

    # check for any equal prototypes and reduce cluster number in case of occurence
    if(iter == (iter.max-1)){ # REM: for last iteration equal prototypes are allowed. otherwise less prototypes than assigned clusters.
      keep.protos <- rep(TRUE,k)
      for(l in 1:(k-1)){
        for(m in (l+1):k){
          d1 <- sum((protos[l,numvars, drop = FALSE]-protos[m,numvars, drop = FALSE])^2) # euclidean for numerics
          d2 <- sum(protos[l,catvars, drop = FALSE] != protos[m,catvars, drop = FALSE]) # wtd simple matching for categorics
          if((d1+d2) == 0) keep.protos[m] <- FALSE
        }
      }
      if(!all(keep.protos)){
        protos <- protos[keep.protos,]
        k <- sum(keep.protos)
        if(verbose) cat("Equal prototypes merged. Cluster number reduced to:", k, "\n\n")
      }
    }

    # add stopping rules
    if(moved[length(moved)] ==  0) break

    if(k == 1){clusters <- rep(1, length(clusters)); size <- table(clusters); iter <- iter.max; break}

    #cat("iter", iter, "moved", moved[length(moved)], "tot.dists",tot.dists[length(tot.dists)],"\n" )
    iter <- iter+1
  }

  ### Final update of prototypes and dists
  if(iter == iter.max){ # otherwise there have been no moves anymore and prototypes correspond to cluster assignments
    # compute new prototypes
    remids <- as.integer(names(size))
    for(i in remids){
      protos[which(remids == i), numvars] <- sapply(x[clusters==i, numvars, drop = FALSE], mean, na.rm = TRUE)
      protos[which(remids == i), catvars] <- sapply(x[clusters==i, catvars, drop = FALSE], function(z) levels(z)[which.max(table(z))])
    }

    # compute distances
    nrows <- nrow(x)
    dists <- matrix(NA, nrow=nrows, ncol = k)
    for(i in 1:k){
      d1 <- (x[,numvars, drop = FALSE] - matrix(rep(as.numeric(protos[i, numvars, drop = FALSE]), nrows), nrow=nrows, byrow=T))^2
      if(length(lambda) == 1) d1 <- rowSums(d1, na.rm = TRUE)
      if(length(lambda) > 1) d1 <- as.matrix(d1) %*% lambda[numvars]
      d2 <- sapply(which(catvars), function(j) return(x[,j] != rep(protos[i,j], nrows)) )
      d2[is.na(d2)] <- FALSE
      if(length(lambda) == 1) d2 <- lambda * rowSums(d2)
      if(length(lambda) > 1) d2 <- as.matrix(d2) %*% lambda[catvars]
      dists[,i] <- d1 + d2
    }

    size          <- table(clusters)
    min.dists     <- apply(cbind(clusters, dists), 1, function(z) z[z[1]+1])
    within        <- as.numeric(by(min.dists, clusters, sum))
    tot.within    <- sum(within)
  }

  names(clusters) <- row.names(dists) <- row.names(x)
  rownames(protos) <- NULL
  # create result:
  res <- list(cluster = clusters,
              centers = protos,
              lambda = lambda,
              size = size,
              withinss = within,
              tot.withinss = tot.within,
              dists = dists,
              iter = iter,
              trace = list(tot.dists = tot.dists, moved = moved))

  # loop: if nstart > 1:
  if(nstart > 1)
    for(j in 2:nstart){
      res.new <- kproto(x=x, k=k_input, lambda = lambda,  iter.max = iter.max, nstart=1, verbose=verbose)
      if(res.new$tot.withinss < res$tot.withinss) res <- res.new
    }

  if(keep.data) res$data = x
  class(res) <- "kproto"
  return(res)
}
</code>```

答: I've managed to modify the functions to accept a variety of similarity measures and uploaded the R file at http://dx.doi.org/10.17632/63nyn9tjcd.1, in case someone needs it.</p>

Body:
I am trying to implement the distance of jaccard in the kproto function (package clustMixType in R), but without any success. The aim is to do a cluster analysis of my dataset.

The distance of jaccard that I want to use is the complement of the similarity coefficient of jaccard, so

distance of jaccard = 1-[a/(a+b+c)] = [(b+c)/(a+b+c)], or
distance of jaccard = 1-[M11/(M01+M10+M11)] = [(M01+M10)/(M01+M10+M11)].

The source code of the kproto function is presented bellow. The variable d1 is the euclidean distance for the numeric variables and the variable d2 is the distance from the simple matching coefficient for the categorical variables (as factors).

It computes the distances between the observations and the prototypes, not between observations. Prototypes are calculated, and not an observation of the data set it self.

So my twoo questions are
1) d2 is what I want to modify, but how?
2) should d1 be the sqrt of what is being calculated?

Thank you for all your help. It will be much apreciated.

Here is an excerpt of the dataset i'm working on, where V1 to V4 are factor (binary) variables (to use the jaccard distance) and V5 to V8 are numeric variables (to use the euclidean distance):

V1;V2;V3;V4;V5;V6;V7;V8
1;1;0;0;6;2;3;3
0;1;0;1;3;5;2;1
1;1;0;0;1;3;2;1
1;1;0;0;4;3;3;1
1;1;1;0;1;4;1;1
1;0;1;0;4;3;1;1
1;1;0;0;2;4;2;1
1;1;0;0;2;4;2;1
1;1;0;0;6;2;1;1
1;1;0;0;6;2;2;1
1;1;0;0;5;2;3;1
1;1;0;0;4;3;3;1
1;1;0;0;4;4;2;1
1;1;0;0;4;3;3;1
1;1;0;0;4;3;3;1
1;1;0;0;3;4;2;1
1;1;0;0;4;3;2;1
1;1;0;0;5;2;3;1
1;1;0;0;4;3;4;1
1;1;0;0;4;3;2;1
1;1;0;0;4;3;2;1
1;1;0;0;3;3;2;1
1;1;0;0;3;3;3;1
1;1;0;0;5;2;3;1
1;1;0;0;5;2;3;1
1;1;0;0;5;2;2;1
1;1;0;0;3;3;2;1
1;1;0;0;5;2;3;1
1;1;0;0;5;2;2;1
1;0;0;0;3;4;2;1
1;1;0;0;7;2;4;1
1;1;0;0;7;2;2;1
1;1;0;0;5;2;4;1
1;1;0;0;5;3;4;1
1;1;0;0;5;3;2;1
1;1;0;0;5;3;4;1
1;0;0;0;3;5;3;1
0;1;0;0;6;2;4;1
1;1;0;0;6;2;3;1
1;1;0;0;6;2;4;1

Lets take the first twoo observations from the dataset provided above as an example:

V1;V2;V3;V4;V5;V6;V7;V8
1;1;0;0;6;2;3;3
0;1;0;1;3;5;2;1

The algorithm first select the k prototypes from the data set randomly, so lets supose that the second observation is one of the inicial prototypes. As I understood the algorithm creates a data frame called "protos" initially with k random observations from the data set provided, so the second observation would be one of the lines of the "proto" dataframe.

The combined distance used to cluster the observations would be d=d1+lambda*d2. Lambda can also be a vector of individual weights to each variable. d is the distance between the observations in the data set provided and the "proto" matrix created initially with k random observations.

In this case, considering the first twoo observations presented, the calculated distances, between the observation (yi) and the prototype (yk), would be as follow:

Euclidian for the numeric variables (V5 to V8):
 d1=sum[(yij-ykj)^2]^0,5
 where,
    k=1 to k clusters
    i=1 to n observations
    j=5 to 8 th variable
 d1=[[(6-3)^2]+[(2-5)^2]+[(3-2)^2]+[(3-1)^2]]^0,5
 d1=[9+9+1+4]^0,5
 d1=4.796

Jaccard, for the set of binary variables (V1 to V4):
 d2=[(b+c)/(a+b+c)]
 where,
    a=1
    b=1
    c=1
    are correspondences counts between the n observations and the k prototypes, for variables 1 to 4.
 d2=[(1+1)/(1+1+1)]
 d2=2/3
 d2=0.667

So the combined distance between this especific observation and the initial prototype of that cluster is:

d=d1+d2
d=4.796+0.667
d=5.463

The results, as I understood, are then stored in a matrix called "d", line by line, the size of [number of lines=number of observations, number of columns = number of clusters k].

I'm expecting to correctly calculate the euclidian and jaccard distances, modifiyng the kproto function, maintaining the steps and results provided by the original function.

NOTE: the final function should work on any number of observations, variables and prototypes, and not only to my specific dataset.

I've also tried to mix the codes from kproto (clustMixType package) and dist.binary (ade4 package), but they work in different ways.

#K-Prototypes algorithm
kproto.default <- function(x, k, lambda = NULL, iter.max = 100, nstart = 1, na.rm = TRUE, keep.data = TRUE, verbose = TRUE, ...){

  # initial error checks
  if(!is.data.frame(x)) stop("x should be a data frame!")
  if(ncol(x) < 2) stop("For clustering x should contain at least two variables!")
  if(iter.max < 1 | nstart < 1) stop("iter.max and nstart must not be specified < 1!")
  if(!is.null(lambda)){
    if(any(lambda < 0)) stop("lambda must be specified >= 0!")
    if(!any(lambda > 0)) stop("lambda must be specified > 0 for at least one variable!")
    }
  # check for numeric and factor variables
  numvars <- sapply(x, is.numeric)
  anynum <- any(numvars)
  catvars <- sapply(x, is.factor)
  anyfact <- any(catvars)
  if(!anynum) stop("\n No numeric variables in x! Try using kmodes() from package klaR...\n\n")
  if(!anyfact) stop("\n No factor variables in x! Try using kmeans()...\n\n")

  # treatment of missings
  NAcount <- apply(x, 2, function(z) sum(is.na(z)))
  if(verbose){
    cat("# NAs in variables:\n")
    print(NAcount)
  }
  if(any(NAcount == nrow(x))) stop(paste("Variable(s) have only NAs please remove them:",names(NAcount)[NAcount == nrow(x)],"!"))
  if(na.rm) {
    miss <- apply(x, 1, function(z) any(is.na(z)))
    if(verbose){
      cat(sum(miss), "observation(s) with NAs.\n")
      if(sum(miss) > 0) message("Observations with NAs are removed.\n")
      cat("\n")
    }
    x <- x[!miss,]
    } # remove missings

  if(!na.rm){
    allNAs <- apply(x,1,function(z) all(is.na(z)))
    if(sum(allNAs) > 0){
      if(verbose) cat(sum(allNAs), "observation(s) where all variables NA.\n")
      warning("No meaningful cluster assignment possible for observations where all variables NA.\n")
      if(verbose) cat("\n")

    }
  }

  if(nrow(x) == 1) stop("Only one observation clustering not meaningful.")

  k_input <- k # store input k for nstart > 1 as clusters can be merged

  # initialize prototypes
  if(!is.data.frame(k)){
    if (length(k) == 1){
      if(as.integer(k) != k){k <- as.integer(k); warning(paste("k has been set to", k,"!"))}
      if(nrow(x) < k) stop("Data frame has less observations than clusters!")
      ids <- sample(nrow(x), k)
      protos <- x[ids,]
    }
    if (length(k) > 1){
      if(nrow(x) < length(k)) stop("Data frame has less observations than clusters!")
      ids <- k
      k <- length(ids)
      if(length(unique(ids)) != length(ids)) stop("If k is specified as a vector it should contain different indices!")
      if(any(ids<1)|any(ids>nrow(x))) stop("If k is specified as a vector all elements must be valid indices of x!")
      #check for integer
      protos <- x[ids,]
    }
    rm(ids)
  }
  if(is.data.frame(k)){
    if(nrow(x) < nrow(k)) stop("Data frame has less observations than clusters!")
    if(length(names(k)) != length(names(x))) stop("k and x have different numbers of columns!")
    if(any(names(k) != names(x))) stop("k and x have different column names!")
    if(anynum) {if( any(sapply(k, is.numeric) != numvars)) stop("Numeric variables of k and x do not match!")}
    if(anyfact) {if( any(sapply(k, is.factor) != catvars)) stop("Factor variables of k and x do not match!")}
    protos <- k
    k <- nrow(protos)
  }
  if(k < 1) stop("Number of clusters k must not be smaller than 1!")

  # automatic calculation of lambda
  if(length(lambda) > 1) {if(length(lambda) != sum(c(numvars,catvars))) stop("If lambda is a vector, its length should be the sum of numeric and factor variables in the data frame!")}
  if(is.null(lambda)){
    if(anynum & anyfact){
      vnum <- mean(sapply(x[,numvars, drop = FALSE], var, na.rm = TRUE))
      vcat <- mean(sapply(x[,catvars, drop = FALSE], function(z) return(1-sum((table(z)/sum(!is.na(z)))^2))))
      if (vnum == 0){
        if(verbose) warning("All numerical variables have zero variance.")
        anynum <- FALSE
      }
      if (vcat == 0){
        if(verbose) warning("All categorical variables have zero variance.")
        anyfact <- FALSE
      }
      if(anynum & anyfact){
        lambda <- vnum/vcat
        if(verbose) cat("Estimated lambda:", lambda, "\n\n")
      }else{
        lambda <- 1
      }
    }
  }

  # initialize clusters
  clusters  <- numeric(nrow(x))
  tot.dists <- NULL
  moved   <- NULL
  iter <- 1

  # check for any equal prototypes and reduce cluster number in case of occurence
  if(k > 1){
    keep.protos <- rep(TRUE,k)
    for(l in 1:(k-1)){
      for(m in (l+1):k){
        d1 <- sum((protos[l,numvars, drop = FALSE]-protos[m,numvars, drop = FALSE])^2) # euclidean for numerics
        d2 <- sum(protos[l,catvars, drop = FALSE] != protos[m,catvars, drop = FALSE]) # wtd simple matching for categorics
        if((d1+d2) == 0) keep.protos[m] <- FALSE
      }
    }
    if(!all(keep.protos)){
      protos <- protos[keep.protos,]
      k <- sum(keep.protos)
      if(verbose) message("Equal prototypes merged. Cluster number reduced to:", k, "\n\n")
    }
  }

  # special case only one cluster
  if(k == 1){clusters <- rep(1, nrow(x)); size  <- table(clusters); iter <- iter.max} # REM: named vector size is needed later...

  # start iterations for standard case (i.e. k > 1)
  while(iter < iter.max){

    # compute distances
    nrows <- nrow(x)
    dists <- matrix(NA, nrow=nrows, ncol = k)
    for(i in 1:k){
      #a0 <- proc.time()[3]
      #d1 <- apply(x[,numvars],1, function(z) sum((z-protos[i,numvars])^2)) # euclidean for numerics
      d1 <- (x[,numvars, drop = FALSE] - matrix(rep(as.numeric(protos[i, numvars, drop = FALSE]), nrows), nrow=nrows, byrow=T))^2
      if(length(lambda) == 1) d1 <- rowSums(d1, na.rm = TRUE)
      if(length(lambda) > 1) d1 <- as.matrix(d1) %*% lambda[numvars]
      #a1 <- proc.time()[3]
      #d2 <- lambda * apply(x[,catvars],1, function(z) sum((z != protos[i,catvars]))) # wtd simple matching for categorics
      d2 <- sapply(which(catvars), function(j) return(x[,j] != rep(protos[i,j], nrows)) )
      d2[is.na(d2)] <- FALSE
      if(length(lambda) == 1) d2 <- lambda * rowSums(d2)
      if(length(lambda) > 1) d2 <- as.matrix(d2) %*% lambda[catvars]
      #a2 <- proc.time()[3]
      dists[,i] <- d1 + d2
      #cat(a1-a0, a2-a1, "\n")
    }

    # assign clusters
    old.clusters  <- clusters
    # clusters      <- apply(dists, 1, function(z) which.min(z))
    clusters      <- apply(dists, 1, function(z) {a <- which.min(z); if (length(a)>1) a <- sample(a,1); return(a)}) # sample in case of multiple minima
    size          <- table(clusters)
    min.dists     <- apply(cbind(clusters, dists), 1, function(z) z[z[1]+1])
    within        <- as.numeric(by(min.dists, clusters, sum))
    tot.within    <- sum(within)
    # prevent from empty classes
    #tot.within    <- numeric(k)
    #totw.list     <- by(min.dists, clusters, sum)
    #tot.within[names(totw.list)] <- as.numeric(totw.list)

    # ...check for empty clusters and eventually reduce number of prototypes
    if (length(size) < k){
      k <- length(size)
      protos <- protos[1:length(size),]
      if(verbose) cat("Empty clusters occur. Cluster number reduced to:", k, "\n\n")
    }

    # trace
    tot.dists <- c(tot.dists, sum(tot.within))
    moved <- c(moved, sum(clusters != old.clusters))

    # compute new prototypes
    remids <- as.integer(names(size))
    for(i in remids){
      protos[which(remids == i), numvars] <- sapply(x[clusters==i, numvars, drop = FALSE], mean, na.rm = TRUE)
      protos[which(remids == i), catvars] <- sapply(x[clusters==i, catvars, drop = FALSE], function(z) levels(z)[which.max(table(z))])
    }

    if(k == 1){clusters <- rep(1, length(clusters)); size <- table(clusters); iter <- iter.max; break}

    # check for any equal prototypes and reduce cluster number in case of occurence
    if(iter == (iter.max-1)){ # REM: for last iteration equal prototypes are allowed. otherwise less prototypes than assigned clusters.
      keep.protos <- rep(TRUE,k)
      for(l in 1:(k-1)){
        for(m in (l+1):k){
          d1 <- sum((protos[l,numvars, drop = FALSE]-protos[m,numvars, drop = FALSE])^2) # euclidean for numerics
          d2 <- sum(protos[l,catvars, drop = FALSE] != protos[m,catvars, drop = FALSE]) # wtd simple matching for categorics
          if((d1+d2) == 0) keep.protos[m] <- FALSE
        }
      }
      if(!all(keep.protos)){
        protos <- protos[keep.protos,]
        k <- sum(keep.protos)
        if(verbose) cat("Equal prototypes merged. Cluster number reduced to:", k, "\n\n")
      }
    }

    # add stopping rules
    if(moved[length(moved)] ==  0) break

    if(k == 1){clusters <- rep(1, length(clusters)); size <- table(clusters); iter <- iter.max; break}

    #cat("iter", iter, "moved", moved[length(moved)], "tot.dists",tot.dists[length(tot.dists)],"\n" )
    iter <- iter+1
  }

  ### Final update of prototypes and dists
  if(iter == iter.max){ # otherwise there have been no moves anymore and prototypes correspond to cluster assignments
    # compute new prototypes
    remids <- as.integer(names(size))
    for(i in remids){
      protos[which(remids == i), numvars] <- sapply(x[clusters==i, numvars, drop = FALSE], mean, na.rm = TRUE)
      protos[which(remids == i), catvars] <- sapply(x[clusters==i, catvars, drop = FALSE], function(z) levels(z)[which.max(table(z))])
    }

    # compute distances
    nrows <- nrow(x)
    dists <- matrix(NA, nrow=nrows, ncol = k)
    for(i in 1:k){
      d1 <- (x[,numvars, drop = FALSE] - matrix(rep(as.numeric(protos[i, numvars, drop = FALSE]), nrows), nrow=nrows, byrow=T))^2
      if(length(lambda) == 1) d1 <- rowSums(d1, na.rm = TRUE)
      if(length(lambda) > 1) d1 <- as.matrix(d1) %*% lambda[numvars]
      d2 <- sapply(which(catvars), function(j) return(x[,j] != rep(protos[i,j], nrows)) )
      d2[is.na(d2)] <- FALSE
      if(length(lambda) == 1) d2 <- lambda * rowSums(d2)
      if(length(lambda) > 1) d2 <- as.matrix(d2) %*% lambda[catvars]
      dists[,i] <- d1 + d2
    }

    size          <- table(clusters)
    min.dists     <- apply(cbind(clusters, dists), 1, function(z) z[z[1]+1])
    within        <- as.numeric(by(min.dists, clusters, sum))
    tot.within    <- sum(within)
  }

  names(clusters) <- row.names(dists) <- row.names(x)
  rownames(protos) <- NULL
  # create result:
  res <- list(cluster = clusters,
              centers = protos,
              lambda = lambda,
              size = size,
              withinss = within,
              tot.withinss = tot.within,
              dists = dists,
              iter = iter,
              trace = list(tot.dists = tot.dists, moved = moved))

  # loop: if nstart > 1:
  if(nstart > 1)
    for(j in 2:nstart){
      res.new <- kproto(x=x, k=k_input, lambda = lambda,  iter.max = iter.max, nstart=1, verbose=verbose)
      if(res.new$tot.withinss < res$tot.withinss) res <- res.new
    }

  if(keep.data) res$data = x
  class(res) <- "kproto"
  return(res)
}


问:
Which technologies/concepts do you suggest I learn before creating an iPhone game?
Sorry if this is a broad question, but other than Objective-C, Cocoa, and OpenGL ES, what technologies or concepts would you suggest I read up on before writing a game for the iPhone?  I'm a beginning game developer and need all the help I can get :)</p>

答:
Sorry, my answer is not computing related.

A game tells a story, a great game tells a great story. So I would suggest to learn principles of storytelling.

Not going as scholar as Aristotle's Poetics, I recommend more modern Story by Robert McKee. It focuses on movie making, but I am pretty sure that many of the concepts he develops can be applied to game making.

OwnerDisplayName: DevFunGuy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: mouviciel


问:
JavaScript passing argument problem
I have following code

```<code>for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }
</code>```

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

答:
You need to create a function closure and pass in the variables that you want to persist as arguments as follows:</p>

```<code>for (var i = 0; i < that.$el.mini.length; i++) {
    var pag = that.$el.mini[i].pagination;
    $('li', pag).each(function (j, el) {

        // function closure to persist i, j, and el
        (function (idx, jdx, elem) {
            $(elem).click(function () {
                that.slider_fn.mini.show(idx, jdx);
                return false;
            });
        } (i, j, el));

    });
}
</code>```

Title: JavaScript passing argument problem

Body:
I have following code

for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

Body:
You need to create a function closure and pass in the variables that you want to persist as arguments as follows:

for (var i = 0; i < that.$el.mini.length; i++) {
    var pag = that.$el.mini[i].pagination;
    $('li', pag).each(function (j, el) {

        // function closure to persist i, j, and el
        (function (idx, jdx, elem) {
            $(elem).click(function () {
                that.slider_fn.mini.show(idx, jdx);
                return false;
            });
        } (i, j, el));

    });
}


问:
Conversion between Cartesian vs. Polar Coordinates. Hoping the result is positive
I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.

For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I wish the angle is 189.92624551. (I hope all of the angles after conversion are between 0~360 degree)

How I fix this?

Thanks!!!

```<code>import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
    return np.angle(complex_format, deg=deg).squeeze()

print(cart_to_pol(points))
</code>```

答:
You could use np.where to add 360 to the negative angles:

```<code>import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    angles = np.angle(complex_format, deg=deg).squeeze()
    summand = 360 if deg else 2*np.pi
    return np.where(angles < 0, angles+summand, angles)

print(cart_to_pol(points))
</code>```

Output:

```<code>[189.92624551 188.53076561 187.12501635 185.71059314 184.28915333]
</code>```

Note that complex numbers are not needed here. arctan2(y, x) calculates the desired angle. To get the distances: np.linalg.norm(diff_with_center, axis=-1).

def cart_to_pol(coords, center=[50, 50], deg=True):
    conversion = 180 / np.pi if deg else 1
    diff_with_center = points - center
    angles = np.arctan2(diff_with_center[:, 1], diff_with_center[:, 0])
    return conversion * np.where(angles < 0, angles + 2*np.pi, angles)
```

Body:
I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.

For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I wish the angle is 189.92624551. (I hope all of the angles after conversion are between 0~360 degree)

How I fix this?

Thanks!!!

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
    return np.angle(complex_format, deg=deg).squeeze()

print(cart_to_pol(points))

Body:
You could use np.where to add 360 to the negative angles:

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    angles = np.angle(complex_format, deg=deg).squeeze()
    summand = 360 if deg else 2*np.pi
    return np.where(angles < 0, angles+summand, angles)

print(cart_to_pol(points))

Output:

[189.92624551 188.53076561 187.12501635 185.71059314 184.28915333]

Note that complex numbers are not needed here. arctan2(y, x) calculates the desired angle. To get the distances: np.linalg.norm(diff_with_center, axis=-1).

def cart_to_pol(coords, center=[50, 50], deg=True):
    conversion = 180 / np.pi if deg else 1
    diff_with_center = points - center
    angles = np.arctan2(diff_with_center[:, 1], diff_with_center[:, 0])
    return conversion * np.where(angles < 0, angles + 2*np.pi, angles)


问:
Git for windows version 2.5.3 not able to push changes
I am receiving errors below when I try to push changes(not a problem with memory, or other already issues already mention on stackoverflow), errors are gone when I uninstall latest version and install

1.9.x

verion. Please consider this if you are having the same issue

fatal: mmap failed: No error

fatal: The remote end hung up unexpectedly

fatal: The remote end hung up unexpectedly

fatal: write error: Bad file descriptor

error: failed to push some refs to

答:
I faced the same issue, and realised that OneDrive was paused. If the files are "online", the files will be fetched automatically, but not if OneDrive is paused or not running:</p>

```<code>git reset --hard <hash>
fatal: mmap failed: Invalid argument
</code>```

Body:
I faced the same issue, and realised that OneDrive was paused. If the files are "online", the files will be fetched automatically, but not if OneDrive is paused or not running:

git reset --hard <hash>
fatal: mmap failed: Invalid argument


问:
How to use svg images on react-native?
I'm trying to use svg images on my native react application, I'm developing on Android.

So I followed this tutorial =>

https://medium.com/faun/add-custom-svg-icons-to-your-expo-app-279b492f6a15

I have an error Unable to read the 'fill' property of undefined while I manage to display the image, so I try to downgrade the version of react-native- svg and the image is displayed but as soon as I integrated react-navigation my application expo on crash at startup.

So I looked for a long time for the cause of this crash.

I tried to delete the react-native-svg library, the metroconfig.js file, and expo worked again, I don't know if this was the cause of the problem.

I would like to know if people have encountered these problems or if not what is the best method which works with the current version of RN to import a svg image in a react-native application?

Thank you in advance for your help and your answers.

EDIT

I tested react-native-svg and react-native-transformer-svg with the latest version of react native / expo / sdk expo

From the moment I create the metro.config.js file and link it with expo by updating the app.json file, my expo application crashes at startup.

I had to use react-native-svg without react-native-transformer-svg, that is to say that I have to convert an SVG file into a reactable SVG file.

If someone has a working solution to import svg files automatically, it would be of great help to me.

答:
```<code>Install react-native-svg-transformer

npm i react-native-svg-transformer --save
</code>```

I'm using SVG as following and it works fine

```<code>import LOGOSVG from "assets/svg/logo.svg"
in render

<View>
  <LOGOSVG
    width="100%"
    height="70%"
  />
</View>
</code>```

Title: How to use svg images on react-native?

Body:
Install react-native-svg-transformer

npm i react-native-svg-transformer --save

I'm using SVG as following and it works fine

import LOGOSVG from "assets/svg/logo.svg"
in render

<View>
  <LOGOSVG
    width="100%"
    height="70%"
  />
</View>


问:
How to refer and access the dictionary's keys and values fron one function into another function in Python 3?
How should we refer a value of a key from a dictionary in one function (i.e. method) into another function ? My piece of python code is as below -

```<code>def function1 (x1, x2):
    dict1 = {'k1':x1, 'k2':x2}
    return

def function2 ():

    # Here function1() is being called and passing 10 into x1 and 20 into x2 of function1 ()...
    function1(10,20)
    print(f"First Value is: {dict1[k1]}"
          f"Second Value is: {dict1[k2]}")
</code>```

I want the result as below -

First value is: 10

Second value is: 20

But I'm not able to ACCESS "{dict1[k1]}" and "{dict1[k2]}" key-value of dict1{} which is from function1() inside the function2(). So, how to access the Keys-values of a dictionary from one function inside another function?

答:
There are several ways to achieve this, one could be to return the whole dictionary and loop through this new dictionary, however I would implement it as so:

```<code>def function1 (x1, x2):
    dict1 = {'k1':x1, 'k2':x2}
    return dict1.values()

def function2 ():

    # Here function1() is being called and passing 10 into x1 and 20 into x2 of function1 ()...
    x, y = function1(10,20)
    print(f"First Value is: {x}"
          f"\nSecond Value is: {y}")
function2()
</code>```

By returning only the values you can avoid loops

Output:

```<code>First Value is: 10
Second Value is: 20
</code>```

Body:
How should we refer a value of a key from a dictionary in one function (i.e. method) into another function ? My piece of python code is as below -

def function1 (x1, x2):
    dict1 = {'k1':x1, 'k2':x2}
    return

def function2 ():

    # Here function1() is being called and passing 10 into x1 and 20 into x2 of function1 ()...
    function1(10,20)
    print(f"First Value is: {dict1[k1]}"
          f"Second Value is: {dict1[k2]}")

I want the result as below -

First value is: 10

Second value is: 20

But I'm not able to ACCESS "{dict1[k1]}" and "{dict1[k2]}" key-value of dict1{} which is from function1() inside the function2(). So, how to access the Keys-values of a dictionary from one function inside another function?

Body:
There are several ways to achieve this, one could be to return the whole dictionary and loop through this new dictionary, however I would implement it as so:

def function1 (x1, x2):
    dict1 = {'k1':x1, 'k2':x2}
    return dict1.values()

def function2 ():

    # Here function1() is being called and passing 10 into x1 and 20 into x2 of function1 ()...
    x, y = function1(10,20)
    print(f"First Value is: {x}"
          f"\nSecond Value is: {y}")
function2()

By returning only the values you can avoid loops

Output:

First Value is: 10
Second Value is: 20


问:
Why does Axios.get give me an [object Object]
I'm trying to get a JSON object into an array to show on a table, however it gives me the error of: TypeError: this.state.allVersions.map is not a function.

```<code>componentDidMount()
{
    axios.get('http://localhost:5000/myblog/' + this.props.match.params.id).then(res =>
    {
        console.log(res.data);
        this.setState({allVersions: res.data});
        console.log(this.allVersions)
    }).catch((err) =>
    {
        console.log(err);
    })
}
</code>```

Here I'm trying using the endpoint to get a JSON object and on the first console log, it gives me the right data but on the second console log it gives me [object Object].

Also,

```<code>{console.log("state of all versions: " + this.state.allVersions)}
</code>```

gets me an [object Object] but if i do

```<code>{console.log(this.state.allVersions)}
</code>```

it gets me the right data? Why is removing the string doing this?

答:
Concatenation of string and object would make object be converted to a string, not to a JSON.
Instead you would want to convert your object to JSON before concatenation.

so in your code it will look like

```<code>console.log("state of all versions: " + JSON.stringify(this.state.allVersions))
</code>```

Body:
I'm trying to get a JSON object into an array to show on a table, however it gives me the error of: TypeError: this.state.allVersions.map is not a function.

componentDidMount()
{
    axios.get('http://localhost:5000/myblog/' + this.props.match.params.id).then(res =>
    {
        console.log(res.data);
        this.setState({allVersions: res.data});
        console.log(this.allVersions)
    }).catch((err) =>
    {
        console.log(err);
    })
}

Here I'm trying using the endpoint to get a JSON object and on the first console log, it gives me the right data but on the second console log it gives me [object Object].

Also,

{console.log("state of all versions: " + this.state.allVersions)}

gets me an [object Object] but if i do

{console.log(this.state.allVersions)}

it gets me the right data? Why is removing the string doing this?

Body:
Concatenation of string and object would make object be converted to a string, not to a JSON.
Instead you would want to convert your object to JSON before concatenation.

so in your code it will look like

console.log("state of all versions: " + JSON.stringify(this.state.allVersions))


问:
When I kill a process in Android a Service is not restarted
I know that I can kill a process when I press the red square button that is in the logcat (Having the corresponding device and process selected).

This image shows the way I use to kill an android process

However, when I do that the service is not restarted how I expect. It calls onCreate and onDestroy and it doesn't call onStartCommand despite the fact that the onStartCommand returns START_STICKY.

I show you my code and please if you have an idea of what the problem might be tell me

Service code to start a music

答: Have you declared service inside manifest file </p>


问:
Reference to Javascript Library in Typescript project
My Project is in Typescript. In this project I want to refer or import another Javascript UI Library. Is there a Way of just importing them and NOT checking the Namespaces for those libraries while doing the "tsc".

For example, suppose the JS UI library has some classes called jsMyLibrary.ui.Button. My requirement is that while my tsc is running, it should not check for any string starting with jsMyLibrary*

答:
The default behaviour of tsc is to compile all .ts, .d.ts and .tsx files in your project. Javascript files will not be compiled unless this is specified in tsconfig.json. If 'jsMyLibrary' does contain some .ts or .d.ts files in the library and you don't want to compile these, it is possible to exclude certain files/file patterns in tsconfig.json:

```<code>"exclude": ["jsMyLibrary/**/*.ts"]
</code>```

"exclude" defaults to some folders such as node_modules if it is not specified, read more about it here

Body:
The default behaviour of tsc is to compile all .ts, .d.ts and .tsx files in your project. Javascript files will not be compiled unless this is specified in tsconfig.json. If 'jsMyLibrary' does contain some .ts or .d.ts files in the library and you don't want to compile these, it is possible to exclude certain files/file patterns in tsconfig.json:

"exclude": ["jsMyLibrary/**/*.ts"]

"exclude" defaults to some folders such as node_modules if it is not specified, read more about it here


问:
Vue.js - JSON API data doesn't appear on click event
I'm having difficulties with a VueJS project of mine.

I'm trying to get a click event to show additional user data from a JSON API.

The console recognizes the click event, but for some odd reason, none of the additional data that I'm trying to toggle, appears.

I'm suspecting that the method is at fault, or maybe perhaps that the click event isn't configured properly, because the data is there, but nothing shows -- no errors in the console either.

Any suggestions would be greatly appreciated!

<template>

                        Name
                        User name
                        Email

                    {{ user.name }}
                    {{ user.username }}
                    {{ user.email }}

{{ userInfo.name }}

{{ userInfo.username }}

{{ userInfo.adress.street }}

{{ userInfo.address.suite }}

{{ userInfo.address.city }}

{{ userInfo.address.zipcode }}

</template>

```

答:
First, you'e making a typo by missing 'd' in
{{ userInfo.adress.street }}
, second your loop should be in
 element, finally pass user.id as parameter in @click="showInfo(user.id)"

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  data() {
    return {
      users: [],
      userInfo: null
    }
  },

  methods: {
    showInfo(userId) {

      for (const user of this.users) {

        if (user.id == userId) {

          this.userInfo = user
          console.log(this.userInfo)
        }
      }
    }
  },

  created() {
    // Fetch JSON data
    fetch('https://jsonplaceholder.typicode.com/users/')
      .then(response => response.json())
      .then(json => {
        this.users = json
      })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.col-12 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.middleSection {
  height: 87vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 5vh !important;
}</code>```

<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

                Name
                User name
                Email

                {{ user.name }}
                {{ user.username }}
                {{ user.email }}

{{ userInfo.name }}

{{ userInfo.username }}

{{ userInfo.address.street }}

{{ userInfo.address.suite }}

{{ userInfo.address.city }}

{{ userInfo.address.zipcode }}

```

Body:
First, you'e making a typo by missing 'd' in <div>{{ userInfo.adress.street }}</div>, second your loop should be in <tr> element, finally pass user.id as parameter in @click="showInfo(user.id)"

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  data() {
    return {
      users: [],
      userInfo: null
    }
  },

  methods: {
    showInfo(userId) {

      for (const user of this.users) {

        if (user.id == userId) {

          this.userInfo = user
          console.log(this.userInfo)
        }
      }
    }
  },

  created() {
    // Fetch JSON data
    fetch('https://jsonplaceholder.typicode.com/users/')
      .then(response => response.json())
      .then(json => {
        this.users = json
      })
  }
})

.col-12 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.middleSection {
  height: 87vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 5vh !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

<div id="app">
  <section class="middleSection">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <table class="table table-dark">
            <thead>
              <tr>
                <th>Name</th>
                <th>User name</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody >
              <tr data-toggle="collapse" v-for="(user, index) in users" :key="index"  @click="showInfo(user.id)">
                <td>{{ user.name }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
              </tr>
            </tbody>
          </table>

          <div v-if="userInfo" class="card card-body">
            <div>{{ userInfo.name }}</div>
            <div>{{ userInfo.username }}</div>
            <div>{{ userInfo.address.street }}</div>
            <div>{{ userInfo.address.suite }}</div>
            <div>{{ userInfo.address.city }}</div>
            <div>{{ userInfo.address.zipcode }}</div>
          </div>

        </div>
      </div>
    </div>
  </section>
</div>


问:
How to upgrade Spyder in Anaconda?
I just installed new Anaconda with Python 3.7. The Spyder version is still 3.36 and it says there is an new version 4.0.1 available each time I started Spyder.

I tried to upgrade Spyder using two approach:

conda update spyder (it didn't work even there was no error)

conda install spyder=4.0.1

Using second method, found so many conflict like below.

答: Open "Anaconda Navigator" and in Spyder Frame you'll see a gear icon, click on that and then click on "Update Application".</p>

Title: How to upgrade Spyder in Anaconda?


问:
How to process a string as a file to contruct a ZipFile object?
I am currently pulling data from a database with blobs. I retrieve the blob from the database, but I need to parse the text. the ZipFile class takes in files not strings, so what would be a good way to solve this?</p>

```<code>import zipfile

data= request.files["file"].read() #this is just binary data
zipfile.ZipFile(data)
</code>```

答:
use io.BytesIO or io.StringIO<br>
essentially u just need file-like interface </p>

Body:
I am currently pulling data from a database with blobs. I retrieve the blob from the database, but I need to parse the text. the ZipFile class takes in files not strings, so what would be a good way to solve this?

import zipfile

data= request.files["file"].read() #this is just binary data
zipfile.ZipFile(data)

Body:
use io.BytesIO or io.StringIO

essentially u just need file-like interface