问:
Create an array of HashMaps while specifying HashMap<String, Integer>
I am trying to create an array of HashMaps within a class and then retrieve a hashmap from the array for calculation purposes. Here is my code:

```<code>HashMap<String, Integer>[] boardPopulation= (HashMap<String, Integer>[]) new HashMap[populationSize];
    for(int i=0; i < populationSize; i++){
        generateQueens();
        boardPopulation[i] = queenMap;
    }
    for(int i=0; i < populationSize; i++){
        queenMap = boardPopulation[i];
        printBoard();
    }
</code>```

When I compile I get two issues:

Board.java uses unchecked or unsafe operations, recompile with -Xlint:unchecked.

When I compile with "Xlint:unchecked" I get

Warning: [unchecked] unchecked cast
HashMap[] boardPop.......(same as line 1 of above code)

required: HashMap[]
found: HashMap[]

Please help me ! :D

Ideally I would like to not have to use Xlint unchecked, but ultimately I really just need to be able to retrive a HashMap from the list and assign it to queenMap so I can do calculations within the class.

Thankyou

答:
Sorry for answering a slightly different question but if an array isn't essential, have you tried using a generic list:</p>

```<code>List<Map<String, Integer>> boardPopulations = new ArrayList<>();
boardPopulations.add(new HashMap<>());
</code>```

Body:
I am trying to create an array of HashMaps within a class and then retrieve a hashmap from the array for calculation purposes. Here is my code:

HashMap<String, Integer>[] boardPopulation= (HashMap<String, Integer>[]) new HashMap[populationSize];
    for(int i=0; i < populationSize; i++){
        generateQueens();
        boardPopulation[i] = queenMap;
    }
    for(int i=0; i < populationSize; i++){
        queenMap = boardPopulation[i];
        printBoard();
    }

When I compile I get two issues:

Board.java uses unchecked or unsafe operations, recompile with -Xlint:unchecked.

When I compile with "Xlint:unchecked" I get

Warning: [unchecked] unchecked cast
HashMap[] boardPop.......(same as line 1 of above code)

required: HashMap[]
found: HashMap[]

Please help me ! :D

Ideally I would like to not have to use Xlint unchecked, but ultimately I really just need to be able to retrive a HashMap from the list and assign it to queenMap so I can do calculations within the class.

Thankyou

Body:
Sorry for answering a slightly different question but if an array isn't essential, have you tried using a generic list:

List<Map<String, Integer>> boardPopulations = new ArrayList<>();
boardPopulations.add(new HashMap<>());


来源: stackexchange

问:
How to secure the password used by TextEncryptor in spring boot
I need to encrypt some details for the users of my application (not the password, I am using bcrypt for that), I need to access the details at some point in the future, so i need to be able to decrypt these details, to do that, I have the following class in my spring boot application, my question is how to secure the password used to encrypt the text?

```<code>import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;

public class Crypto
{

 final static String password = "How_to_Secure_This_Password?";

 public static String encrypt(String textToEncrypt, String salt)
 {
    if (textToEncrypt != null && !textToEncrypt.isEmpty())
    {
        TextEncryptor encryptor = Encryptors.text(password, salt);
        String encryptedText = encryptor.encrypt(textToEncrypt);
        return encryptedText;
    }

    return null;

 }

 public static String decrypt(String encryptedText, String salt)
 {
    if(encryptedText != null && !encryptedText.isEmpty())
    {
        TextEncryptor decryptor = Encryptors.text(password, salt);
        String decryptedText = decryptor.decrypt(encryptedText);

        return decryptedText;
    }

    return null;

 }
}
</code>```

From my research so far I can suggest the following solutions:

1- Get the password from a properties file and use Spring Cloud Config for the encryption/decryption feature for the properties file (values prefixed with the string {cipher}), a good starting point is here. I don't like this solution as I don't need the client/sever config structure, and I don't feel good about using it for the sake of one feature only, I believe Spring framework should have similar feature.

2- Use Jasypt library, or its 'unofficial' support for spring boot from here. Again, not sure if the problem is a matter of encrypting this password in a properties file?

3- use the Vault which looks built for something similar to what I need here (API keys, secrets etc...) but it is too much overhead to build, maintain, and integrate ...

My argument here is that if an attacker was able to access my database machine/s then he is most likely will be able to access the application machine/s which means he may be able to revers-engineer the class and will be able to decrypt all the details which I want to secure! I feel confused here, what is best practice and the industry standard here?

答: Vault is a good solution, but one way to do it would be to provide the password manually when you initialise the component, so that it would be stored in memory and not typed in any config file.</p>

ContentLicense: CC BY-SA 3.0

Body:
I need to encrypt some details for the users of my application (not the password, I am using bcrypt for that), I need to access the details at some point in the future, so i need to be able to decrypt these details, to do that, I have the following class in my spring boot application, my question is how to secure the password used to encrypt the text?

import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;

public class Crypto
{

 final static String password = "How_to_Secure_This_Password?";

 public static String encrypt(String textToEncrypt, String salt)
 {
    if (textToEncrypt != null && !textToEncrypt.isEmpty())
    {
        TextEncryptor encryptor = Encryptors.text(password, salt);
        String encryptedText = encryptor.encrypt(textToEncrypt);
        return encryptedText;
    }

    return null;

 }

 public static String decrypt(String encryptedText, String salt)
 {
    if(encryptedText != null && !encryptedText.isEmpty())
    {
        TextEncryptor decryptor = Encryptors.text(password, salt);
        String decryptedText = decryptor.decrypt(encryptedText);

        return decryptedText;
    }

    return null;

 }
}

From my research so far I can suggest the following solutions:

1- Get the password from a properties file and use Spring Cloud Config for the encryption/decryption feature for the properties file (values prefixed with the string {cipher}), a good starting point is here. I don't like this solution as I don't need the client/sever config structure, and I don't feel good about using it for the sake of one feature only, I believe Spring framework should have similar feature.

2- Use Jasypt library, or its 'unofficial' support for spring boot from here. Again, not sure if the problem is a matter of encrypting this password in a properties file?

3- use the Vault which looks built for something similar to what I need here (API keys, secrets etc...) but it is too much overhead to build, maintain, and integrate ...

My argument here is that if an attacker was able to access my database machine/s then he is most likely will be able to access the application machine/s which means he may be able to revers-engineer the class and will be able to decrypt all the details which I want to secure! I feel confused here, what is best practice and the industry standard here?


问:
Can you use Document.SetPropertyValue(string,string) on nested properties?
Say for a given DocumentDb document such as:

```<code>{
    "id": "CDC101",
    "title": "Fundamentals of database design",
    "authordetails": {
       "Name" : "Dave",
       "Age : "33"
    },
    "credits":  10
}
</code>```

If I wanted to update authordetails.Name using SetPropertyValue, what syntax would I use? The following doesn't seem to work as I'd expect it to:

```<code>//Fetch the Document to be updated
Document doc = client.CreateDocumentQuery<Document>(collectionLink)
                            .Where(r => r.Id == "CDC101")
                            .AsEnumerable()
                            .SingleOrDefault();

//Update some properties on the found resource
doc.SetPropertyValue("authordetails.Name", "Mike");

//Now persist these changes to the database by replacing the original resource
Document updated = await client.ReplaceDocumentAsync(doc);
</code>```

The reason I ask: I have to change a single property on a large number of documents in the collection (new requirement), and I'm trying to process them from a queue on a separate process to avoid the UI timing out. I considered a sproc, but being javascript based, and without a batch upsert like mongo I'm failing to find a suitable & scalable way to do this. I'm new to the NoSQL way of thinking and I'm quite baffled. Any help is appreciated.

答:
SetPropertyValue does not support to set nested properties. You could submit this user voice at Azure feedback forum. At currently, we can query the document as an object then replace the document. Refer to below code:

```<code>var entity = client.CreateDocumentQuery<Cred>(UriFactory.CreateDocumentCollectionUri("<databaseid>", "<collectionid>")).Where(r => r.ID == "CDC101")
                        .AsEnumerable().SingleOrDefault();
entity.AuthInfo.Name = "mike";
await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri("<databaseid>", "<collectionid>", entity.ID), entity);
</code>```

This is my tested class:

```<code>public class Cred
{
    [JsonProperty(PropertyName = "id")]
    public string ID { get; set; }
    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }
    [JsonProperty(PropertyName = "credits")]
    public int Credits { get; set; }
    [JsonProperty(PropertyName = "authordetails")]
    public AuthDetail AuthInfo { get; set; }
}
public class AuthDetail
{
    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName = "Age")]
    public int Age { get; set; }
}
</code>```

We can also use store produce to do this:

```<code>// SAMPLE STORED PROCEDURE
function sample() {
var collection = getContext().getCollection();

// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
    collection.getSelfLink(),
    'SELECT * FROM root r',
    function (err, feed, options) {
        if (err) throw err;

        // Check the feed and if empty, set the body to 'no docs found',
        // else take 1st element from feed
        if (!feed || !feed.length) getContext().getResponse().setBody('no docs found');
        else getContext().getResponse().setBody(JSON.stringify(feed[0]));
        var doc= feed[0];
        doc.authordetails.Name="mike";
        var isAccepted = collection.replaceDocument(feed[0]._self, doc);
    });

if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
</code>```

Body:
Say for a given DocumentDb document such as:

{
    "id": "CDC101",
    "title": "Fundamentals of database design",
    "authordetails": {
       "Name" : "Dave",
       "Age : "33"
    },
    "credits":  10
}

If I wanted to update authordetails.Name using SetPropertyValue, what syntax would I use? The following doesn't seem to work as I'd expect it to:

//Fetch the Document to be updated
Document doc = client.CreateDocumentQuery<Document>(collectionLink)
                            .Where(r => r.Id == "CDC101")
                            .AsEnumerable()
                            .SingleOrDefault();

//Update some properties on the found resource
doc.SetPropertyValue("authordetails.Name", "Mike");

//Now persist these changes to the database by replacing the original resource
Document updated = await client.ReplaceDocumentAsync(doc);

The reason I ask: I have to change a single property on a large number of documents in the collection (new requirement), and I'm trying to process them from a queue on a separate process to avoid the UI timing out. I considered a sproc, but being javascript based, and without a batch upsert like mongo I'm failing to find a suitable & scalable way to do this. I'm new to the NoSQL way of thinking and I'm quite baffled. Any help is appreciated.

Body:
SetPropertyValue does not support to set nested properties. You could submit this user voice at Azure feedback forum. At currently, we can query the document as an object then replace the document. Refer to below code:

var entity = client.CreateDocumentQuery<Cred>(UriFactory.CreateDocumentCollectionUri("<databaseid>", "<collectionid>")).Where(r => r.ID == "CDC101")
                        .AsEnumerable().SingleOrDefault();
entity.AuthInfo.Name = "mike";
await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri("<databaseid>", "<collectionid>", entity.ID), entity);

This is my tested class:

public class Cred
{
    [JsonProperty(PropertyName = "id")]
    public string ID { get; set; }
    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }
    [JsonProperty(PropertyName = "credits")]
    public int Credits { get; set; }
    [JsonProperty(PropertyName = "authordetails")]
    public AuthDetail AuthInfo { get; set; }
}
public class AuthDetail
{
    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName = "Age")]
    public int Age { get; set; }
}

We can also use store produce to do this:

// SAMPLE STORED PROCEDURE
function sample() {
var collection = getContext().getCollection();

// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
    collection.getSelfLink(),
    'SELECT * FROM root r',
    function (err, feed, options) {
        if (err) throw err;

        // Check the feed and if empty, set the body to 'no docs found',
        // else take 1st element from feed
        if (!feed || !feed.length) getContext().getResponse().setBody('no docs found');
        else getContext().getResponse().setBody(JSON.stringify(feed[0]));
        var doc= feed[0];
        doc.authordetails.Name="mike";
        var isAccepted = collection.replaceDocument(feed[0]._self, doc);
    });

if (!isAccepted) throw new Error('The query was not accepted by the server.');
}


问:
pip install web.py but errors modulenotfounderror
use pip to install web.py,but it errors:

```<code>C:\Users\apple>pip install web.py
Collecting web.py
  Downloading web.py-0.38.tar.gz (91kB)
    100% |████████████████████████████████| 92kB 537kB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\apple\AppData\Local\Temp\pip-build-   drp6zgow\web.py\setup.py", line 6, in <module>
    from web import __version__
      File "C:\Users\apple\AppData\Local\Temp\pip-build-drp6zgow\web.py\web\__init__.py", line 14, in <module>
    import utils, db, net, wsgi, http, webapi, httpserver, debugerror
ModuleNotFoundError: No module named 'utils'

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in
C:\Users\apple\AppData\Local\Temp\pip-build-drp6zgow\web.py\
</code>```

Could you give me the reason and the steps, on how to solve it?

答:
Have a try with the following</p>

```<code>pip2 install web.py
</code>```

Body:
use pip to install web.py,but it errors:

C:\Users\apple>pip install web.py
Collecting web.py
  Downloading web.py-0.38.tar.gz (91kB)
    100% |████████████████████████████████| 92kB 537kB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\apple\AppData\Local\Temp\pip-build-   drp6zgow\web.py\setup.py", line 6, in <module>
    from web import __version__
      File "C:\Users\apple\AppData\Local\Temp\pip-build-drp6zgow\web.py\web\__init__.py", line 14, in <module>
    import utils, db, net, wsgi, http, webapi, httpserver, debugerror
ModuleNotFoundError: No module named 'utils'

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in
C:\Users\apple\AppData\Local\Temp\pip-build-drp6zgow\web.py\

Could you give me the reason and the steps, on how to solve it?

Body:
Have a try with the following

pip2 install web.py


问:
React-Native : how show loading screen before list view populated
Here is my code .I am using ComponentwillMount Function for API and then using isLoading variable and accordingly displaying the particular view.But its doesnt work...  its seems to be I done something wrong please took a glance and help me out I am new to react - native

```<code>const UserPage = React.createClass({

    getInitialState() {
        return {
            dataSource: dataSource.cloneWithRows(dataList),
            isLoading:true
        }
    },

    componentWillMount() {

        SharedPreferences.getItem("sender_id", (value) => {
            let user_id = value;
            let url = "BaseURL/fetchSendTokens?user_id="+user_id;
            fetch(url, {
                method: "GET",
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                },
            })
                .then((response) => response.json())
                .then((responseData) => {
                    if (responseData.responsecode === 1) {
                        dataList = responseData.data;
                        this.setState = ({
                            dataSource: this.state.dataSource.cloneWithRows(dataList),
                            isLoading:false,
                        })
                    }
                    else {
                        ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                    }
                })
                .catch(e => {
                    ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                })
                .done();
        });
    },

    renderRow(rowData, sectionID,){

        let  currentView = (rowData.visitor_profileImageUrl)?
            <Image
                source={{uri:rowData.visitor_profileImageUrl}}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/> :
            <Image
                source={userprofilepic}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/>;

        return <View key={ sectionID }>
            <View style={{ flex: 1,height:70,flexDirection: 'row'}}>
                <View>
                    {currentView}
                </View>
                <Text style={{fontSize : 18,marginTop:15,marginLeft:20,color:"black"}} >{ rowData.visitor_name }</Text>
            </View>
        </View>
    },

    render() {
        let loadingGif = "URL-loading.gif";
        let currentView = (this.state.isLoading)?<View style={styles.background}>
                <View style={styles.markWrap}>
                    <Image source={{uri:loadingGif}} style={styles.verifyLogo} resizeMode="contain"/>
                </View>
            </View>:
            <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} enableEmptySections={true}/>;

        return(
            <View>
                {currentView}
            </View>
        );

    },
});
</code>```

答:
```<code>    constructor(props){
       super(props);

       this.state = {
         loading: true,
       }

    }

    render(){
       if (this.props.loading) {
              return (<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}><ActivityIndicator
                animating={states.campaign.loading}
                style={[styles.centering, { height: 80 }]}
                size="large"
              /></View>);
            }else{
              return (<ListView></ListView>);
            }
}
</code>```

Body:
Here is my code .I am using ComponentwillMount Function for API and then using isLoading variable and accordingly displaying the particular view.But its doesnt work...  its seems to be I done something wrong please took a glance and help me out I am new to react - native

const UserPage = React.createClass({

    getInitialState() {
        return {
            dataSource: dataSource.cloneWithRows(dataList),
            isLoading:true
        }
    },

    componentWillMount() {

        SharedPreferences.getItem("sender_id", (value) => {
            let user_id = value;
            let url = "BaseURL/fetchSendTokens?user_id="+user_id;
            fetch(url, {
                method: "GET",
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                },
            })
                .then((response) => response.json())
                .then((responseData) => {
                    if (responseData.responsecode === 1) {
                        dataList = responseData.data;
                        this.setState = ({
                            dataSource: this.state.dataSource.cloneWithRows(dataList),
                            isLoading:false,
                        })
                    }
                    else {
                        ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                    }
                })
                .catch(e => {
                    ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                })
                .done();
        });
    },

    renderRow(rowData, sectionID,){

        let  currentView = (rowData.visitor_profileImageUrl)?
            <Image
                source={{uri:rowData.visitor_profileImageUrl}}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/> :
            <Image
                source={userprofilepic}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/>;

        return <View key={ sectionID }>
            <View style={{ flex: 1,height:70,flexDirection: 'row'}}>
                <View>
                    {currentView}
                </View>
                <Text style={{fontSize : 18,marginTop:15,marginLeft:20,color:"black"}} >{ rowData.visitor_name }</Text>
            </View>
        </View>
    },

    render() {
        let loadingGif = "URL-loading.gif";
        let currentView = (this.state.isLoading)?<View style={styles.background}>
                <View style={styles.markWrap}>
                    <Image source={{uri:loadingGif}} style={styles.verifyLogo} resizeMode="contain"/>
                </View>
            </View>:
            <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} enableEmptySections={true}/>;

        return(
            <View>
                {currentView}
            </View>
        );

    },
});


问:
Checkboxes behave like Radiobutton
I have got 4 checkboxes ad they should act like checkboxes, but they don't.
I just can select one. Can somebody please help me with my problem?

My second question is, is it possible that they are all selected from the beginning?

Thanks!

I think i descriped my question wrong, I can click for example two checkboxes, but then nothing is shown.

Eg.: if i click green and red, then both colors should be shown.

    <input type="checkbox" id="stat1" ng-true-value="'black'" ng-model="statusblack"/>
    black

    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred"/>
    red

    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow"/>
    yellowt

    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen"/>
    green

            Number
            Color
            Info

            {{ co.no }}
            {{ co.color }}
            {{ co.info }}

```

答:
As mentioned, the code does work.

In regards to having it checked by default you need to add checked at the end of the  input tag.

E.g.
<input type="checkbox" id="stat1" ng-true-value="'black'" ng-model="statusblack" checked/>

Refer to W3Schools for more info.

Title: Checkboxes behave like Radiobutton


问:
List of Map.Entry<String,String>
how to convert a list of Map.Entry<String, String> to a String?

```<code>List<Map.Entry<String, String>> : [AREA_DS_ID=1,5,9,13,17,21,25,29,33, PROJECTS_ID=13,78,267,18,28,33,55,99, SIGNAL_NAME=a, ASSESSMENTNAME=a]
// these are the values which I need to convert into String.
</code>```

答:
what's you mean ?? you want to convert map element( key=value) to string value ??? for this, you can use a loop on map entry set and read key and value of map elements and create custom string and concat all list:

```<code>String resultString ="" ;
for(Map.Entry<String,String> entry : map.EntrySet())
{
   String key = entry.getKey();
   String value = entry.getValue();
   // create custom string for each map element
   String testString = key + "=" + value;
   resultString +=  testString ;
}
</code>```

for a list of Map you can define loop on list :

```<code>for(Map<String,String> map : list)
{
  // use map such above code
  ...
}
</code>```

Title: List of Map.Entry<String,String>

Body:
how to convert a list of Map.Entry<String, String> to a String?

List<Map.Entry<String, String>> : [AREA_DS_ID=1,5,9,13,17,21,25,29,33, PROJECTS_ID=13,78,267,18,28,33,55,99, SIGNAL_NAME=a, ASSESSMENTNAME=a]
// these are the values which I need to convert into String.

Body:
what's you mean ?? you want to convert map element( key=value) to string value ??? for this, you can use a loop on map entry set and read key and value of map elements and create custom string and concat all list:

String resultString ="" ;
for(Map.Entry<String,String> entry : map.EntrySet())
{
   String key = entry.getKey();
   String value = entry.getValue();
   // create custom string for each map element
   String testString = key + "=" + value;
   resultString +=  testString ;
}

for a list of Map you can define loop on list :

for(Map<String,String> map : list)
{
  // use map such above code
  ...
}


问:
iOS app rejected - Your app enables the display of nearby users' locations on a map, but does not have the required privacy precautions in place
My iOS app rejected from apple due to following reason :-

Your app enables the display of nearby users' locations on a map, but
  does not have the required privacy precautions in place.

And they are sharing this screenshot of my app with rejection message.

In my app, I am using user’s location for showing near by events on the Map. Also I have enabled option showing user’s location on the Map.

I am using following code for setting up location services into my app.

```<code>//Declarting objects in .h file
CLGeocoder *geocoder;
CLPlacemark *placemark;

@property (nonatomic,retain) CLLocationManager *locationManager;

//Calling this method from viewDidLoad for setup location services..
-(void)getUserCurrentLocation
{
    geocoder = [[CLGeocoder alloc] init];

    self.locationManager=[[CLLocationManager alloc]init];
    self.locationManager.delegate=self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter=kCLDistanceFilterNone;

    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    {
        [_locationManager requestWhenInUseAuthorization];
    }

    [self.locationManager startUpdatingLocation];
}

-(void)StopUpdateLOcation
{
    if([CLLocationManager locationServicesEnabled])
    {
        [self.locationManager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil)
    {

        //Saving location
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.latitude] forKey:@"CurrentLocationLatitude"];
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.longitude] forKey:@"CurrentLocationLongitude"];

       //Here reverseGeocodeLocation method for fetching address from location

        [self StopUpdateLOcation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
}
</code>```

Also I have added property “Privacy - Location When In Use Usage Description” with proper message. Also I have disabled the location service when got the location.

Not sure, why they are rejecting app. Did I miss something.?

How can I resolved this issue.?

Any help would be appreciated.

答:
Finally, Got the proper solution for this. Thanks @Anbu.kartik for helping to findout this solution.

I have enabled the option for showing user’s location on the MAP. but didn’t wrote the failure delegate methods for handling, if user’s location not found.

So I write following delegate methods and send an app for approval again. And the app is approved by apple.

```<code>- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"didFailToLocateUserWithError %@", error.description);
}

- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error{
    NSLog(@"mapViewDidFailLoadingMap %@", error.description);
}
</code>```

So we must have to write failure delegates for handling errors for all the functionalities. So never happens rejection of app related this type of issues.

Hope, this is what you're looking for. Any concern get back to me. :)

Body:
My iOS app rejected from apple due to following reason :-

Your app enables the display of nearby users' locations on a map, but
  does not have the required privacy precautions in place.

And they are sharing this screenshot of my app with rejection message.

In my app, I am using user’s location for showing near by events on the Map. Also I have enabled option showing user’s location on the Map.

I am using following code for setting up location services into my app.

//Declarting objects in .h file
CLGeocoder *geocoder;
CLPlacemark *placemark;

@property (nonatomic,retain) CLLocationManager *locationManager;

//Calling this method from viewDidLoad for setup location services..
-(void)getUserCurrentLocation
{
    geocoder = [[CLGeocoder alloc] init];

    self.locationManager=[[CLLocationManager alloc]init];
    self.locationManager.delegate=self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter=kCLDistanceFilterNone;

    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    {
        [_locationManager requestWhenInUseAuthorization];
    }

    [self.locationManager startUpdatingLocation];
}

-(void)StopUpdateLOcation
{
    if([CLLocationManager locationServicesEnabled])
    {
        [self.locationManager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil)
    {

        //Saving location
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.latitude] forKey:@"CurrentLocationLatitude"];
        [USERDEFAULT setValue:[NSNumber numberWithFloat:currentLocation.coordinate.longitude] forKey:@"CurrentLocationLongitude"];

       //Here reverseGeocodeLocation method for fetching address from location

        [self StopUpdateLOcation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
}

Also I have added property “Privacy - Location When In Use Usage Description” with proper message. Also I have disabled the location service when got the location.

Not sure, why they are rejecting app. Did I miss something.?

How can I resolved this issue.?

Any help would be appreciated.

Body:
Finally, Got the proper solution for this. Thanks @Anbu.kartik for helping to findout this solution.

I have enabled the option for showing user’s location on the MAP. but didn’t wrote the failure delegate methods for handling, if user’s location not found.

So I write following delegate methods and send an app for approval again. And the app is approved by apple.

- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"didFailToLocateUserWithError %@", error.description);
}

- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error{
    NSLog(@"mapViewDidFailLoadingMap %@", error.description);
}

So we must have to write failure delegates for handling errors for all the functionalities. So never happens rejection of app related this type of issues.

Hope, this is what you're looking for. Any concern get back to me. :)


问:
How to implement sql coalesce in pandas
I have a data frame like

```<code>df = pd.DataFrame({"A":[1,2,np.nan],"B":[np.nan,10,np.nan], "C":[5,10,7]})
     A     B   C
0  1.0   NaN   5
1  2.0  10.0  10
2  NaN   NaN   7
</code>```

I want to add a new column 'D'. Expected output is

```<code>     A     B   C    D
0  1.0   NaN   5    1.0
1  2.0  10.0  10    2.0
2  NaN   NaN   7    7.0
</code>```

Thanks in advance!

答:
I think you need bfill with selecting first column by iloc:

```<code>df['D'] = df.bfill(axis=1).iloc[:,0]
print (df)
     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0
</code>```

same as:

```<code>df['D'] = df.fillna(method='bfill',axis=1).iloc[:,0]
print (df)
     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0
</code>```

Title: How to implement sql coalesce in pandas

Body:
I have a data frame like

df = pd.DataFrame({"A":[1,2,np.nan],"B":[np.nan,10,np.nan], "C":[5,10,7]})
     A     B   C
0  1.0   NaN   5
1  2.0  10.0  10
2  NaN   NaN   7

I want to add a new column 'D'. Expected output is

     A     B   C    D
0  1.0   NaN   5    1.0
1  2.0  10.0  10    2.0
2  NaN   NaN   7    7.0

Thanks in advance!

Body:
I think you need bfill with selecting first column by iloc:

df['D'] = df.bfill(axis=1).iloc[:,0]
print (df)
     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0

same as:

df['D'] = df.fillna(method='bfill',axis=1).iloc[:,0]
print (df)
     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0


问:
How can I transload data between two delphi applications over internet?
Hi
let me make my question clear. Two people using my app are connected to the internet. Both have each other's IP and they want to chat (like Y!messanger) with each other.
I think I need to use Indy components; right? Which component should I use?
Thanks in advance</p>

答:
You don't have to use Indy components, you just need anything that will handle communications over the network.  Any HTTP or sockets network stack will do.  Indy is the defacto standard for Delphi Win32.

To do network communications, you will need to create a listener object or service on machine A and a sender object on machine B to send a network message from A to B.  To send a message from B to A, you will need a reverse path as well - 4 objects total to perform bidirectional comms.  Some object wrappers hide this detail internally.  I don't recall offhand whether Indy hides this or not.

It would probably be easiest if you use a common TCP/IP protocol for your machine to machine communications, such as HTTP.  This will make it easier to get your connections through firewalls and proxies that frequently exist between arbitrary users.  To avoid conflicting with any HTTP web services that might be running on either machine, you should use a custom port number with the IP address:  192.168.1.10:12345, not the standard HTTP web server port 80.  This is what most of the IM clients do.

ContentLicense: CC BY-SA 2.5


问:
Modules Error in Prestashop Admin Panel
There is no modules installed line UPS but still getting errors.

Errors:

**Error found : CData section not finished The UPS module can handle the shipping via UPS Ge in must_have_module_list.xml file.

Error found : Premature end of data in tag description line 1 in must_have_module_list.xml file.

Error found : Premature end of data in tag module line 1 in must_have_module_list.xml file.

Error found : Premature end of data in tag modules line 1 in must_have_module_list.xml file.**

答:
The above error occurred in two ways,i.e

Error in while login in admin.
Answer:

a->Rename your own customize module if you have add any others modules.

b->Remove two files i.e(default_country_modules_list.xml, must_have_modules_list.xml) from your  config/xml folder, please make sure backup these two files before removing.

Error in Admin panel in module section. Answer: Only Remove two files i.e(default_country_modules_list.xml, must_have_modules_list.xml) from your  config/xml folder,please make sure backup these two files before removing.

I hope above are help full to you.

Thanks.

Title: Modules Error in Prestashop Admin Panel


问:
How to add and remove active class to anchor tag within li using Jquery/Javascript
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

```<code><ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>
</code>```

My active class is given below.

```<code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}
</code>```

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

答:
$(document).ready(function(){
    $('#ulCategory li a').click(function(){
    $('#ulCategory li a').removeClass("active")
        $(this).toggleClass("active");
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  color: red;
}</code>```

ABC

ABF

ABK

```

Body:
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

ABC

ABF

ABK

My active class is given below.

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

Body:
$(document).ready(function(){
    $('#ulCategory li a').click(function(){
    $('#ulCategory li a').removeClass("active")
        $(this).toggleClass("active");
    });
});

.active {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ulCategory">
<li><a>ABC</a></li>
<li><a>ABF</a></li>
<li><a>ABK</a></li>
</ul>


问:
AWS IOT : Cannot Register with shadow
I have created a thing in AWS IoT called RasberryPi and I am trying to register with its shadow using the following code :

```<code>var awsIot = require('aws-iot-device-sdk');

var thingShadows = awsIot.thingShadow({
   keyPath: "./certs/private.pem.key",
   certPath: "./certs/certificate.pem.crt",
   caPath: "./certs/root-CA.crt",
   clientId: "RasberryPi1",
   region: "eu-west-1",
   port: "8883",
   debug: true
});

thingShadows.on('connect', function() {

    console.log('connected');

    thingShadows.register( 'RasberryPi1', function() {
        console.log('registered');
...
</code>```

I successfully connect but I never register. That is, the second console.log statement never runs. Can anybody please advise on my mistake? I'm very new to AWS IoT and my mistake is probably very basic.

Many thanks

答:
It may be really confusing but it is because of docs. You are probably following examples like here: https://github.com/aws/aws-iot-device-sdk-js#thing-shadow-class

```<code>//
// After connecting to the AWS IoT platform, register interest in the
// Thing Shadow named 'RGBLedLamp'.
//
thingShadows.register( 'RGBLedLamp', function() {
    // Your code here
}
</code>```

but when you read the docs here: https://github.com/aws/aws-iot-device-sdk-js#awsiotthingshadowregisterthingname-options-callback- you can see that the register function takes callback not as second argument but as third(!)

Just call it like this:

```<code> thingShadows.register( 'RGBLedLamp', {}, function() {
    // Your code here
}
</code>```

and it'll work like a charm

Title: AWS IOT : Cannot Register with shadow

Body:
I have created a thing in AWS IoT called RasberryPi and I am trying to register with its shadow using the following code :

var awsIot = require('aws-iot-device-sdk');

var thingShadows = awsIot.thingShadow({
   keyPath: "./certs/private.pem.key",
   certPath: "./certs/certificate.pem.crt",
   caPath: "./certs/root-CA.crt",
   clientId: "RasberryPi1",
   region: "eu-west-1",
   port: "8883",
   debug: true
});

thingShadows.on('connect', function() {

    console.log('connected');

    thingShadows.register( 'RasberryPi1', function() {
        console.log('registered');
...

I successfully connect but I never register. That is, the second console.log statement never runs. Can anybody please advise on my mistake? I'm very new to AWS IoT and my mistake is probably very basic.

Many thanks

Body:
It may be really confusing but it is because of docs. You are probably following examples like here: https://github.com/aws/aws-iot-device-sdk-js#thing-shadow-class

//
// After connecting to the AWS IoT platform, register interest in the
// Thing Shadow named 'RGBLedLamp'.
//
thingShadows.register( 'RGBLedLamp', function() {
    // Your code here
}

but when you read the docs here: https://github.com/aws/aws-iot-device-sdk-js#awsiotthingshadowregisterthingname-options-callback- you can see that the register function takes callback not as second argument but as third(!)

Just call it like this:

 thingShadows.register( 'RGBLedLamp', {}, function() {
    // Your code here
}

and it'll work like a charm


问:
How do I run func applicationDidEnterBackground code only if user locks in swift?
I want to run code when the user is no longer on the app, but only if the way they exited the app is if they locked their phone. I don't want the code to run if they switch apps.</p>

答: I don't believe there's a way to tell if the app entered the background as the result of a lock even or another type of event. I believe Apple doesn't expose this data to developers.</p>


问:
Array pointer outside of main function
Here is another total-beginner-noob question of me: when putting the lines

```<code>double w[1];
double *l;
l = w;
</code>```

into the main() function, everything works perfectly well when compiling, however, when putting it before the main() (as declared variables), then the error

expected ',' or ';' before '=' token

appears for the last line.

Also, putting the former two before main() and only l = w; into the main() will work fine. Why is that so? Does it have something to do with compile/runtime? Can I not assign values outside main() when having them declared before? If so, why?

答:
You can't have freestanding expressions outside of functions in C++.

You can work around this by moving the expression to the initializer of l:

```<code>double w[1];
double *l = w;
</code>```

Title: Array pointer outside of main function

Body:
Here is another total-beginner-noob question of me: when putting the lines

double w[1];
double *l;
l = w;

into the main() function, everything works perfectly well when compiling, however, when putting it before the main() (as declared variables), then the error

expected ',' or ';' before '=' token

appears for the last line.

Also, putting the former two before main() and only l = w; into the main() will work fine. Why is that so? Does it have something to do with compile/runtime? Can I not assign values outside main() when having them declared before? If so, why?

Body:
You can't have freestanding expressions outside of functions in C++.

You can work around this by moving the expression to the initializer of l:

double w[1];
double *l = w;


问:
Icon of the notification is different
I get a push notification from FCM. When my application is minimized or screen is locked, I see a title of notification : Here is your notification and different icon.

How I can change this? This is my code and how I create and display a notification I don't have this:

```<code>private void createNotification( String messageBody) {
    Intent intent = new Intent( this , NotificationActivity. class );
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Wiadomosc z serwera")
            .setContentText(messageBody)
            .setAutoCancel( true )
            .setSound(notificationSoundURI)
            .setContentIntent(resultIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, mNotificationBuilder.build());
}
</code>```

答:
You'll have to use setLargeIcon(Bitmap bitmap) method.

```<code>Bitmap largeIconBitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.launcher_logo);

NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
            .setLargeIcon(largeIconBitmap)
            .setSmallIcon(R.mipmap.ic_launcher)
</code>```

Title: Icon of the notification is different

Body:
I get a push notification from FCM. When my application is minimized or screen is locked, I see a title of notification : Here is your notification and different icon.

How I can change this? This is my code and how I create and display a notification I don't have this:

private void createNotification( String messageBody) {
    Intent intent = new Intent( this , NotificationActivity. class );
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Wiadomosc z serwera")
            .setContentText(messageBody)
            .setAutoCancel( true )
            .setSound(notificationSoundURI)
            .setContentIntent(resultIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, mNotificationBuilder.build());
}

Body:
You'll have to use setLargeIcon(Bitmap bitmap) method.

Bitmap largeIconBitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.launcher_logo);

NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
            .setLargeIcon(largeIconBitmap)
            .setSmallIcon(R.mipmap.ic_launcher)


问:
Reporting Services Line Breaks When Exported Not In HTML
In Reportings Serivces 2005..I have a matrix control with a the below expression in one of the cells. The problem is that all these lines are running together when viewed from the report viewer. It does, however, export in the correct format (pdf, excel). This is a little issue but its drving me nuts. I use the same technique on other reports and they display as expected.

Expression:

```<code>=Fields!FullName.Value + " (" + Fields!Id.Value.ToString() + ") "
+ chr(10) + chr(13)
+ "dob " + Format(Fields!DateOfBirth.Value, "MM/dd/yyyy")
+ chr(10) + chr(13)
+ "Days Enrolled: " + Fields!OriginalDaysEnrolled.Value.ToString()
+ chr(10) + chr(13)
+ "45 Day: " + Fields!ItemStringFor45Day.Value
+ chr(10) + chr(13)
+ "90 Day: " + Fields!NinetyDay.Value.ToString()
+ chr(10) + chr(13)
+ "Current: " + Fields!CurrentDescription.Value
+ chr(10) + chr(13)
+ "Open Follow Ups: " + Fields!FollowUpCount.Value.ToString()
</code>```

Web Appearance (IE7, haven't checked others)

Doe, Johnny (123456) dob 03/30/2009 Days Enrolled: 98 45 Day: V H Deca Dev 90 Day: 18 Month Current: 18 Month Open Follow Ups: 1

Exported Appearance (as expected and as Web should look)

Doe, Johnny (123456)

  dob 03/30/2009

  Days Enrolled: 98

  45 Day: V H Deca Dev

  90 Day: 18 Month

  Current: 18 Month

  Open Follow Ups: 1

答:
I figured this out after checking a report that was working correctly (for the fifth time)...it's simple.

I used:

```<code>+ chr(10) + chr(13)
</code>```

but I should have used:

```<code>+ chr(13) + chr(10)
</code>```

I feel silly for overlooking it for so long, but I guess it never popped out at me.

Body:
In Reportings Serivces 2005..I have a matrix control with a the below expression in one of the cells. The problem is that all these lines are running together when viewed from the report viewer. It does, however, export in the correct format (pdf, excel). This is a little issue but its drving me nuts. I use the same technique on other reports and they display as expected.

Expression:

=Fields!FullName.Value + " (" + Fields!Id.Value.ToString() + ") "
+ chr(10) + chr(13)
+ "dob " + Format(Fields!DateOfBirth.Value, "MM/dd/yyyy")
+ chr(10) + chr(13)
+ "Days Enrolled: " + Fields!OriginalDaysEnrolled.Value.ToString()
+ chr(10) + chr(13)
+ "45 Day: " + Fields!ItemStringFor45Day.Value
+ chr(10) + chr(13)
+ "90 Day: " + Fields!NinetyDay.Value.ToString()
+ chr(10) + chr(13)
+ "Current: " + Fields!CurrentDescription.Value
+ chr(10) + chr(13)
+ "Open Follow Ups: " + Fields!FollowUpCount.Value.ToString()

Web Appearance (IE7, haven't checked others)

Doe, Johnny (123456) dob 03/30/2009 Days Enrolled: 98 45 Day: V H Deca Dev 90 Day: 18 Month Current: 18 Month Open Follow Ups: 1

Exported Appearance (as expected and as Web should look)

Doe, Johnny (123456)

  dob 03/30/2009

  Days Enrolled: 98

  45 Day: V H Deca Dev

  90 Day: 18 Month

  Current: 18 Month

  Open Follow Ups: 1

Body:
I figured this out after checking a report that was working correctly (for the fifth time)...it's simple.

I used:

+ chr(10) + chr(13)

but I should have used:

+ chr(13) + chr(10)

I feel silly for overlooking it for so long, but I guess it never popped out at me.


问:
What is the syntax for an inner join in LINQ to SQL?
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.

How do you represent the following in LINQ to SQL:

```<code>select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
</code>```

答:
```<code>var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName

}).ToList();
</code>```

OwnerDisplayName: Glenn Slaven

Body:
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.

How do you represent the following in LINQ to SQL:

select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID

LastEditorDisplayName: Kevin Fairchild


问:
Standard way of configuring multiple application
We've got many java components running on several machines. Mostly web applications (on tomcat), and some are standalone processes. Historically, each application uses its own way to configure itself: singleton class, or properties file on disk, or application resource file, etc. By configuration I mean String key-value pairs, that affect application behaviour (eg. folder name to store files, or some timeout, and so on).

Question: Is there a standard (desirably simple and reliable) way to configure many applications in one place ?

答:
You could use Redis(distributed key-value store) and write a service to retrieve the configuration entries for the relevant application server there.

Alternatively if you are using Spring Boot
, you can try Spring Cloud Config

If you are using CDI, you can try the DeltaSpike Configuration Mechanism


问:
Autofac Func<T> with InstancePerMatchingLifetimeScope
When evaluating Func<T> where T is registered with InstancePerMatchingLifetimeScope, inside a singleton class, shouldn't it provide the same instance? that is, shouldn't Func<T> be "scope-aware"?

Maybe an example would be better.

I have two class:

```<code>    class MyScoped
    {
        public int Num { get; set; }
    }

    class MySingleton
    {
        readonly Func<MyScoped> scoped;

        public MySingleton(Func<MyScoped> scoped)
        {
            this.scoped = scoped;
        }

        public void Do()
        {
            var scopedObj = scoped();

            Console.WriteLine(scopedObj.Num);
        }
    }
</code>```

Which are registered like this:

```<code>        var builder = new ContainerBuilder();

        builder.RegisterType<MyScoped>().InstancePerMatchingLifetimeScope("MyScope", "root");
        builder.RegisterType<MySingleton>().SingleInstance();

        var container = builder.Build();
</code>```

And I am running the following piece of code:

```<code>        var singleton = container.Resolve<MySingleton>();

        singleton.Do();

        using (var scope = container.BeginLifetimeScope("MyScope"))
        {
            var scoped = scope.Resolve<MyScoped>();

            scoped.Num = 1;

            singleton.Do();
        }
</code>```

I would expect that the first call to Do() would print 0, and the second would print 1.

I had to changed MySingleton to InstancePerDependency so it would work, which is a bad solution for me, because MySingleton can be expensive to create.

What am I missing here?

答:
It seems services registered as single instance are resolved in the context of root scope. It means that your Func<MyScoped> injected to MySingleton would always resolve MyScoped from the root. The following code:

```<code>var singleton = container.Resolve<MySingleton>();
var s = container.Resolve<MyScoped>();

s.Num = 1;

singleton.Do();

using (var scope = container.BeginLifetimeScope("MyScope"))
{
    var scoped = scope.Resolve<MyScoped>();

    scoped.Num = 10;

    singleton.Do();
}
</code>```

would print 1 twice, because var scopedObj = scoped(); in Do() method would resolve MyScoped from root container, not from the scope.

You could achieve what you want by passing required dependency manually into Do() method:

```<code>class MySingleton
{
    public void Do(MyScoped myScoped)
    {
        Console.WriteLine(myScoped.Num);
    }
}

// ...

var singleton = container.Resolve<MySingleton>();
var s = container.Resolve<MyScoped>();

s.Num = 1;

singleton.Do(s);

using (var scope = container.BeginLifetimeScope("MyScope"))
{
    var scoped = scope.Resolve<MyScoped>();

    scoped.Num = 10;

    singleton.Do(scoped);
}
</code>```

It would print 1 and 10 respectively.

Body:
When evaluating Func<T> where T is registered with InstancePerMatchingLifetimeScope, inside a singleton class, shouldn't it provide the same instance? that is, shouldn't Func<T> be "scope-aware"?

Maybe an example would be better.

I have two class:

    class MyScoped
    {
        public int Num { get; set; }
    }

    class MySingleton
    {
        readonly Func<MyScoped> scoped;

        public MySingleton(Func<MyScoped> scoped)
        {
            this.scoped = scoped;
        }

        public void Do()
        {
            var scopedObj = scoped();

            Console.WriteLine(scopedObj.Num);
        }
    }

Which are registered like this:

        var builder = new ContainerBuilder();

        builder.RegisterType<MyScoped>().InstancePerMatchingLifetimeScope("MyScope", "root");
        builder.RegisterType<MySingleton>().SingleInstance();

        var container = builder.Build();

And I am running the following piece of code:

        var singleton = container.Resolve<MySingleton>();

        singleton.Do();

        using (var scope = container.BeginLifetimeScope("MyScope"))
        {
            var scoped = scope.Resolve<MyScoped>();

            scoped.Num = 1;

            singleton.Do();
        }

I would expect that the first call to Do() would print 0, and the second would print 1.

I had to changed MySingleton to InstancePerDependency so it would work, which is a bad solution for me, because MySingleton can be expensive to create.

What am I missing here?

Body:
It seems services registered as single instance are resolved in the context of root scope. It means that your Func<MyScoped> injected to MySingleton would always resolve MyScoped from the root. The following code:

var singleton = container.Resolve<MySingleton>();
var s = container.Resolve<MyScoped>();

s.Num = 1;

singleton.Do();

using (var scope = container.BeginLifetimeScope("MyScope"))
{
    var scoped = scope.Resolve<MyScoped>();

    scoped.Num = 10;

    singleton.Do();
}

would print 1 twice, because var scopedObj = scoped(); in Do() method would resolve MyScoped from root container, not from the scope.

You could achieve what you want by passing required dependency manually into Do() method:

class MySingleton
{
    public void Do(MyScoped myScoped)
    {
        Console.WriteLine(myScoped.Num);
    }
}

// ...

var singleton = container.Resolve<MySingleton>();
var s = container.Resolve<MyScoped>();

s.Num = 1;

singleton.Do(s);

using (var scope = container.BeginLifetimeScope("MyScope"))
{
    var scoped = scope.Resolve<MyScoped>();

    scoped.Num = 10;

    singleton.Do(scoped);
}

It would print 1 and 10 respectively.


问:
React js with react-chart js, does not render doughnut chart
I want to use react-chartjs for my statistics page. So I am currently testing each components of react-chartjs such as bar chart and line chart.

For rendering bar chart and line chart, I made simple datasets and it works fine. However, for doughnut chart, it does not render it.

```<code>import React, {PropTypes}                           from 'react';
import classnames                                   from 'classnames';
import Actions                                      from '../../actions/statistics';
import {Doughnut as DoughnutChart}                  from 'react-chartjs';

export default class Testing extends React.Component {

 render () {
    const data = {
        labels: [
            "Red",
            "Blue",
            "Yellow"
        ],
        datasets: [
            {
                data: [300, 50, 100],
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ]
            }]
       };

    const styles = {
     graphContainer: {
      border: '1px solid black',
      padding: '15px'
     }
    }

    return (
        <div style={styles.graphContainer}>

        <DoughnutChart data={data} />

        </div>

    );
 }
}
</code>```

So to see how it shows on the page, I simply followed example in documentations to render DoughnutChart. In the element inspection tool, it shows that canvas class is rendered, but it does not show the chart...

What am I doing wrong here? Thanks in advance..

答: The problem was from react-chartjs. After I change react-chartjs to react-chartjs-2, it works.

Body:
I want to use react-chartjs for my statistics page. So I am currently testing each components of react-chartjs such as bar chart and line chart.

For rendering bar chart and line chart, I made simple datasets and it works fine. However, for doughnut chart, it does not render it.

import React, {PropTypes}                           from 'react';
import classnames                                   from 'classnames';
import Actions                                      from '../../actions/statistics';
import {Doughnut as DoughnutChart}                  from 'react-chartjs';

export default class Testing extends React.Component {

 render () {
    const data = {
        labels: [
            "Red",
            "Blue",
            "Yellow"
        ],
        datasets: [
            {
                data: [300, 50, 100],
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ]
            }]
       };

    const styles = {
     graphContainer: {
      border: '1px solid black',
      padding: '15px'
     }
    }

    return (

        <DoughnutChart data={data} />

    );
 }
}

So to see how it shows on the page, I simply followed example in documentations to render DoughnutChart. In the element inspection tool, it shows that canvas class is rendered, but it does not show the chart...

What am I doing wrong here? Thanks in advance..


问:
How to test Controller Filters in Ruby on Rails and Test::Unit
We have a large application in Ruby on Rails with many filters.  Some of these filters can be complex.  I am looking for a way to individually test these filters with a unit test.  Right now I test them by testing them through an action that uses them with a functional test.  This just doesn't feel like the right way.

Does anyone have advice or experience with this?

答:
I've come across this issue.

What about filters that perform actions requiring a request.  i.e. using Flash

Example being Authlogic require_user method won't work just by using ApplicationController.new.send(:some_filter).

https://github.com/binarylogic/authlogic_example/blob/master/app/controllers/application_controller.rb

Anyone have some non-hack ideas on how to test this kind of thing in isolation?  (I'm doing it by creating a extra dummy controller that I only use for testing.)

OwnerDisplayName: ScottD


问:
Why are my semaphores allowing out-of-order events within forked processes?
I am trying to make a program that counts from 0 to whatever number is input in the command line in C. In this program, there has to be two fork() calls, making a total of 3 processes. I have to then use a minimum of 1 semaphore to ensure that the processes run in numerical order with each one in charge of a different n % 3.

The issue I am having is that despite the semaphores I'm using, the program seems to run out of order on a fairly regular basis. I am currently using a gate-style system where each process will force it's own designated semaphore to wait, and once finished, sem_post the semaphore of the process that is supposed to run next. I know this is not the prettiest or most logically efficient way of doing this, but it is one that I was pretty sure would work after my first two different attempts that got this same issue.

If anyone can give me any suggestions as to where I have gone so wrong, I would very much appreciate it.

My code is below:

```<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <semaphore.h>
    #include <fcntl.h>

    #define SEM_NAME1 "/sem1.mutex"
    #define SEM_NAME2 "/sem2.mutex"
    #define SEM_NAME3 "/sem3.mutex"

    int main(int argc, char *argv[]) {

        if(argc <= 1){
            printf("No arguments were provided so there is no number to count to");
            return 1;
        }

        // Create the 3 semaphores needed
        sem_t *sem1;
        sem_t *sem2;
        sem_t *sem3;

        //initialize to 0
        sem1 = sem_open(SEM_NAME1, O_CREAT, O_RDWR, 0);
        if (sem1==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME1);
            return (-1);
        }
        //initialize to 1
        sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 1);
        if (sem2==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME2);
            return (-1);
        }
        //initialize to 1
        sem3 = sem_open(SEM_NAME3, O_CREAT, O_RDWR, 1);
        if (sem3==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME3);
            return (-1);
        }

        pid_t pid;
        pid_t pid2;
        pid = fork();

        if(pid == 0){
            pid2 = fork();
        }
        // Shared fork variables
        int counter = 0;
        int ranOnce = 0;
        int max_num = atoi(argv[1]);

        while(counter <= max_num){
            if(pid > 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 1;
                    ranOnce = 1;
                }
                sem_wait(sem2);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem3);
            }
            else if(pid2 == 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 0;
                    ranOnce = 1;
                }
                sem_wait(sem1);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem2);
            }
            else{
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 2;
                    ranOnce = 1;
                }
                sem_wait(sem3);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem1);
            }
        }
        //sem_unlink(SEM_NAME1);
        //sem_unlink(SEM_NAME2);
        //sem_unlink(SEM_NAME3);
        return 0;
    }
</code>```

答:
The semaphore initial values must be the inverse

```<code>sem1 = sem_open(SEM_NAME1, O_CREAT, O_RDWR, 1);
sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 0);
sem3 = sem_open(SEM_NAME3, O_CREAT, O_RDWR, 0);
</code>```

You are currently activate sem2 and sem3 processes at the same time, so they work concurrently, but you need to synchronize them for removing out of ordering events.

Body:
I am trying to make a program that counts from 0 to whatever number is input in the command line in C. In this program, there has to be two fork() calls, making a total of 3 processes. I have to then use a minimum of 1 semaphore to ensure that the processes run in numerical order with each one in charge of a different n % 3.

The issue I am having is that despite the semaphores I'm using, the program seems to run out of order on a fairly regular basis. I am currently using a gate-style system where each process will force it's own designated semaphore to wait, and once finished, sem_post the semaphore of the process that is supposed to run next. I know this is not the prettiest or most logically efficient way of doing this, but it is one that I was pretty sure would work after my first two different attempts that got this same issue.

If anyone can give me any suggestions as to where I have gone so wrong, I would very much appreciate it.

My code is below:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <semaphore.h>
    #include <fcntl.h>

    #define SEM_NAME1 "/sem1.mutex"
    #define SEM_NAME2 "/sem2.mutex"
    #define SEM_NAME3 "/sem3.mutex"

    int main(int argc, char *argv[]) {

        if(argc <= 1){
            printf("No arguments were provided so there is no number to count to");
            return 1;
        }

        // Create the 3 semaphores needed
        sem_t *sem1;
        sem_t *sem2;
        sem_t *sem3;

        //initialize to 0
        sem1 = sem_open(SEM_NAME1, O_CREAT, O_RDWR, 0);
        if (sem1==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME1);
            return (-1);
        }
        //initialize to 1
        sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 1);
        if (sem2==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME2);
            return (-1);
        }
        //initialize to 1
        sem3 = sem_open(SEM_NAME3, O_CREAT, O_RDWR, 1);
        if (sem3==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME3);
            return (-1);
        }

        pid_t pid;
        pid_t pid2;
        pid = fork();

        if(pid == 0){
            pid2 = fork();
        }
        // Shared fork variables
        int counter = 0;
        int ranOnce = 0;
        int max_num = atoi(argv[1]);

        while(counter <= max_num){
            if(pid > 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 1;
                    ranOnce = 1;
                }
                sem_wait(sem2);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem3);
            }
            else if(pid2 == 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 0;
                    ranOnce = 1;
                }
                sem_wait(sem1);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem2);
            }
            else{
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 2;
                    ranOnce = 1;
                }
                sem_wait(sem3);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem1);
            }
        }
        //sem_unlink(SEM_NAME1);
        //sem_unlink(SEM_NAME2);
        //sem_unlink(SEM_NAME3);
        return 0;
    }

Body:
The semaphore initial values must be the inverse

sem1 = sem_open(SEM_NAME1, O_CREAT, O_RDWR, 1);
sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 0);
sem3 = sem_open(SEM_NAME3, O_CREAT, O_RDWR, 0);

You are currently activate sem2 and sem3 processes at the same time, so they work concurrently, but you need to synchronize them for removing out of ordering events.


问:
Could not use lazy variable inside NSCoding protocol methods
I ran into an issue where I could not use a lazy variable inside init?(coder aDecoder: NSCoder)

My sample code is

```<code>class Category: NSObject, NSCoding {
    var categoryID: NSInteger!
    var categoryName: String!
    var categoryLogoURL: String!
    lazy var categoryTags = [String]()
    private override init() {

    }

required init?(coder aDecoder: NSCoder) {
        self.categoryID = aDecoder.decodeInteger(forKey: "categoryID")
        self.categoryName = aDecoder.decodeObject(forKey: "categoryName") as! String
        self.categoryLogoURL = aDecoder.decodeObject(forKey: "categoryLogoURL") as! String
        self.categoryTags = aDecoder.decodeObject(forKey: "categoryTags") as! [String]
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.categoryID, forKey: "categoryID")
        aCoder.encode(categoryName, forKey: "categoryName")
        aCoder.encode(categoryLogoURL, forKey: "categoryLogoURL")
        aCoder.encode(categoryTags, forKey: "categoryTags")
    }
}
</code>```

I am getting an error Use of 'self' in property access 'categoryTags' before super.init initializes self

Once I remove lazy everything works fine. What I am doing wrong?

答:
call Super Init:</p>

```<code>required init?(coder aDecoder: NSCoder) {
    super.init()
    self.categoryID = aDecoder.decodeInteger(forKey: "categoryID")
    self.categoryName = aDecoder.decodeObject(forKey: "categoryName") as! String
    self.categoryLogoURL = aDecoder.decodeObject(forKey: "categoryLogoURL") as! String
    self.categoryTags = aDecoder.decodeObject(forKey: "categoryTags") as! [String]
}
</code>```

Body:
I ran into an issue where I could not use a lazy variable inside init?(coder aDecoder: NSCoder)

My sample code is

class Category: NSObject, NSCoding {
    var categoryID: NSInteger!
    var categoryName: String!
    var categoryLogoURL: String!
    lazy var categoryTags = [String]()
    private override init() {

    }

required init?(coder aDecoder: NSCoder) {
        self.categoryID = aDecoder.decodeInteger(forKey: "categoryID")
        self.categoryName = aDecoder.decodeObject(forKey: "categoryName") as! String
        self.categoryLogoURL = aDecoder.decodeObject(forKey: "categoryLogoURL") as! String
        self.categoryTags = aDecoder.decodeObject(forKey: "categoryTags") as! [String]
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.categoryID, forKey: "categoryID")
        aCoder.encode(categoryName, forKey: "categoryName")
        aCoder.encode(categoryLogoURL, forKey: "categoryLogoURL")
        aCoder.encode(categoryTags, forKey: "categoryTags")
    }
}

I am getting an error Use of 'self' in property access 'categoryTags' before super.init initializes self

Once I remove lazy everything works fine. What I am doing wrong?

Body:
call Super Init:

required init?(coder aDecoder: NSCoder) {
    super.init()
    self.categoryID = aDecoder.decodeInteger(forKey: "categoryID")
    self.categoryName = aDecoder.decodeObject(forKey: "categoryName") as! String
    self.categoryLogoURL = aDecoder.decodeObject(forKey: "categoryLogoURL") as! String
    self.categoryTags = aDecoder.decodeObject(forKey: "categoryTags") as! [String]
}


问:
Splash Screen image background in LinearLayout not fit
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>
</code>```

答:
Firstly check the image my_image_background has any white spaces on the sides .if not , your code works...else u can try this code too

```<code> <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout         xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/activity_splash"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.myproject.SplashActivity"
            android:orientation="vertical"
            android:layout_alignParentRight="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:background="@drawable/my_image_background">

        </RelativeLayout>
</code>```

Check out this too:::
Showing Splash screen in android apps

Body:
I used an image as a background of LinearLayout in splash screen activity but it show not fit for the screen. I don't know how to use attribute for it to stretching it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myproject.SplashActivity"
    android:orientation="horizontal"
    android:background="@drawable/my_image_background">

</LinearLayout>

Body:
Firstly check the image my_image_background has any white spaces on the sides .if not , your code works...else u can try this code too

 <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout         xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/activity_splash"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.myproject.SplashActivity"
            android:orientation="vertical"
            android:layout_alignParentRight="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:background="@drawable/my_image_background">

        </RelativeLayout>

Check out this too:::
Showing Splash screen in android apps


问:
How do I parse HTML in Rails?
I have a string with html tags in it saved.

```<code>=> "<p>hey man this is crazy g funk</p>\n<p>here i come with another crazy message from..</p>\n<p>dj eassssy d!@#!.</p>"
</code>```

How do you parse this so that it displays the way the HTML tags are implying?

I tried:

```<code>= Post.text
=h Post.text
= RedCloth.new(Post.text).to_html
= Hpricot(Post.text)
</code>```

答: Generally one parses html with html parsers. What do you mean "so that it displays the way the HTML tags are implying"? Displays on what? Presumably not a web browser..</p>

Title: How do I parse HTML in Rails?

Body:
I have a string with html tags in it saved.

=> "
hey man this is crazy g funk
\n
here i come with another crazy message from..
\n
dj eassssy d!@#!.
"

How do you parse this so that it displays the way the HTML tags are implying?

I tried:

= Post.text
=h Post.text
= RedCloth.new(Post.text).to_html
= Hpricot(Post.text)


问:
How to scroll collectionview horizontal?
I'm using camera and gallery to take image and add it to collection view, i want to add image to collection view to horizontal direction only so i add image to array and change collection frame to increase collection view width increase, but collection is not scroll to horizontal as i increase height of it, so what is way to do it?

Here is my code :

```<code>UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[arrayPictures addObject:image];
_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, arrayPictures.count*76, 76);
[_collPic reloadData];
</code>```

答:
```<code>UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init ];
layout.minimumInteritemSpacing = 5;
layout.minimumLineSpacing = 6;
layout.itemSize = CGSizeMake(55, 55);
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
</code>```

<hr>

```<code>blendEffectCollectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 95, 320, 60) collectionViewLayout:layout];
[blendEffectCollectionView setDataSource:self];
[blendEffectCollectionView setDelegate:self];

[blendEffectCollectionView registerClass:[BlendModeCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[blendEffectCollectionView setBackgroundColor:[UIColor clearColor]];

[self.view addSubview:blendEffectCollectionView];
</code>```

Body:
I'm using camera and gallery to take image and add it to collection view, i want to add image to collection view to horizontal direction only so i add image to array and change collection frame to increase collection view width increase, but collection is not scroll to horizontal as i increase height of it, so what is way to do it?

Here is my code :

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[arrayPictures addObject:image];
_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, arrayPictures.count*76, 76);
[_collPic reloadData];

Body:
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init ];
layout.minimumInteritemSpacing = 5;
layout.minimumLineSpacing = 6;
layout.itemSize = CGSizeMake(55, 55);
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

blendEffectCollectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 95, 320, 60) collectionViewLayout:layout];
[blendEffectCollectionView setDataSource:self];
[blendEffectCollectionView setDelegate:self];

[blendEffectCollectionView registerClass:[BlendModeCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[blendEffectCollectionView setBackgroundColor:[UIColor clearColor]];

[self.view addSubview:blendEffectCollectionView];


问:
Close modal on AJAX Sucess(ASP.NET MVC)
I have Modal in view for making new record in Database.

View for it in Partial View

Here is code of view

```<code><script src="~/Scripts/jquery-3.1.1.js"></script>
</code>```

For AJAX I using this code

```<code><script>
   $(document).ready(function () {
       $('#save_quest').click(function () {
        savequestion();
    });
});
    function savequestion() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                Question_new: $('#question').val(),
                Answer: $('#answer').val(),
                Preparing: $('#prepare').val(),
                Retries: $('#retries').val(),
                  },
            url: '@Url.Action("CreateNewQuestion", "Questions")',
            success: function (da) {
                if (da.Result === "Success") {
                    $('#myModal').modal('hide')
                    //window.location.href = da.RedirectUrl;

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</code>```

I need to hide modal when AJAX call is Successful

I try this $('#myModal').modal('hide')

Here is my modal on Primary View

```<code><div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
<div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
            @Html.Partial("~/Views/Questions/CreateQuestion.cshtml")
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>

</div>
</code>```

How I can hide it on AJAX Success?

答:
This is not the proper way.
        $('#myModal').hide();

The proper way
     $("#myModal").modal('hide');

Have you try adding bootstrap.js in your page? if not please include it in your page and then test. It should work.

Title: Close modal on AJAX Sucess(ASP.NET MVC)

Body:
I have Modal in view for making new record in Database.

View for it in Partial View

Here is code of view

For AJAX I using this code


问:
How to implement sql coalesce in pandas
I have a data frame like

```<code>df = pd.DataFrame({"A":[1,2,np.nan],"B":[np.nan,10,np.nan], "C":[5,10,7]})
     A     B   C
0  1.0   NaN   5
1  2.0  10.0  10
2  NaN   NaN   7
</code>```

I want to add a new column 'D'. Expected output is

```<code>     A     B   C    D
0  1.0   NaN   5    1.0
1  2.0  10.0  10    2.0
2  NaN   NaN   7    7.0
</code>```

Thanks in advance!

答:
option 1

pandas

```<code>df.assign(D=df.lookup(df.index, df.isnull().idxmin(1)))

     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0
</code>```

option 2

numpy

```<code>v = df.values
j = np.isnan(v).argmin(1)
df.assign(D=v[np.arange(len(v)), j])

     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0
</code>```

naive time test

over given data

over larger data

Title: How to implement sql coalesce in pandas

Body:
I have a data frame like

df = pd.DataFrame({"A":[1,2,np.nan],"B":[np.nan,10,np.nan], "C":[5,10,7]})
     A     B   C
0  1.0   NaN   5
1  2.0  10.0  10
2  NaN   NaN   7

I want to add a new column 'D'. Expected output is

     A     B   C    D
0  1.0   NaN   5    1.0
1  2.0  10.0  10    2.0
2  NaN   NaN   7    7.0

Thanks in advance!

Body:
option 1

pandas

df.assign(D=df.lookup(df.index, df.isnull().idxmin(1)))

     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0

option 2

numpy

v = df.values
j = np.isnan(v).argmin(1)
df.assign(D=v[np.arange(len(v)), j])

     A     B   C    D
0  1.0   NaN   5  1.0
1  2.0  10.0  10  2.0
2  NaN   NaN   7  7.0

naive time test

over given data

over larger data


问:
What are the matlab equivalent for '\n' '\t' and other escape characters?
I am reading a file using fileread() which returns me the entire file. Now I need to read line by line and convert them into process the data. Can I know how I would be able to detect the newline character in Matlab? I tried '\n' and '\r\n' and it doesn't work.

Thanks in advance

答:
I already replied here (please avoid posting the question twice)Escape characters in Matlab

For special acharacters either use the char function with the character code (http://www.asciitable.com/) or sprintf (my preferred way for better readability. For example you are looking for sprintf('\n') or sprintf('\r\n')

char(13) is carriage return \r char(10) is new line \n


问:
Spark Dataframe UDAF issue
Error while decoding:

```<code>java.util.concurrent.ExecutionException: java.lang.Exception: failed to
compile: org.codehaus.commons.compiler.CompileException: File
'generated.java', Line 58, Column 33: Incompatible expression types "boolean"
and "java.lang.Boolean"
</code>```

Find code over here  issues.apache.org/jira/browse/SPARK-20176

答:
Please post code details here and steps to replicate the issue.

And also make sure that spark and scala version are correct in your project.

Example:

scala.version : 2.11.5

scala.compat.version : 2.11

spark.version : 2.1.0

Title: Spark Dataframe UDAF issue

Body:
Error while decoding:

java.util.concurrent.ExecutionException: java.lang.Exception: failed to
compile: org.codehaus.commons.compiler.CompileException: File
'generated.java', Line 58, Column 33: Incompatible expression types "boolean"
and "java.lang.Boolean"

Find code over here  issues.apache.org/jira/browse/SPARK-20176


答:
You are setting the width based on the number of the pictures. It should be set to a reasonable value.

Try

```<code>_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, self.view.frame.width, 76);
</code>```

And set the scrooll direction of collection view to horizontal.

Title: How to scroll collectionview horizontal?

Body:
You are setting the width based on the number of the pictures. It should be set to a reasonable value.

Try

_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, self.view.frame.width, 76);

And set the scrooll direction of collection view to horizontal.


问:
Speed of different data structures in Python
I have a piece of code I need to run, however, it is taking so long. I estimate it will take a minimum of 2 hours to run and at most 100 hours. As you can see, I would like to speed this up.

My code is as follows:

```<code>#B1
file = open("/home/1015097/Downloads/B1/tour5.txt", "r").readlines()
# This is a very large file. You can find it on http://codemasters.eng.unimelb.edu.au/bit_problems/B1.zip
# It is named tour5.txt, you can also find the question I am trying to solve there.
racers = [int(file[0].split()[0]) / float(x) for x in file[0].split()[1::]]
print("hi")
def av(race):
    race = race.split()
    j = 0
    while j != len([float(race[0]) / float(x) for x in race[1::]]):
        racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
        j += 1
        print(j)
    print("yay...")
for i in range(1, len(file)):
    print("yay")
    av(file[i])
print("yaaay")
a = min(racers)
del(racers[racers.index(min(racers))])
b = min(racers)
c = b-a
h = int(c)
c-=h

m = int(c * 60)
c-=m/60
s = round(c * 60 * 60)
print(str(h) + "h" + str(m) + "m" + str(s) + "s")
</code>```

We are currently coming first in Australia for the Code Bits contest and would not like to drop our perfect score. The random print statements were so that we could tell if the code was actually running, they are essentially checkpoints. the number that is printed out is the racer number, there are at least 3000 racers, we do not know exactly.

答:
I think you should be looking at numpy arrays instead of lists. Thereby you can avoid the loops and obtain close to c -speed. This problem is easily applicable to that. And by the way why not store anything in float64 or float32 so there is no conversion of datatypes. Code example not fully portable. It is a schoolwork and I should not do it for you:</p>

```<code>import numpy as np
racer=np.array(racer) # Will work for 1 d lists and for 2-d lists with same lenght
racer_time=racer/time # diving a vector by a scalar is easy
</code>```

Body:
I have a piece of code I need to run, however, it is taking so long. I estimate it will take a minimum of 2 hours to run and at most 100 hours. As you can see, I would like to speed this up.

My code is as follows:

#B1
file = open("/home/1015097/Downloads/B1/tour5.txt", "r").readlines()
# This is a very large file. You can find it on http://codemasters.eng.unimelb.edu.au/bit_problems/B1.zip
# It is named tour5.txt, you can also find the question I am trying to solve there.
racers = [int(file[0].split()[0]) / float(x) for x in file[0].split()[1::]]
print("hi")
def av(race):
    race = race.split()
    j = 0
    while j != len([float(race[0]) / float(x) for x in race[1::]]):
        racers[j] = [float(race[0]) / float(x) for x in race[1::]][j] + racers[j]
        j += 1
        print(j)
    print("yay...")
for i in range(1, len(file)):
    print("yay")
    av(file[i])
print("yaaay")
a = min(racers)
del(racers[racers.index(min(racers))])
b = min(racers)
c = b-a
h = int(c)
c-=h

m = int(c * 60)
c-=m/60
s = round(c * 60 * 60)
print(str(h) + "h" + str(m) + "m" + str(s) + "s")

We are currently coming first in Australia for the Code Bits contest and would not like to drop our perfect score. The random print statements were so that we could tell if the code was actually running, they are essentially checkpoints. the number that is printed out is the racer number, there are at least 3000 racers, we do not know exactly.

Body:
I think you should be looking at numpy arrays instead of lists. Thereby you can avoid the loops and obtain close to c -speed. This problem is easily applicable to that. And by the way why not store anything in float64 or float32 so there is no conversion of datatypes. Code example not fully portable. It is a schoolwork and I should not do it for you:

import numpy as np
racer=np.array(racer) # Will work for 1 d lists and for 2-d lists with same lenght
racer_time=racer/time # diving a vector by a scalar is easy


问:
Bullet - Rigid bodies not colliding at high speed?
I'm trying to make a basic first person shooter game with Bullet and OpenGL. I'm having the issue of my rigid bodies not colliding at high speed.

My bullets will go straight through any other rigid bodies that I have, such as walls. Reducing velocity to less than 10 does result in collisions, but this is too low for a moving bullet. The bullet also moves insanely fast (I know it's a fast moving bullet, but sometimes I can't even see it, not sure if that's expected).

I'm thinking that it's to do with how I'm stepping the simulation? Reading up on it has left me confused. How can I make it so that my objects will always collide (at least, when going reasonably fast), and if possible, is there a way to slow the simulation down whilst maintaining the correct bullet velocity etc. so that I can actually see the bullet moving and colliding?

答:
Here are some approaches to solve:-

It is copied from How can I avoid missing collisions for fast moving objects? - an official FAQ

smaller timesteps

extruding the object along the motion

ray cast to the new position

swept collision test (convex cast, linear cast)

continuous collision detection, including rotational motion

Please read the link for more detail.     It is not a trivial issue.

One important thing to ask before try anything: do you really need high speed object?

It is not free (cost more CPU).

Here is another useful link (less useful though) : https://gamedev.stackexchange.com/questions/11961/how-can-i-enable-ccd-in-bullet-physics


问:
best way to add an xml element around xml or a row-by-row basis
On SQL Server 2012 (SP1), what's the best way to take data that looks like this:

```<code>declare @t table (
  id int,
  data xml
)

insert into @t values (1, '<node/>'), (2, '<node/>')

id  data
1   <node />
2   <node />
</code>```

and turn it into

```<code>id  data
1   <root><node /></root>
2   <root><node /></root>
</code>```

?

Is there a way that's more efficient than just converting it to character data, adding the node start and end tag and then converting it back to xml? I'm dealing with this issue on larger data sets, so this is just a simple example.

答:
One more approach (but my favorite was har07's answer)</p>

```<code>declare @t table (
  id int,
  data xml
)

insert into @t values (1, '<node/>'), (2, '<node/>');

SELECT id
      ,(SELECT data AS [*] FOR XML PATH('root'),TYPE)
FROM @t;
</code>```

Body:
On SQL Server 2012 (SP1), what's the best way to take data that looks like this:

declare @t table (
  id int,
  data xml
)

insert into @t values (1, '<node/>'), (2, '<node/>')

id  data
1   <node />
2   <node />

and turn it into

id  data
1   <root><node /></root>
2   <root><node /></root>

?

Is there a way that's more efficient than just converting it to character data, adding the node start and end tag and then converting it back to xml? I'm dealing with this issue on larger data sets, so this is just a simple example.

Body:
One more approach (but my favorite was har07's answer)

declare @t table (
  id int,
  data xml
)

insert into @t values (1, '<node/>'), (2, '<node/>');

SELECT id
      ,(SELECT data AS [*] FOR XML PATH('root'),TYPE)
FROM @t;


问:
Checkboxes behave like Radiobutton
I have got 4 checkboxes ad they should act like checkboxes, but they don't.
I just can select one. Can somebody please help me with my problem?

My second question is, is it possible that they are all selected from the beginning?

Thanks!

I think i descriped my question wrong, I can click for example two checkboxes, but then nothing is shown.

Eg.: if i click green and red, then both colors should be shown.

    <input type="checkbox" id="stat1" ng-true-value="'black'" ng-model="statusblack"/>
    black

    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred"/>
    red

    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow"/>
    yellowt

    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen"/>
    green

            Number
            Color
            Info

            {{ co.no }}
            {{ co.color }}
            {{ co.info }}

```

答:
Add checked in input tag

    <input type="checkbox" id="stat1" ng-true-value="'black'" ng-model="statusblack"/>
    black

    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred"/>
    red

    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow"/>
    yellowt

    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen" checked/>
    green

            Number
            Color
            Info

            {{ co.no }}
            {{ co.color }}
            {{ co.info }}

```

Title: Checkboxes behave like Radiobutton

Body:
Add checked in input tag

<div class="form-group">
    <input type="checkbox" id="stat1" ng-true-value="'black'" ng-model="statusblack"/>&nbsp;
    <label for="stat1">black</label><br />
    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred"/>&nbsp;
    <label for="stat2">red</label><br />
    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow"/>&nbsp;
    <label for="stat3">yellowt</label><br />
    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen" checked/>&nbsp;
    <label for="stat4">green</label><br />
</div>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Number</th>
            <th>Color</th>
            <th>Info</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="co in $ctrl.colors | filter:statusred | filter:statusblack | filter:statusgreen | filter:statusyellow">
            <td>{{ co.no }}</td>
            <td>{{ co.color }}</td>
            <td>{{ co.info }}</td>
        </tr>
    </tbody>
  </table>