问:
Using CompletableFuture with @Async returns an empty response for spring boot API
Here is my controller. I used postman to test if it's working but I am getting an empty response. I used @EnableAsync in application configuration and @Async on the service. If I remove @Async on service layer it works but it doesn't run asynchronously.

```<code>@ApiOperation(value = "search person by passing search criteria event/title/role/host/is_current", response = ElasticSearchResultData.class)
@RequestMapping(value = "/async2/searchPerson", produces = "application/json", method = RequestMethod.POST)
public @ResponseBody CompletableFuture<ElasticSearchResultData> searchPersonAsync2(@RequestBody SearchCriteriaTo criteriaForDivNetFolderTo,
        HttpServletRequest request, HttpServletResponse response){
    LOGGER.info("searchPerson controller start");
    SearchCriteria searchCriteria = criteriaForDivNetFolderTo.getSearchCriteria();
    if (Util.isNull(searchCriteria))
        throw new IllegalArgumentException("search criteria should not be null.");

    try {
        CompletableFuture<ElasticSearchResultData> searchPerson = cubService.searchPersonAsync2(criteriaForDivNetFolderTo);
        ObjectMapper mapper = new ObjectMapper();
        LOGGER.info("search Person "+mapper.writeValueAsString(searchPerson));
        return searchPerson;
    } catch (Exception e) {
        LOGGER.error("Exception in searchPersonAsync controller "+e.getMessage());
    }
    return null;
}
</code>```

Service

```<code>@Async
@Override
public CompletableFuture<ElasticSearchResultData> searchPersonAsync2(SearchCriteriaTo searchCriteriaForDivNetFolderTo) {
   Long start = System.currentTimeMillis();
   LOGGER.info(":in searchPerson");
   CompletableFuture<ElasticSearchResultData> completableFuture = new CompletableFuture<>();
   ElasticSearchResultData searchResultData = null;
   SearchCriteria searchCriteria = searchCriteriaForDivNetFolderTo.getSearchCriteria();
   try {
        LOGGER.info("************ Started searchPerson by criteria ************");
        StringBuilder url = new StringBuilder();
        url.append(equilarSearchEngineApiUrl)
        .append(focusCompanySearchUrl)
        .append("/")
        .append("searchPerson")
        .append("?view=").append(VIEW_ALL)
        .append("&isProcessing=true");

        LOGGER.debug("Calling equilar search engine for focused company search, URL : " + url);
        LOGGER.info(searchCriteria.toString());
        String output = null;
        if (redisEnable != null && redisEnable) {
            output = cacheDao.getDataFromRestApi(url.toString(), RequestMethod.POST.name(), searchCriteria);
        } else {
            output = Util.getDataFromRestApi(url.toString(), RequestMethod.POST.name(), searchCriteria);
        }
        if (!Util.isEmptyString(output)) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            searchResultData = objectMapper.readValue(output,
                            objectMapper.getTypeFactory().constructType(ElasticSearchResultData.class));
        }
        List<PersonSearchDetails> newPersonDetails = new ArrayList<PersonSearchDetails>();
        if (!Util.isNull(searchResultData) && !Util.isNullOrEmptyCollection(searchResultData.getPersonDetails())
                && !Util.isNullOrEmptyCollection(searchCriteriaForDivNetFolderTo.getNetworkFoldersData())) {
            for (PersonSearchDetails personDetail : searchResultData.getPersonDetails()) {
                String logoUrl = null;
                if(!Util.isNull(searchCriteria.getTargetFolderId())){
                    List<DiversityNetworkFolderTo> filteredFolderTos = searchCriteriaForDivNetFolderTo
                            .getNetworkFoldersData()
                            .stream()
                            .filter(folder -> folder.getId()
                            .longValue() == searchCriteria
                            .getTargetFolderId())
                            .collect(Collectors.toList());
                    logoUrl = getLogoUrl(personDetail.getPersonId(),
                            filteredFolderTos);
                } else {
                    logoUrl = getLogoUrl(personDetail.getPersonId(),
                            searchCriteriaForDivNetFolderTo.getNetworkFoldersData());
                }
                personDetail.setLogoUrl(logoUrl);
                newPersonDetails.add(personDetail);
            }
            searchResultData.setPersonDetails(newPersonDetails);
        }
        completableFuture.complete(searchResultData);
        return completableFuture;
    } catch (Exception e) {
        completableFuture.completeExceptionally(e);
        LOGGER.error(
                " ************** Error in proccessing searchPerson by criteria ************** " + e.getMessage());
    }
    Long end = System.currentTimeMillis();
    LOGGER.info(TIME_DURATION+(end - start)+"ms");
    return null;
}
</code>```

答:
It would be good to read more about async processing. javadocs are usually a great start!

If you really want to get the result from a Future method, you need to wait for it.

There is a method public T get() method in the CompletableFuture API to wait for wait for the result to be created and return the result once it's done.

If your job is to search a database for the result and then return it - you will still have to wait for it async is not much help in here. It would help you if you had to make multiple things at the same time, e.g. a call to DB, a web service and something else at the same time, then you can create an array of futures and wait for all of them to complete.

Or, let's say you're creating a POST method, so you can quickly validate the input and send to store to DB async while quickly returning the response to UI and hoping that your async method will be completed in another thread and not returning any errors to UI.

This is a great technique when you know what you're doing, but think if & when you really need it before using it.

The short way to "fix" this is:

```<code>CompletableFuture<ElasticSearchResultData> searchPerson = cubService.searchPersonAsync2(criteriaForDivNetFolderTo);
ElasticSearchResultData result = searchPerson.get();
ObjectMapper mapper = new ObjectMapper();
LOGGER.info("search Person "+mapper.writeValueAsString(result));
return result;
</code>```

( and obviously change the method return signature )

Body:
Here is my controller. I used postman to test if it's working but I am getting an empty response. I used @EnableAsync in application configuration and @Async on the service. If I remove @Async on service layer it works but it doesn't run asynchronously.

@ApiOperation(value = "search person by passing search criteria event/title/role/host/is_current", response = ElasticSearchResultData.class)
@RequestMapping(value = "/async2/searchPerson", produces = "application/json", method = RequestMethod.POST)
public @ResponseBody CompletableFuture<ElasticSearchResultData> searchPersonAsync2(@RequestBody SearchCriteriaTo criteriaForDivNetFolderTo,
        HttpServletRequest request, HttpServletResponse response){
    LOGGER.info("searchPerson controller start");
    SearchCriteria searchCriteria = criteriaForDivNetFolderTo.getSearchCriteria();
    if (Util.isNull(searchCriteria))
        throw new IllegalArgumentException("search criteria should not be null.");

    try {
        CompletableFuture<ElasticSearchResultData> searchPerson = cubService.searchPersonAsync2(criteriaForDivNetFolderTo);
        ObjectMapper mapper = new ObjectMapper();
        LOGGER.info("search Person "+mapper.writeValueAsString(searchPerson));
        return searchPerson;
    } catch (Exception e) {
        LOGGER.error("Exception in searchPersonAsync controller "+e.getMessage());
    }
    return null;
}

Service

@Async
@Override
public CompletableFuture<ElasticSearchResultData> searchPersonAsync2(SearchCriteriaTo searchCriteriaForDivNetFolderTo) {
   Long start = System.currentTimeMillis();
   LOGGER.info(":in searchPerson");
   CompletableFuture<ElasticSearchResultData> completableFuture = new CompletableFuture<>();
   ElasticSearchResultData searchResultData = null;
   SearchCriteria searchCriteria = searchCriteriaForDivNetFolderTo.getSearchCriteria();
   try {
        LOGGER.info("************ Started searchPerson by criteria ************");
        StringBuilder url = new StringBuilder();
        url.append(equilarSearchEngineApiUrl)
        .append(focusCompanySearchUrl)
        .append("/")
        .append("searchPerson")
        .append("?view=").append(VIEW_ALL)
        .append("&isProcessing=true");

        LOGGER.debug("Calling equilar search engine for focused company search, URL : " + url);
        LOGGER.info(searchCriteria.toString());
        String output = null;
        if (redisEnable != null && redisEnable) {
            output = cacheDao.getDataFromRestApi(url.toString(), RequestMethod.POST.name(), searchCriteria);
        } else {
            output = Util.getDataFromRestApi(url.toString(), RequestMethod.POST.name(), searchCriteria);
        }
        if (!Util.isEmptyString(output)) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            searchResultData = objectMapper.readValue(output,
                            objectMapper.getTypeFactory().constructType(ElasticSearchResultData.class));
        }
        List<PersonSearchDetails> newPersonDetails = new ArrayList<PersonSearchDetails>();
        if (!Util.isNull(searchResultData) && !Util.isNullOrEmptyCollection(searchResultData.getPersonDetails())
                && !Util.isNullOrEmptyCollection(searchCriteriaForDivNetFolderTo.getNetworkFoldersData())) {
            for (PersonSearchDetails personDetail : searchResultData.getPersonDetails()) {
                String logoUrl = null;
                if(!Util.isNull(searchCriteria.getTargetFolderId())){
                    List<DiversityNetworkFolderTo> filteredFolderTos = searchCriteriaForDivNetFolderTo
                            .getNetworkFoldersData()
                            .stream()
                            .filter(folder -> folder.getId()
                            .longValue() == searchCriteria
                            .getTargetFolderId())
                            .collect(Collectors.toList());
                    logoUrl = getLogoUrl(personDetail.getPersonId(),
                            filteredFolderTos);
                } else {
                    logoUrl = getLogoUrl(personDetail.getPersonId(),
                            searchCriteriaForDivNetFolderTo.getNetworkFoldersData());
                }
                personDetail.setLogoUrl(logoUrl);
                newPersonDetails.add(personDetail);
            }
            searchResultData.setPersonDetails(newPersonDetails);
        }
        completableFuture.complete(searchResultData);
        return completableFuture;
    } catch (Exception e) {
        completableFuture.completeExceptionally(e);
        LOGGER.error(
                " ************** Error in proccessing searchPerson by criteria ************** " + e.getMessage());
    }
    Long end = System.currentTimeMillis();
    LOGGER.info(TIME_DURATION+(end - start)+"ms");
    return null;
}

Body:
It would be good to read more about async processing. javadocs are usually a great start!

If you really want to get the result from a Future method, you need to wait for it.

There is a method public T get() method in the CompletableFuture API to wait for wait for the result to be created and return the result once it's done.

If your job is to search a database for the result and then return it - you will still have to wait for it async is not much help in here. It would help you if you had to make multiple things at the same time, e.g. a call to DB, a web service and something else at the same time, then you can create an array of futures and wait for all of them to complete.

Or, let's say you're creating a POST method, so you can quickly validate the input and send to store to DB async while quickly returning the response to UI and hoping that your async method will be completed in another thread and not returning any errors to UI.

This is a great technique when you know what you're doing, but think if & when you really need it before using it.

The short way to "fix" this is:

CompletableFuture<ElasticSearchResultData> searchPerson = cubService.searchPersonAsync2(criteriaForDivNetFolderTo);
ElasticSearchResultData result = searchPerson.get();
ObjectMapper mapper = new ObjectMapper();
LOGGER.info("search Person "+mapper.writeValueAsString(result));
return result;

( and obviously change the method return signature )


来源: stackexchange

问:
get user location lat long on cordova without enable their location
I am making mobile (Android, iPhone and WP8) app in cordova with angular. I need to take users lat, long. I used http://ngcordova.com/docs/plugins/geolocation/ and HTML 5 geolocation API and angular geolocation Js to get users location. When I turn on Mobiles -> Settins -> Locations -> On I am getting users location, When users turned off their location I couldn't take their location.

Is it possible to get users locations if user turned off their locations at mobile settings.

答:
No, if the user disables their location you're not allowed to get it. Not only by software, but also in the Terms of Use of the SDKs you're using (Android and iOS stores will ban your apps).

As jcesarmobile commented, you can get it with some accuracy the user location based on their IP. For example, it's good enough for getting the user country to set the app language, works like a charm.

ContentLicense: CC BY-SA 3.0


问:
Node js async convert to sync
I need to push data to array synchronously. First API request get image key base one that need to get image data within loop.</p>

```<code> var deasync = require('deasync');

        router.get('/a', function(req, res) {
                var username="user";
                var passw ="pass";
                var op = [];
                var args = {
                    headers: {
                    'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
                }
            };
         //this is first api request
        client.get(global.apiUrl+"V1/ProductItem", args,
        function (data, response) {
                //this is second api request
            data.forEach(function(img) {client.get(global.apiUrl+"V1/ImagePreview/"+img.AvatarKey,args,
                    function (data2, response){
                               img['data']=data2.Image;
                               deasync(pushData(img));
                          });
                    });
                });

        function pushData(img){
            op.push(img);//array push
        }
        res.render('test1', { "out":JSON.stringify(op) });
        });
</code>```

答:
As much as I think deasync is a poor choice of solving your particular issue, the key to using it, is to "deasync" asynchronous functions. As Array.push is synchronous, deasync'ing Array.push makes no sense

having read the documentation for deasync, it's fairly simple to use

```<code>var deasync = require('deasync');
// create a sync client.get
function syncClientGet(client, url, args) {
    var inflight = true;
    var ret;
    client.get(url, args, function(data, response) {
        // as your original code ignores response, ignore it here as well
        ret = data;
        inflight = false;
    });
    deasync.loopWhile(() => inflight);
    return ret;
}

router.get('/a', function(req, res) {
    var username = "user";
    var passw = "pass";
    var op = [];
    var args = {
        headers: {
            'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
        }
    };

    let data = syncClientGet(client, global.apiUrl + "V1/ProductItem", args);
    data.forEach(function(img) {
        let data2 = syncClientGet(client, global.apiUrl + "V1/ImagePreview/" + img.AvatarKey, args);
        img['data'] = data2.Image;
        op.push(img);
    });
    res.render('test1', {
        "out": JSON.stringify(op)
    });
});
</code>```

However, embracing asynchronicity, the code you posted could be easily written as

```<code>router.get('/a', function (req, res) {
    var username = "user";
    var passw = "pass";
    var op = [];
    var args = {
        headers: {
            'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
        }
    };
    client.get(global.apiUrl + "V1/ProductItem", args, function (data, response) {
        data.forEach(function (img) {
            client.get(global.apiUrl + "V1/ImagePreview/" + img.AvatarKey, args, function (data2, response) {
                img['data'] = data2.Image;
                op.push(img);
                if (img.length == data.length) {
                    res.render('test1', {
                        "out": JSON.stringify(op)
                    });
                }
            });
        });
    });
});
</code>```

or, using Promises

```<code>router.get('/a', function (req, res) {
    var username = "user";
    var passw = "pass";
    var args = {
        headers: {
            'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
        }
    };
    // create a Promisified client get
    var clientGetPromise = function clientGetPromise(client, url, args) {
        return new Promise(function (resolve, reject) {
            return client.get(url, args, function (data, response) {
                return resolve(data);
            });
        });
    };

    clientGetPromise(client, global.apiUrl + "V1/ProductItem", args).then(function (data) {
        return Promise.all(data.map(function (img) {
            return clientGetPromise(client, global.apiUrl + "V1/ImagePreview/" + img.AvatarKey, args).then(function (data2) {
                img['data'] = data2.Image;
                return img;
            });
        }));
    }).then(function (op) { // op is an Array of img because that's how Promise.all rolls
        return res.render('test1', { "out": JSON.stringify(op) });
    });
});
</code>```

Title: Node js async convert to sync

Body:
I need to push data to array synchronously. First API request get image key base one that need to get image data within loop.

 var deasync = require('deasync');

        router.get('/a', function(req, res) {
                var username="user";
                var passw ="pass";
                var op = [];
                var args = {
                    headers: {
                    'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
                }
            };
         //this is first api request
        client.get(global.apiUrl+"V1/ProductItem", args,
        function (data, response) {
                //this is second api request
            data.forEach(function(img) {client.get(global.apiUrl+"V1/ImagePreview/"+img.AvatarKey,args,
                    function (data2, response){
                               img['data']=data2.Image;
                               deasync(pushData(img));
                          });
                    });
                });

        function pushData(img){
            op.push(img);//array push
        }
        res.render('test1', { "out":JSON.stringify(op) });
        });

Body:
As much as I think deasync is a poor choice of solving your particular issue, the key to using it, is to "deasync" asynchronous functions. As Array.push is synchronous, deasync'ing Array.push makes no sense

having read the documentation for deasync, it's fairly simple to use

var deasync = require('deasync');
// create a sync client.get
function syncClientGet(client, url, args) {
    var inflight = true;
    var ret;
    client.get(url, args, function(data, response) {
        // as your original code ignores response, ignore it here as well
        ret = data;
        inflight = false;
    });
    deasync.loopWhile(() => inflight);
    return ret;
}

router.get('/a', function(req, res) {
    var username = "user";
    var passw = "pass";
    var op = [];
    var args = {
        headers: {
            'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
        }
    };

    let data = syncClientGet(client, global.apiUrl + "V1/ProductItem", args);
    data.forEach(function(img) {
        let data2 = syncClientGet(client, global.apiUrl + "V1/ImagePreview/" + img.AvatarKey, args);
        img['data'] = data2.Image;
        op.push(img);
    });
    res.render('test1', {
        "out": JSON.stringify(op)
    });
});

However, embracing asynchronicity, the code you posted could be easily written as

router.get('/a', function (req, res) {
    var username = "user";
    var passw = "pass";
    var op = [];
    var args = {
        headers: {
            'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
        }
    };
    client.get(global.apiUrl + "V1/ProductItem", args, function (data, response) {
        data.forEach(function (img) {
            client.get(global.apiUrl + "V1/ImagePreview/" + img.AvatarKey, args, function (data2, response) {
                img['data'] = data2.Image;
                op.push(img);
                if (img.length == data.length) {
                    res.render('test1', {
                        "out": JSON.stringify(op)
                    });
                }
            });
        });
    });
});

or, using Promises

router.get('/a', function (req, res) {
    var username = "user";
    var passw = "pass";
    var args = {
        headers: {
            'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
        }
    };
    // create a Promisified client get
    var clientGetPromise = function clientGetPromise(client, url, args) {
        return new Promise(function (resolve, reject) {
            return client.get(url, args, function (data, response) {
                return resolve(data);
            });
        });
    };

    clientGetPromise(client, global.apiUrl + "V1/ProductItem", args).then(function (data) {
        return Promise.all(data.map(function (img) {
            return clientGetPromise(client, global.apiUrl + "V1/ImagePreview/" + img.AvatarKey, args).then(function (data2) {
                img['data'] = data2.Image;
                return img;
            });
        }));
    }).then(function (op) { // op is an Array of img because that's how Promise.all rolls
        return res.render('test1', { "out": JSON.stringify(op) });
    });
});


问:
multiple str_replace in given output (PHP)
Really bad at PHP. Learning it. I have an output here that's from scraped data. Data is scraped and saved in a cache file under the name nationalhi. In the output, there's an undesirable "2)", so I put in an str_replace and it's getting rid of it succesfully. Thing is, there's also a "5)" I'd like to get rid of, but everytime I try and combine two str, it breaks the code, because I'm doing something wrong. Any suggestions/help? Thanks very much.

Working code with one single str replace function:

```<code>file_put_contents(globalVars::$_cache_dir . "nationalhifour",
str_replace('Low', ' ', $ret_[39]));
</code>```

Two STR replaces, not working:

```<code> file_put_contents(globalVars::$_cache_dir . "nationalhi", str_replace('2)',
' ', str_replace('5)', ' ', $ret_[35]));
</code>```

答:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [,
  int &$count ] ) If search and replace are arrays, then str_replace()
  takes a value from each array and uses them to search and replace on
  subject

for more info look at str_replace
here is an example

```<code>echo str_replace(['1','2','3'],['100','200','300'],'the strings  1 2 3 are replaced successfully ');
// output the strings 100 200 300 are replaced successfully
</code>```

Body:
Really bad at PHP. Learning it. I have an output here that's from scraped data. Data is scraped and saved in a cache file under the name nationalhi. In the output, there's an undesirable "2)", so I put in an str_replace and it's getting rid of it succesfully. Thing is, there's also a "5)" I'd like to get rid of, but everytime I try and combine two str, it breaks the code, because I'm doing something wrong. Any suggestions/help? Thanks very much.

Working code with one single str replace function:

file_put_contents(globalVars::$_cache_dir . "nationalhifour",
str_replace('Low', ' ', $ret_[39]));

Two STR replaces, not working:

 file_put_contents(globalVars::$_cache_dir . "nationalhi", str_replace('2)',
' ', str_replace('5)', ' ', $ret_[35]));

Body:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [,
  int &$count ] ) If search and replace are arrays, then str_replace()
  takes a value from each array and uses them to search and replace on
  subject

for more info look at str_replace
here is an example

echo str_replace(['1','2','3'],['100','200','300'],'the strings  1 2 3 are replaced successfully ');
// output the strings 100 200 300 are replaced successfully


问:
How many times a digit show up
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

```<code>#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}
</code>```

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.

答:
The faster, O(2n-1) complexity solution

```<code>#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;

    for(int i = 0; i < 10; ++i)
       ++occur[arr[i]];

    for (int i = 1; i < 10; ++i)
       if (occur[i] > occur[max])
         max = i;

    printf("Most frequent: %d\ occurs: %d\n", max, occur[max]);

    return 0;
}
</code>```

Yet faster, in O(n)...  I had a feeling that..

```<code>int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;

    for(int i = 0; i < 10; ++i)
       if (++occur[arr[i]] > occur[max])
          max = arr[i];

    printf("Most frequent: %d\ occurs: %d\n", max, occur[max]);

    return 0;
}
</code>```

Title: How many times a digit show up

Body:
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.

Body:
The faster, O(2n-1) complexity solution

#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;

    for(int i = 0; i < 10; ++i)
       ++occur[arr[i]];

    for (int i = 1; i < 10; ++i)
       if (occur[i] > occur[max])
         max = i;

    printf("Most frequent: %d\ occurs: %d\n", max, occur[max]);

    return 0;
}

Yet faster, in O(n)...  I had a feeling that..

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;

    for(int i = 0; i < 10; ++i)
       if (++occur[arr[i]] > occur[max])
          max = arr[i];

    printf("Most frequent: %d\ occurs: %d\n", max, occur[max]);

    return 0;
}


问:
A field initializer cannot reference the nonstatic field, method, or property, setting a variable
Coding enthusiast/hobbyist here, new to C#, trying to wrap my head around the language and have been beating my head against a wall on this problem for a few days.  Have tried searching on this site as well as reading the documentation on this error on msdn, as well as documentation on classes, field, intitialization, etc.  Apologies if this is obvious to everyone else, but I've tied my brain in knots trying to understand this error.

I'm writing a basic MUD game (text-based RPG run in the command line) as my first C# program, and I'm running into an issue when I try to access monster stats (which I've put in a different namespace titled "Bestiary," which will contain the stats for all monsters as their own Class).  I've tried several different methods but have been unable to get the program to compile without error.

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

//Battle system is contained in this namespace.

class Combat(string playerName)
{
  public int[] playerStats= new int[] { 25, 10};
  public int[] monsterStats= new int[] { 10, 10};

  string playerName = playerName;
  Slime s = new Slime();
  string monsterName = s.Name();
...

//Bestiary section being referenced in Combat
using System;
using System.Collections;

namespace Bestiary
{
    //List of Monsters and their stats
    class Slime
    {
        private string name = "Slime";
        public string Name
        {
            get { return name; }

            set { name = value; }
        }

        private int hp = 10;
        public int HP
        {
            get { return hp; }

            set { hp = value; }
        }

        private int atk = 1;
        public int ATK
        {
            get { return atk; }

            set { atk = value; }
        }

    }
</code>```

When I try to compile this I get the error at the line "string monsterName = s.Name();".

答:
You should reference your slime's name like this:

```<code>  string monsterName = s.Name;
</code>```

Properties were designed specifically to allow you to put logic inside get and set 'methods' while retaining the syntax of reading or writing fields.

Also, put the code inside the constructor:

```<code>class Combat
{
  public int[] playerStats = new int[] { 25, 10};
  public int[] monsterStats = new int[] { 10, 10};
  string playerName;
  string monsterName;

  public Combat(string playerName)
  {
    this.playerName = playerName;
    Slime s = new Slime();
    monsterName = s.Name;
  }
}
</code>```

Apart from that, I suggest you leverage the usage of var.

```<code>  Slime s = new Slime();
</code>```

Will become

```<code>  var slime = new Slime();
</code>```

Also, there is no need to declare backing fields directly. Use this:

```<code>public string Name { get; set; } = "Slime";
</code>```

Good luck with C#.

Body:
Coding enthusiast/hobbyist here, new to C#, trying to wrap my head around the language and have been beating my head against a wall on this problem for a few days.  Have tried searching on this site as well as reading the documentation on this error on msdn, as well as documentation on classes, field, intitialization, etc.  Apologies if this is obvious to everyone else, but I've tied my brain in knots trying to understand this error.

I'm writing a basic MUD game (text-based RPG run in the command line) as my first C# program, and I'm running into an issue when I try to access monster stats (which I've put in a different namespace titled "Bestiary," which will contain the stats for all monsters as their own Class).  I've tried several different methods but have been unable to get the program to compile without error.

using System;
using System.Collections;
using Bestiary;

//Battle system is contained in this namespace.

class Combat(string playerName)
{
  public int[] playerStats= new int[] { 25, 10};
  public int[] monsterStats= new int[] { 10, 10};

  string playerName = playerName;
  Slime s = new Slime();
  string monsterName = s.Name();
...

//Bestiary section being referenced in Combat
using System;
using System.Collections;

namespace Bestiary
{
    //List of Monsters and their stats
    class Slime
    {
        private string name = "Slime";
        public string Name
        {
            get { return name; }

            set { name = value; }
        }

        private int hp = 10;
        public int HP
        {
            get { return hp; }

            set { hp = value; }
        }

        private int atk = 1;
        public int ATK
        {
            get { return atk; }

            set { atk = value; }
        }

    }

When I try to compile this I get the error at the line "string monsterName = s.Name();".

Body:
You should reference your slime's name like this:

  string monsterName = s.Name;

Properties were designed specifically to allow you to put logic inside get and set 'methods' while retaining the syntax of reading or writing fields.

Also, put the code inside the constructor:

class Combat
{
  public int[] playerStats = new int[] { 25, 10};
  public int[] monsterStats = new int[] { 10, 10};
  string playerName;
  string monsterName;

  public Combat(string playerName)
  {
    this.playerName = playerName;
    Slime s = new Slime();
    monsterName = s.Name;
  }
}

Apart from that, I suggest you leverage the usage of var.

  Slime s = new Slime();

Will become

  var slime = new Slime();

Also, there is no need to declare backing fields directly. Use this:

public string Name { get; set; } = "Slime";

Good luck with C#.


问:
Projection Matrix in Apple's iPhone OpenGLES 2.0 Template Project
Background:

I am trying to learn OpenGLES 2.0 for the iPhone and have been stumped by the template project that Apple provides in xCode.

The default project shows a 2d square, but I want to experiment with adding vertexes with varying depths on the z axis.

In Apple's default OpenGL project, they draw a 2d square using only x and y coordinates passed to the vertex shader.

In order to experiment with placing vertices in 3d space, I added a z value to the vertex data in the sample project.  Then I changed the size parameter in the glVertexAttribPointer method from 2 to 3.  I changed the z values on the vertices in the hope that it would cause the square to appear tilted backwards when I ran the program.

The problem is that it still shows up as the same 2d square.  From my reading, I believe this is caused by the projection matrix being set to Orthographic instead of Perspective.

Question:

How do I change the projection matrix from Orthographic to Perspective using OpenGLES 2.0 in Apple's template OpenGL project?

I have tried:

glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 glFrustumf(-0.5, 0.5, -0.5, 0.5, 1, 10);

But it didn't change the result.

I also tried adding something like this to the vertex shader program:

mat4 projectionMatrix = { 2.0/320.0, 0.0, 0.0, -1.0,
         0.0, 2.0/480.0, 0.0, -1.0,
         0.0, 0.0, -1.0, 0.0,
  0.0, 0.0, 0.0, 1.0};

gl_Position *= projectionMatrix;

But that didn't work either.

Is the method for setting the projection matrix different for OpenGLES 2.0 that it was for 1.0.  I am thinking maybe the stuff I am trying is not compatible with 2.0.

Thanks in advance.

Mike

Update

Thanks for your help John.  I really appreciate it.  I tried adding a depth buffer based on your suggestion by adding the following code to the createFramebuffer method in my EAGL view, but still no change.

```<code>// Create depth render buffer and allocate backing store.
        glGenRenderbuffers(1, &depthRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);

        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, framebufferWidth, framebufferHeight);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);
</code>```

And if I add the following code to my render method:

```<code>    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustumf(-0.5, 0.5, -0.5, 0.5, 1, 10);
</code>```

Xcode throws an exception.  Any thoughts?

答: It sounds like you are using the example that doesn't default to using a depth buffer. Look for references to GL_DEPTH_COMPONENT16 in the sample project and implement the use of the depth buffer.</p>

ContentLicense: CC BY-SA 2.5

Body:
Background:

I am trying to learn OpenGLES 2.0 for the iPhone and have been stumped by the template project that Apple provides in xCode.

The default project shows a 2d square, but I want to experiment with adding vertexes with varying depths on the z axis.

In Apple's default OpenGL project, they draw a 2d square using only x and y coordinates passed to the vertex shader.

In order to experiment with placing vertices in 3d space, I added a z value to the vertex data in the sample project.  Then I changed the size parameter in the glVertexAttribPointer method from 2 to 3.  I changed the z values on the vertices in the hope that it would cause the square to appear tilted backwards when I ran the program.

The problem is that it still shows up as the same 2d square.  From my reading, I believe this is caused by the projection matrix being set to Orthographic instead of Perspective.

Question:

How do I change the projection matrix from Orthographic to Perspective using OpenGLES 2.0 in Apple's template OpenGL project?

I have tried:

glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 glFrustumf(-0.5, 0.5, -0.5, 0.5, 1, 10);

But it didn't change the result.

I also tried adding something like this to the vertex shader program:

mat4 projectionMatrix = { 2.0/320.0, 0.0, 0.0, -1.0,
         0.0, 2.0/480.0, 0.0, -1.0,
         0.0, 0.0, -1.0, 0.0,
  0.0, 0.0, 0.0, 1.0};

gl_Position *= projectionMatrix;

But that didn't work either.

Is the method for setting the projection matrix different for OpenGLES 2.0 that it was for 1.0.  I am thinking maybe the stuff I am trying is not compatible with 2.0.

Thanks in advance.

Mike

Update

Thanks for your help John.  I really appreciate it.  I tried adding a depth buffer based on your suggestion by adding the following code to the createFramebuffer method in my EAGL view, but still no change.

// Create depth render buffer and allocate backing store.
        glGenRenderbuffers(1, &depthRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);

        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, framebufferWidth, framebufferHeight);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);

And if I add the following code to my render method:

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustumf(-0.5, 0.5, -0.5, 0.5, 1, 10);

Xcode throws an exception.  Any thoughts?


问:
How can I filter by a subset of conditions based on a parameter in Microsoft SQL?
I have a parameter in an SQL query where I would like to select either a subset of possible rows, or one based on the parameter.

Basically, I have a column called model, which can contain either 1000, 2000, 3000, 4000, or 5000. When the parameter is set to NULL, I would like it to select just 1000, 2000 and 3000, but not 4000 or 5000.

I have tried various combinations of CASE statements, I.e.

```<code>WHERE model = CASE WHEN @model = NULL THEN model = 1000 OR model = 2000 OR
model = 3000 ELSE @model END AND <query continues>
</code>```

How can I achieve this in SQL Server?

答:
Just do this using or:

```<code>WHERE ( (@model is null and model in (1000, 2000, 3000)) or
        model = @model
      )
</code>```

Body:
I have a parameter in an SQL query where I would like to select either a subset of possible rows, or one based on the parameter.

Basically, I have a column called model, which can contain either 1000, 2000, 3000, 4000, or 5000. When the parameter is set to NULL, I would like it to select just 1000, 2000 and 3000, but not 4000 or 5000.

I have tried various combinations of CASE statements, I.e.

WHERE model = CASE WHEN @model = NULL THEN model = 1000 OR model = 2000 OR
model = 3000 ELSE @model END AND <query continues>

How can I achieve this in SQL Server?

Body:
Just do this using or:

WHERE ( (@model is null and model in (1000, 2000, 3000)) or
        model = @model
      )


问:
Telerik radgrid row color issue
In my code I have this sub to handle changing row colors depending on the contents of a column called "backorder" which is bit in sqlserver.
When I test if it is True or 1 it executes the main "IF" code twice which is correct for my datatable. 2 rows display as backorder = True. However the grid remains the normal color. If I uncomment the else code block, ALL cells in that column are orange regardless of content and the execution still passed thru the main "IF" twice. I am quite confused by this behavior. If it was CSS interfering, why would it let the orange color work? I have tried a dozen variations of code which all posters say should work...

Please help! I have spent most of the day trying to unravel this!

```<code>Protected Sub RadGrid1_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound
    If TypeOf e.Item Is GridDataItem Then
        Dim item As GridDataItem = DirectCast(e.Item, GridDataItem)
        If item("backorder").Text = "True" Or item("backorder").Text = "1" Then
            item("backorder").BackColor = System.Drawing.Color.Red
        Else
            'item("backorder").BackColor = System.Drawing.Color.Orange
        End If
    End If

End Sub
</code>```

答:
Your problem is that item("backorder") returns an object of type TableCell, not a row. Therefore, when setting item("backorder").BackColor = System.Drawing.Color.Red you are setting the cell in the column backorder's BackColor, not the entire rows backcolor. If the Column backorder is not visible, you wont see any change.

Try the following code:

```<code>Protected Sub RadGrid1_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound
If TypeOf e.Item Is GridDataItem Then
     Dim item As GridDataItem = DirectCast(e.Item, GridDataItem)
     If item("backorder").Text = "True" Or item("backorder").Text = "1" Then
         item.BackColor = Drawing.Color.Red
     Else
         item.BackColor = System.Drawing.Color.Orange
     End If
End If
End Sub
</code>```

What this does is check the column 'backorder', and then sets the entire rows BackColor by setting the BackColor for the GridDataItem.

Check out Shinu's answer in the following post. Telerik Forum Post

Title: Telerik radgrid row color issue

Body:
In my code I have this sub to handle changing row colors depending on the contents of a column called "backorder" which is bit in sqlserver.
When I test if it is True or 1 it executes the main "IF" code twice which is correct for my datatable. 2 rows display as backorder = True. However the grid remains the normal color. If I uncomment the else code block, ALL cells in that column are orange regardless of content and the execution still passed thru the main "IF" twice. I am quite confused by this behavior. If it was CSS interfering, why would it let the orange color work? I have tried a dozen variations of code which all posters say should work...

Please help! I have spent most of the day trying to unravel this!

Protected Sub RadGrid1_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound
    If TypeOf e.Item Is GridDataItem Then
        Dim item As GridDataItem = DirectCast(e.Item, GridDataItem)
        If item("backorder").Text = "True" Or item("backorder").Text = "1" Then
            item("backorder").BackColor = System.Drawing.Color.Red
        Else
            'item("backorder").BackColor = System.Drawing.Color.Orange
        End If
    End If

End Sub

Body:
Your problem is that item("backorder") returns an object of type TableCell, not a row. Therefore, when setting item("backorder").BackColor = System.Drawing.Color.Red you are setting the cell in the column backorder's BackColor, not the entire rows backcolor. If the Column backorder is not visible, you wont see any change.

Try the following code:

Protected Sub RadGrid1_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound
If TypeOf e.Item Is GridDataItem Then
     Dim item As GridDataItem = DirectCast(e.Item, GridDataItem)
     If item("backorder").Text = "True" Or item("backorder").Text = "1" Then
         item.BackColor = Drawing.Color.Red
     Else
         item.BackColor = System.Drawing.Color.Orange
     End If
End If
End Sub

What this does is check the column 'backorder', and then sets the entire rows BackColor by setting the BackColor for the GridDataItem.

Check out Shinu's answer in the following post. Telerik Forum Post


问:
mysqli_affected_rows() when update
I have a trouble in this code, can anybody help?:(
There's my code:</p>

```<code>$query = "UPDATE subjects SET
              menu_name = '{$menu_name}',
              position = {$position},
              visible = {$visible}
              WHERE id = {$id}";
    $result = mysqli_query($connection, $query);
    if (mysqli_affected_rows() == 1) {
      $message = "The subject was successfully updated.";
    } else {
      $message = "The subject update failed.";
      $message .= "<br>" . mysqli_error();
    }

  } else {
    $message = "There were " . count($errors) . " errors in the form.";
  }
</code>```

答:
```<code>mysqli_affected_rows();
</code>```

Connection Required. Specifies the MySQL connection to use

Change your code to

```<code>mysqli_affected_rows($connection);
</code>```

Title: mysqli_affected_rows() when update

Body:
I have a trouble in this code, can anybody help?:(
There's my code:

$query = "UPDATE subjects SET
              menu_name = '{$menu_name}',
              position = {$position},
              visible = {$visible}
              WHERE id = {$id}";
    $result = mysqli_query($connection, $query);
    if (mysqli_affected_rows() == 1) {
      $message = "The subject was successfully updated.";
    } else {
      $message = "The subject update failed.";
      $message .= "
" . mysqli_error();
    }

  } else {
    $message = "There were " . count($errors) . " errors in the form.";
  }

Body:
mysqli_affected_rows();

Connection Required. Specifies the MySQL connection to use

Change your code to

mysqli_affected_rows($connection);


问:
To PyQt5 'connect' conversion
I try to make a conversion of some code from PyQt4 to PyQt5, however I have not ever worked with PyQt, that is why I have some problems with this. I failed to convert some code with .connect, because as I understand in PyQt5 work with signals and slots changed. Here is the code.

```<code>class Gui(QWidget.QMainWindow, Ui_MainWindow):

    def __init__(self, cfgpath):
        QWidget.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        self.configpath = cfgpath
        self.paint = Viewer(self)
        self.setupUi(self)

        self.loadButton.clicked.connect(self.loadImage)
        self.maskClearButton.clicked.connect(self.paint.clearMask)
        self.brushSizeSB.valueChanged.connect(self.brushSizeChange)
        btnlist = [self.horDownBtn, self.horDownLargeBtn, self.horUpBtn, self.horUpLargeBtn,
                   self.vertDownBtn, self.vertDownLargeBtn, self.vertUpBtn, self.vertUpLargeBtn]
        sigmap = QtCore.QSignalMapper(self)
        for i in range(len(btnlist)):
            # Here it falls
            self.connect(btnlist[i], QtCore.SIGNAL("clicked()"), sigmap, QtCore.SLOT("map()"))
            btnlist[i].clicked
            sigmap.setMapping(btnlist[i], i)
        # And here
        self.connect(sigmap, QtCore.SIGNAL("mapped(int)"), self.paint.handleScaleBtn)
</code>```

So how can I change this code to make it work?

答:
Here you have all the information needed for the new signal slot style: pyqt new-style signal/slots
Try and if you have any particular problem let me know. </p>

Title: To PyQt5 'connect' conversion

Body:
I try to make a conversion of some code from PyQt4 to PyQt5, however I have not ever worked with PyQt, that is why I have some problems with this. I failed to convert some code with .connect, because as I understand in PyQt5 work with signals and slots changed. Here is the code.

class Gui(QWidget.QMainWindow, Ui_MainWindow):

    def __init__(self, cfgpath):
        QWidget.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        self.configpath = cfgpath
        self.paint = Viewer(self)
        self.setupUi(self)

        self.loadButton.clicked.connect(self.loadImage)
        self.maskClearButton.clicked.connect(self.paint.clearMask)
        self.brushSizeSB.valueChanged.connect(self.brushSizeChange)
        btnlist = [self.horDownBtn, self.horDownLargeBtn, self.horUpBtn, self.horUpLargeBtn,
                   self.vertDownBtn, self.vertDownLargeBtn, self.vertUpBtn, self.vertUpLargeBtn]
        sigmap = QtCore.QSignalMapper(self)
        for i in range(len(btnlist)):
            # Here it falls
            self.connect(btnlist[i], QtCore.SIGNAL("clicked()"), sigmap, QtCore.SLOT("map()"))
            btnlist[i].clicked
            sigmap.setMapping(btnlist[i], i)
        # And here
        self.connect(sigmap, QtCore.SIGNAL("mapped(int)"), self.paint.handleScaleBtn)

So how can I change this code to make it work?


问:
C# ASP MVC pulling data from the web config file is not working
I'm trying to pull data from the web config file as outlined by this msdn resource.

Here is my code:

```<code>System.Configuration.Configuration activeCampaignApiSetting1 =
  System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (activeCampaignApiSetting1.AppSettings.Settings.Count > 0) {
    System.Configuration.KeyValueConfigurationElement activeCampaignApiKeySetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiKey"];
    if (activeCampaignApiKeySetting != null) {
        activeCampaignApiKey = activeCampaignApiKeySetting.Value;
    }

    System.Configuration.KeyValueConfigurationElement activeCamapignApiUrlSetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiUrl"];
    if (activeCamapignApiUrlSetting != null) {
        activeCampaignApiUrl = activeCamapignApiUrlSetting.Value;
    }
}
</code>```

When I try to instantiate this class:

```<code>var acs = new Acs(activeCampaignApiKey, activeCampaignApiUrl);
</code>```

it throws an exception telling me that the values are blank.

The values in the web config file are there:

```<code><add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />
</code>```

Anyone know where I may be going wrong?
Cheers

答:
Ok so I have a better solution,

As I'm working with nopCommerce I need to use:

```<code>private readonly ISettingService _settingService = EngineContext.Current.Resolve<ISettingService>();

string apikey = _settingService.GetSettingByKey<string>("apikey_removed");
string apiurl = _settingService.GetSettingByKey<string>("apiurl_removed");
</code>```

As outlined in this forum thread

Then in the administration backend under configuration > settings > all settings I add the key there.

This is a much better solution because if the api key or url ever need to be changed it can be done through the nopcommerce administration panel. rather than rebuilding/publishing the solution to a web server.

Hope this helps someone :)

Body:
I'm trying to pull data from the web config file as outlined by this msdn resource.

Here is my code:

System.Configuration.Configuration activeCampaignApiSetting1 =
  System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (activeCampaignApiSetting1.AppSettings.Settings.Count > 0) {
    System.Configuration.KeyValueConfigurationElement activeCampaignApiKeySetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiKey"];
    if (activeCampaignApiKeySetting != null) {
        activeCampaignApiKey = activeCampaignApiKeySetting.Value;
    }

    System.Configuration.KeyValueConfigurationElement activeCamapignApiUrlSetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiUrl"];
    if (activeCamapignApiUrlSetting != null) {
        activeCampaignApiUrl = activeCamapignApiUrlSetting.Value;
    }
}

When I try to instantiate this class:

var acs = new Acs(activeCampaignApiKey, activeCampaignApiUrl);

it throws an exception telling me that the values are blank.

The values in the web config file are there:

<add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />

Anyone know where I may be going wrong?
Cheers

Body:
Ok so I have a better solution,

As I'm working with nopCommerce I need to use:

private readonly ISettingService _settingService = EngineContext.Current.Resolve<ISettingService>();

string apikey = _settingService.GetSettingByKey<string>("apikey_removed");
string apiurl = _settingService.GetSettingByKey<string>("apiurl_removed");

As outlined in this forum thread

Then in the administration backend under configuration > settings > all settings I add the key there.

This is a much better solution because if the api key or url ever need to be changed it can be done through the nopcommerce administration panel. rather than rebuilding/publishing the solution to a web server.

Hope this helps someone :)


问:
multiple images in div
Could not find anything on this for the life of me. I simply want to display 1 little icon, multiple times on the same row,
But want to rotate each instance a bit more then the last one. So by the end of the row, the last icon is completely flipped compared to the first icon.

Here is my attempt: (thanks)

```<code><div class="container">
    <p class="one">I don't</p><p class="two">really want </p><p class="three">any</p><p class="four">words here</p>
</div>

<style>
p.one {
  float:left;
  image: url("http://www.itel.am/assets/ico/iconsForSocials/gl.png");
}
p.two {
  float:right;
  background-image: url("http://www.itel.am/assets/ico/iconsForSocials/gl.png");
  transform: rotate(60deg);
}
p.three {
  float:right;
  background-image: url("http://www.itel.am/assets/ico/iconsForSocials/gl.png");
  transform: rotate(120deg);
}
p.four {
  float:right;
  background-image: url("http://www.itel.am/assets/ico/iconsForSocials/gl.png");
  transform: rotate(180deg);
}
</style>
</code>```

答:
I think you should separate the text from rotating. something like this

```<code><div class="container">
    <p><span class="one"></span>I don't</p>
    <p><span class="two"></span>really want </p>
    <p><span class="three"></span>any</p>
    <p><span class="four"></span>words here</p>
</div>
</code>```

and in css use image as background image

```<code>.container {width:100%}
.container p { float:left; margin:0 20px}
.container p span {
     width:20px; height:20px; display:block;
     background: url("http://www.itel.am/assets/ico/iconsForSocials/gl.png") no-repeat left center; float:left;
}
.two { transform: rotate(60deg); }
.three { transform: rotate(120deg); }
.four { transform: rotate(180deg); }
</code>```

here is the working sample

Title: multiple images in div

Body:
Could not find anything on this for the life of me. I simply want to display 1 little icon, multiple times on the same row,
But want to rotate each instance a bit more then the last one. So by the end of the row, the last icon is completely flipped compared to the first icon.

Here is my attempt: (thanks)

I don't

really want

any

words here

Body:
I think you should separate the text from rotating. something like this

<div class="container">
    <p><span class="one"></span>I don't</p>
    <p><span class="two"></span>really want </p>
    <p><span class="three"></span>any</p>
    <p><span class="four"></span>words here</p>
</div>

and in css use image as background image

.container {width:100%}
.container p { float:left; margin:0 20px}
.container p span {
     width:20px; height:20px; display:block;
     background: url("http://www.itel.am/assets/ico/iconsForSocials/gl.png") no-repeat left center; float:left;
}
.two { transform: rotate(60deg); }
.three { transform: rotate(120deg); }
.four { transform: rotate(180deg); }

here is the working sample


问:
Why does my DbProviderFactory perform differently than SqlClientFactory?
I implemented a custom DbProviderFactory which returned the SqlX types except I added the following logic to CreateCommand

```<code>public override DbCommand CreateCommand()
{
    var cmd = new SqlCommand();
    if (CommandCreated != null)
        CommandCreated(cmd, EventArgs.Empty);
    cmd.StatementCompleted += cmd_StatementCompleted;
    return cmd;
}

void cmd_StatementCompleted(object sender, StatementCompletedEventArgs e)
{
    if (StatementCompleted != null)
        StatementCompleted(sender, e);
}
</code>```

I did this so I could track whenever a SqlDataSource created a command and then when it finished to log all SqlCalls (without needing Sql Profiler up).  This worked, however after I implemented this I got an exception with the following SqlDataSource

```<code><asp:SqlDataSource ProviderName="MyProvider" ID="SqlDataSource1"
    runat="server" ConnectionString="<%$ ConnectionStrings:default %>"
    SelectCommandType="StoredProcedure"
    SelectCommand="dbo.GetX"
    OnSelecting="SqlDataSource1_Selecting">
    <SelectParameters>
      <asp:Parameter Name="x_id" Type="Byte"/>
    </SelectParameters>
</asp:SqlDataSource>
</code>```

and this in the code behind.

```<code>protected void SqlDataSource1_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
    e.Command.Parameters["@x_id"].Value = "something else";
}
</code>```

The error being thrown was that the SqlParameter "@x_id" doesn't exist, even though this worked with the standard SqlClientFactory.  When using the debugger it showed that there was 1 parameter in the collection x_id when using MyProvider, and @x_id when using the default provider.

Is there some reason for this and is there some way I can get the @'s added automatically or should I just make sure the code-behind and the SqlDataSource agree on whether there is an @ or not.

The Stored Procedure still works without the '@' sign and luckily I don't do this direct manipulation of the Parameters collection much but I would like to know why this happens in the first place.

Thanks for the help.

答:
After digging more I found the following in the Source of SqlDataSourceView

```<code>protected virtual string ParameterPrefix
{
  get
  {
    if (!string.IsNullOrEmpty(this._owner.ProviderName) && !string.Equals(this._owner.ProviderName, "System.Data.SqlClient", StringComparison.OrdinalIgnoreCase))
    {
      return string.Empty;
    }
    return "@";
  }
}
</code>```

and so when using your own Provider it doesn't match the expected Provider name and so it just returns string.Empty.  If you need to do this then you will have to subclass SqlDataSource and SqlDataSourceView

```<code>public class MySqlDataSource : SqlDataSource
{
    protected override SqlDataSourceView CreateDataSourceView(string viewName)
    {
        return new MySqlDataSourceView(this, viewName, this.Context);
    }
}

public class MySqlDataSourceView : SqlDataSourceView
{
    private MySqlDataSource _owner;
    public MySqlDataSourceView(IPSqlDataSource owner, string name, System.Web.HttpContext context)
        : base(owner, name, context)
    {
        _owner = owner;
    }

    protected override string ParameterPrefix
    {
        get
        {
            if (!string.IsNullOrEmpty(this._owner.ProviderName) && !string.Equals(this._owner.ProviderName, "MyProvider", StringComparison.OrdinalIgnoreCase))
            {
                return base.ParameterPrefix;
            }
            return "@";
        }
    }

}
</code>```

Body:
I implemented a custom DbProviderFactory which returned the SqlX types except I added the following logic to CreateCommand

public override DbCommand CreateCommand()
{
    var cmd = new SqlCommand();
    if (CommandCreated != null)
        CommandCreated(cmd, EventArgs.Empty);
    cmd.StatementCompleted += cmd_StatementCompleted;
    return cmd;
}

void cmd_StatementCompleted(object sender, StatementCompletedEventArgs e)
{
    if (StatementCompleted != null)
        StatementCompleted(sender, e);
}

I did this so I could track whenever a SqlDataSource created a command and then when it finished to log all SqlCalls (without needing Sql Profiler up).  This worked, however after I implemented this I got an exception with the following SqlDataSource

<asp:SqlDataSource ProviderName="MyProvider" ID="SqlDataSource1"
    runat="server" ConnectionString="<%$ ConnectionStrings:default %>"
    SelectCommandType="StoredProcedure"
    SelectCommand="dbo.GetX"
    OnSelecting="SqlDataSource1_Selecting">
    <SelectParameters>
      <asp:Parameter Name="x_id" Type="Byte"/>
    </SelectParameters>
</asp:SqlDataSource>

and this in the code behind.

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
    e.Command.Parameters["@x_id"].Value = "something else";
}

The error being thrown was that the SqlParameter "@x_id" doesn't exist, even though this worked with the standard SqlClientFactory.  When using the debugger it showed that there was 1 parameter in the collection x_id when using MyProvider, and @x_id when using the default provider.

Is there some reason for this and is there some way I can get the @'s added automatically or should I just make sure the code-behind and the SqlDataSource agree on whether there is an @ or not.

The Stored Procedure still works without the '@' sign and luckily I don't do this direct manipulation of the Parameters collection much but I would like to know why this happens in the first place.

Thanks for the help.

Body:
After digging more I found the following in the Source of SqlDataSourceView

protected virtual string ParameterPrefix
{
  get
  {
    if (!string.IsNullOrEmpty(this._owner.ProviderName) && !string.Equals(this._owner.ProviderName, "System.Data.SqlClient", StringComparison.OrdinalIgnoreCase))
    {
      return string.Empty;
    }
    return "@";
  }
}

and so when using your own Provider it doesn't match the expected Provider name and so it just returns string.Empty.  If you need to do this then you will have to subclass SqlDataSource and SqlDataSourceView

public class MySqlDataSource : SqlDataSource
{
    protected override SqlDataSourceView CreateDataSourceView(string viewName)
    {
        return new MySqlDataSourceView(this, viewName, this.Context);
    }
}

public class MySqlDataSourceView : SqlDataSourceView
{
    private MySqlDataSource _owner;
    public MySqlDataSourceView(IPSqlDataSource owner, string name, System.Web.HttpContext context)
        : base(owner, name, context)
    {
        _owner = owner;
    }

    protected override string ParameterPrefix
    {
        get
        {
            if (!string.IsNullOrEmpty(this._owner.ProviderName) && !string.Equals(this._owner.ProviderName, "MyProvider", StringComparison.OrdinalIgnoreCase))
            {
                return base.ParameterPrefix;
            }
            return "@";
        }
    }

}


问:
C# Accessing Web Page - URI could not be determined
I'm trying to use a proxy to access a webpage but I am getting:

URI could not be determined

Here is my code:

```<code>WebProxy proxy = new WebProxy();
proxy.Address = new Uri("myproxyaddress");
proxy.UseDefaultCredentials = true;
proxy.BypassProxyOnLocal = false;

WebClient client = new WebClient();
client.Proxy = proxy;

string doc = client.DownloadString("http://www.google.com/");
</code>```

答:
This error happens when you try creating a URI and the constructor can't determine what format to parse the URI as (Relative or Absolute).

Normally, if you are specifying a full valid URL you won't have this issue.

If for some reason you can specify the kind of URI you are trying to create (UriKind.Absolute or UriKind.Relative)

For your purposes, you will need an absolute URI, which can be created like this:

```<code>var url = new Uri("myproxyaddress", UriKind.Absolute);
proxy.Address = url;
</code>```

Odds are that you might get an error calling new Uri("myproxyaddress", UriKind.Absolute) because the underlying issue is that "myproxyaddress" isn't a valid absolute URI.

Body:
I'm trying to use a proxy to access a webpage but I am getting:

URI could not be determined

Here is my code:

WebProxy proxy = new WebProxy();
proxy.Address = new Uri("myproxyaddress");
proxy.UseDefaultCredentials = true;
proxy.BypassProxyOnLocal = false;

WebClient client = new WebClient();
client.Proxy = proxy;

string doc = client.DownloadString("http://www.google.com/");

Body:
This error happens when you try creating a URI and the constructor can't determine what format to parse the URI as (Relative or Absolute).

Normally, if you are specifying a full valid URL you won't have this issue.

If for some reason you can specify the kind of URI you are trying to create (UriKind.Absolute or UriKind.Relative)

For your purposes, you will need an absolute URI, which can be created like this:

var url = new Uri("myproxyaddress", UriKind.Absolute);
proxy.Address = url;

Odds are that you might get an error calling new Uri("myproxyaddress", UriKind.Absolute) because the underlying issue is that "myproxyaddress" isn't a valid absolute URI.


问:
Using Javascript if else to trigger css transition when Navbar is open
I have a hamburger menu button that transforms into a 'X' when clicked using css and javascript. Because my Navbar closes when a selection is made, not just when the menu button is clicked, the menu button stays as a 'X'.

I assume that I will need to use an 'if else' statement to tell the menu button to change instead of on click but I am not sure how to code this.

I have included the css code for the style of the button as well as the javascript that is currently used to make it transform and the javascript for the navbar.

The button code is from this site:
http://callmenick.com/post/animating-css-only-hamburger-menu-icons

And the navbar is from here:
https://www.w3schools.com/howto/howto_js_sidenav.asp

Button CSS Code:

```<code>.c-hamburger {
  display: block;
  position: relative;
  overflow: hidden;
  margin: 0;
  padding: 0;
  width: 96px;
  height: 96px;
  font-size: 0;
  text-indent: -9999px;
  appearance: none;
  box-shadow: none;
  border-radius: none;
  border: none;
  cursor: pointer;
  transition: background 0.3s;
}

.c-hamburger:focus {
  outline: none;
}

.c-hamburger span {
  display: block;
  position: absolute;
  top: 44px;
  left: 18px;
  right: 18px;
  height: 8px;
  background: white;
}

.c-hamburger span::before,
.c-hamburger span::after {
  position: absolute;
  display: block;
  left: 0;
  width: 100%;
  height: 8px;
  background-color: #fff;
  content: "";
}

.c-hamburger span::before {
  top: -20px;
}

.c-hamburger span::after {
  bottom: -20px;
}

.c-hamburger {
  background-color: #ff3264;
}

.c-hamburger span {
  transition: background 0s 0.3s;
}

.c-hamburger span::before,
.c-hamburger span::after {
  transition-duration: 0.3s, 0.3s;
  transition-delay: 0.3s, 0s;
}

.c-hamburger span::before {
  transition-property: top, transform;
}

.c-hamburger span::after {
  transition-property: bottom, transform;
}

/* active state, i.e. menu open */
.c-hamburger.is-active {
  background-color: #cb0032;
}

.c-hamburger.is-active span {
  background: none;
}

.c-hamburger.is-active span::before {
  top: 0;
  transform: rotate(45deg);
}

.c-hamburger.is-active span::after {
  bottom: 0;
  transform: rotate(-45deg);
}

.c-hamburger.is-active span::before,
.c-hamburger.is-active span::after {
  transition-delay: 0s, 0.3s;
}
</code>```

Button Javascript:

```<code>(function() {

  "use strict";

  var toggles = document.querySelectorAll(".c-hamburger");

  for (var i = toggles.length - 1; i >= 0; i--) {
    var toggle = toggles[i];
    toggleHandler(toggle);
  };

  function toggleHandler(toggle) {
    toggle.addEventListener( "click", function(e) {
      e.preventDefault();
      (this.classList.contains("is-active") === true) ? this.classList.remove("is-active") : this.classList.add("is-active");
    });
  }

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

Navbar Javascript:

```<code>/* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */
function openNav() {
document.getElementById("mySidenav").style.width = "200px";
open = true;

}

/* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
open = false;

}
</code>```

If someone can help me find the correct code to do this, or has a better idea, I would really appreciate it. I'm quite new to Javascript if you can't already tell.

Thanks!

答:
I didn't quite get what you were up to. Did you mean that you wanted your NavBar to be closed when you click on a button not just only when clicking on the 'X'?

If it was so, in the HTML code, you simply need to add the onclick="closeNav();" to every button. Something like this

```<code><button onclick = "closeNav();"> My Button </button>
</code>```

Ok. Since you want the button to change into 'X' when the NavBar is open, you need to give your button an ID, then I think we could use the following Javascript condition.

HTML

```<code><button id="myButton" class="c-hamburger c-hamburger--htx">
    <span>
        ::before
        "toggle menu"
        ::after
    </span>
</button><!--I copied from the site you provided-->
</code>```

Javascript
I have edited your sidenav.js

```<code>function decide(){
  if(open == true){
    closeNav();
  }else{
    openNav();
  }
}

/* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */
function openNav() {
  document.getElementById("mySidenav").style.width = "200px";
  document.getElementById("myButton").classList.add("is-active");
  open = true;
}

/* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */
function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("myButton").classList.remove("is-active");
  open = false;
}
</code>```

Body:
I have a hamburger menu button that transforms into a 'X' when clicked using css and javascript. Because my Navbar closes when a selection is made, not just when the menu button is clicked, the menu button stays as a 'X'.

I assume that I will need to use an 'if else' statement to tell the menu button to change instead of on click but I am not sure how to code this.

I have included the css code for the style of the button as well as the javascript that is currently used to make it transform and the javascript for the navbar.

The button code is from this site:
http://callmenick.com/post/animating-css-only-hamburger-menu-icons

And the navbar is from here:
https://www.w3schools.com/howto/howto_js_sidenav.asp

Button CSS Code:

.c-hamburger {
  display: block;
  position: relative;
  overflow: hidden;
  margin: 0;
  padding: 0;
  width: 96px;
  height: 96px;
  font-size: 0;
  text-indent: -9999px;
  appearance: none;
  box-shadow: none;
  border-radius: none;
  border: none;
  cursor: pointer;
  transition: background 0.3s;
}

.c-hamburger:focus {
  outline: none;
}

.c-hamburger span {
  display: block;
  position: absolute;
  top: 44px;
  left: 18px;
  right: 18px;
  height: 8px;
  background: white;
}

.c-hamburger span::before,
.c-hamburger span::after {
  position: absolute;
  display: block;
  left: 0;
  width: 100%;
  height: 8px;
  background-color: #fff;
  content: "";
}

.c-hamburger span::before {
  top: -20px;
}

.c-hamburger span::after {
  bottom: -20px;
}

.c-hamburger {
  background-color: #ff3264;
}

.c-hamburger span {
  transition: background 0s 0.3s;
}

.c-hamburger span::before,
.c-hamburger span::after {
  transition-duration: 0.3s, 0.3s;
  transition-delay: 0.3s, 0s;
}

.c-hamburger span::before {
  transition-property: top, transform;
}

.c-hamburger span::after {
  transition-property: bottom, transform;
}

/* active state, i.e. menu open */
.c-hamburger.is-active {
  background-color: #cb0032;
}

.c-hamburger.is-active span {
  background: none;
}

.c-hamburger.is-active span::before {
  top: 0;
  transform: rotate(45deg);
}

.c-hamburger.is-active span::after {
  bottom: 0;
  transform: rotate(-45deg);
}

.c-hamburger.is-active span::before,
.c-hamburger.is-active span::after {
  transition-delay: 0s, 0.3s;
}

Button Javascript:

(function() {

  "use strict";

  var toggles = document.querySelectorAll(".c-hamburger");

  for (var i = toggles.length - 1; i >= 0; i--) {
    var toggle = toggles[i];
    toggleHandler(toggle);
  };

  function toggleHandler(toggle) {
    toggle.addEventListener( "click", function(e) {
      e.preventDefault();
      (this.classList.contains("is-active") === true) ? this.classList.remove("is-active") : this.classList.add("is-active");
    });
  }

})();

Navbar Javascript:

/* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */
function openNav() {
document.getElementById("mySidenav").style.width = "200px";
open = true;

}

/* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
open = false;

}

If someone can help me find the correct code to do this, or has a better idea, I would really appreciate it. I'm quite new to Javascript if you can't already tell.

Thanks!

Body:
I didn't quite get what you were up to. Did you mean that you wanted your NavBar to be closed when you click on a button not just only when clicking on the 'X'?

If it was so, in the HTML code, you simply need to add the onclick="closeNav();" to every button. Something like this

<button onclick = "closeNav();"> My Button </button>

Ok. Since you want the button to change into 'X' when the NavBar is open, you need to give your button an ID, then I think we could use the following Javascript condition.

HTML

<button id="myButton" class="c-hamburger c-hamburger--htx">
    <span>
        ::before
        "toggle menu"
        ::after
    </span>
</button><!--I copied from the site you provided-->

Javascript
I have edited your sidenav.js

function decide(){
  if(open == true){
    closeNav();
  }else{
    openNav();
  }
}

/* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */
function openNav() {
  document.getElementById("mySidenav").style.width = "200px";
  document.getElementById("myButton").classList.add("is-active");
  open = true;
}

/* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */
function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("myButton").classList.remove("is-active");
  open = false;
}


问:
Change FilePath of CS-Script AsmHelper Object
I am using the AsmHelper class in the CS-Script library. I am wondering how to only use one AsmHelper object and just change the filepath using CSScript.LoadCode so I can load a new script after the previous script is done, but with only one AsmHelper object. Right now, as shown below, I have four AsmHelper objects.

```<code>        AsmHelper transform1 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\parent.cs", null, true));
        ITransform engine1 = (ITransform)transform1.CreateObject("Script");

        AsmHelper transform2 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\bYear.cs", null, true));
        ITransform engine2 = (ITransform)transform2.CreateObject("Script");

        AsmHelper transform3 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\fInitial.cs", null, true));
        ITransform engine3 = (ITransform)transform3.CreateObject("Script");

        AsmHelper transform4 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\pet.cs", null, true));
        ITransform engine4 = (ITransform)transform4.CreateObject("Script");
</code>```

Here is the interface that goes with it if needed:

```<code>public interface ITransform
{
    User Transform(User record);
}
</code>```

If you need me to provide additional details, just ask below.

答:
You should not reuse AsmHelper. It was designed early days for a single script use-case. That's why it is IDisposable.

The AsmHelper rsponsibility is accessing script methods via 'Dispatch' invocation model, handling script specific assembly probing and unloading script assembly when it's loaded in  a remote AppDomain.

Since you are not using none of these features you are much better off by using newer APIs:

```<code>var engine1 = (ITransform)CSScript.LoadCode(@"CS-Scripts\parent.cs", null, true)
                                  .CreateObject("Script");

var engine2 = (ITransform)CSScript.LoadCode(@"CS-Scripts\bYear.cs", null, true)
                                  .CreateObject("Script");

var engine3 = (ITransform)CSScript.LoadCode(@"CS-Scripts\fInitial.cs", null, true)
                                  .CreateObject("Script");

var engine4 = (ITransform)CSScript.LoadCode(@"CS-Scripts\pet.cs", null, true)
                                  .CreateObject("Script");
</code>```

If you install CS-Script NuGet package it will add to your VS project a few sample files that demonstrate these techniques.

Body:
I am using the AsmHelper class in the CS-Script library. I am wondering how to only use one AsmHelper object and just change the filepath using CSScript.LoadCode so I can load a new script after the previous script is done, but with only one AsmHelper object. Right now, as shown below, I have four AsmHelper objects.

        AsmHelper transform1 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\parent.cs", null, true));
        ITransform engine1 = (ITransform)transform1.CreateObject("Script");

        AsmHelper transform2 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\bYear.cs", null, true));
        ITransform engine2 = (ITransform)transform2.CreateObject("Script");

        AsmHelper transform3 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\fInitial.cs", null, true));
        ITransform engine3 = (ITransform)transform3.CreateObject("Script");

        AsmHelper transform4 = new AsmHelper
            (CSScript.LoadCode(@"CS-Scripts\pet.cs", null, true));
        ITransform engine4 = (ITransform)transform4.CreateObject("Script");

Here is the interface that goes with it if needed:

public interface ITransform
{
    User Transform(User record);
}

If you need me to provide additional details, just ask below.

Body:
You should not reuse AsmHelper. It was designed early days for a single script use-case. That's why it is IDisposable.

The AsmHelper rsponsibility is accessing script methods via 'Dispatch' invocation model, handling script specific assembly probing and unloading script assembly when it's loaded in  a remote AppDomain.

Since you are not using none of these features you are much better off by using newer APIs:

var engine1 = (ITransform)CSScript.LoadCode(@"CS-Scripts\parent.cs", null, true)
                                  .CreateObject("Script");

var engine2 = (ITransform)CSScript.LoadCode(@"CS-Scripts\bYear.cs", null, true)
                                  .CreateObject("Script");

var engine3 = (ITransform)CSScript.LoadCode(@"CS-Scripts\fInitial.cs", null, true)
                                  .CreateObject("Script");

var engine4 = (ITransform)CSScript.LoadCode(@"CS-Scripts\pet.cs", null, true)
                                  .CreateObject("Script");

If you install CS-Script NuGet package it will add to your VS project a few sample files that demonstrate these techniques.


答:
try one of the following:

```<code>Where (model = @model OR
(@model IS NULL AND model <> model IN (1000,2000,3000,4000))
</code>```

OR

```<code>Where (model = @model OR (@model IS NULL AND model <> model <> 5000)
</code>```

Title: How can I filter by a subset of conditions based on a parameter in Microsoft SQL?

Body:
I have a parameter in an SQL query where I would like to select either a subset of possible rows, or one based on the parameter.

Basically, I have a column called model, which can contain either 1000, 2000, 3000, 4000, or 5000. When the parameter is set to NULL, I would like it to select just 1000, 2000 and 3000, but not 4000 or 5000.

I have tried various combinations of CASE statements, I.e.

WHERE model = CASE WHEN @model = NULL THEN model = 1000 OR model = 2000 OR
model = 3000 ELSE @model END AND <query continues>

How can I achieve this in SQL Server?

Body:
try one of the following:

Where (model = @model OR
(@model IS NULL AND model <> model IN (1000,2000,3000,4000))

OR

Where (model = @model OR (@model IS NULL AND model <> model <> 5000)


问:
Cannot connect to MongoDB via node.js in Docker
My node.js express app cannot connect to the MongoDB in a Docker. I'm not that familiar with Docker.

node.js connection:

```<code>import mongodb from 'mongodb';
...
mongodb.MongoClient.connect('mongodb://localhost:27017', ... );
</code>```

Dockerfile:

```<code>FROM node:argon
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "start"]
</code>```

docker-compose.yml

```<code>version: “2”
 services:
  web:
   build: .
   volumes:
     — ./:/app
   ports:
   — “3000:3000”
   links:
    — mongo
   mongo:
    image: mongo
    ports:
      — “27017:27017”
</code>```

Build command: docker build -t NAME .

Run command: docker run -ti -p 3000:3000 NAME

Connection error:

```<code>[MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]]
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]'
</code>```

答:
Try:

```<code>mongodb.MongoClient.connect('mongodb://mongo:27017', ... );
</code>```

Change your docker-compose.yml:

```<code>version: "2"

services:

  web:
    build: .
    volumes:
      - ./:/app
    ports:
      - "3000:3000"
    links:
      - mongo

  mongo:
    image: mongo
    ports:
      - "27017:27017"
</code>```

And use some docker compose commands:

```<code>docker-compose down
docker-compose build
docker-compose up -d mongo
docker-compose up web
</code>```

Body:
My node.js express app cannot connect to the MongoDB in a Docker. I'm not that familiar with Docker.

node.js connection:

import mongodb from 'mongodb';
...
mongodb.MongoClient.connect('mongodb://localhost:27017', ... );

Dockerfile:

FROM node:argon
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "start"]

docker-compose.yml

version: “2”
 services:
  web:
   build: .
   volumes:
     — ./:/app
   ports:
   — “3000:3000”
   links:
    — mongo
   mongo:
    image: mongo
    ports:
      — “27017:27017”

Build command: docker build -t NAME .

Run command: docker run -ti -p 3000:3000 NAME

Connection error:

[MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]]
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]'

Body:
Try:

mongodb.MongoClient.connect('mongodb://mongo:27017', ... );

Change your docker-compose.yml:

version: "2"

services:

  web:
    build: .
    volumes:
      - ./:/app
    ports:
      - "3000:3000"
    links:
      - mongo

  mongo:
    image: mongo
    ports:
      - "27017:27017"

And use some docker compose commands:

docker-compose down
docker-compose build
docker-compose up -d mongo
docker-compose up web


问:
How does the inner loop append on each iteration?
```<code>def per1(seq):
    if not seq:
        return [seq]
    else:
        res=[]
        for i in range(len(seq)):
            rest=seq[:i]+seq[i+1:]
            for x in per1(rest):
                 res.append(seq[i:i+1]+x)

        return res

print(per1('abc'))
</code>```

The function is to print a permuted list of sequence but I am not sure how the inner for loop is working. I have tried to use trace() to see how the control is moving thru the loop but I couldn't figure how the loop is working the second time. The first time, ' rest ' value is 'bc','c'.

答:
Each time through the for i loop, rest is set to the input string with one character removed. The first time it has the first character removed, the second time it has the second character removed, etc. seq[:i] is every character before i, and seq[i+1:] is every character after i.

Then it calls itself recursively on rest. This returns all the permutations of that shorter string. So when rest is "bc", this returns ["bc", "cb"]. The for x loop iterates through this list, and concatenates each one to seq[i:i+1] (which is the character that was removed when creating rest), and appends this to res.

So the first iteration of the main loop sets rest to "bc", then appends "abc" and "acb" to res.

The second iteration does the same thing, with rest set to "ac", and seq[i:i+1] being the missing character "b", so it appends "bac" and "bca" to res.

The third iteration is similar, with rest set to "ab", so it appends "cab" and "cba" to res.

The special situation is the base case of the recursion. If the input string is empty, we just return a list with that empty string -- an empty string has trivial permutations. When the caller does its for x loop, it will simply concatenate this empty string onto the current letter. This case is needed to prevent infinite recursion. You could also make the case where len(seq) == 1 the base case, since the permutations of a single letter is also trivial.

Body:
def per1(seq):
    if not seq:
        return [seq]
    else:
        res=[]
        for i in range(len(seq)):
            rest=seq[:i]+seq[i+1:]
            for x in per1(rest):
                 res.append(seq[i:i+1]+x)

        return res

print(per1('abc'))

The function is to print a permuted list of sequence but I am not sure how the inner for loop is working. I have tried to use trace() to see how the control is moving thru the loop but I couldn't figure how the loop is working the second time. The first time, ' rest ' value is 'bc','c'.


问:
C++ member initialization from derived class to base class
Let's see the following C++ codes.
Each inherited class has its member variables and initialization function.
These member variables are some different(almost same type) between inherited classes.
Is there any good way to move (or merge) this initialization into base class?</p>

```<code>class Base {
public:
   virtual init() = 0;
}
class A: public Base {
public:
   int a1;
   void init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
   void init() { b1 = 1;}
}
</code>```

答:
Maybe you could use the template class skills to solve the problem. Like:

```<code>template <typename T> class Base {
public :
  virtual void init( T t ) = 0;
};

class A: public Base<T> {
public:
   T a1;
   void init( T t ) { a1 = t;}
}

class B: public Base<T> {
public:
   T b1;
   void init( T t ) { b1 = t;}
}
</code>```

You could have a try.

Body:
Let's see the following C++ codes.
Each inherited class has its member variables and initialization function.
These member variables are some different(almost same type) between inherited classes.
Is there any good way to move (or merge) this initialization into base class?

class Base {
public:
   virtual init() = 0;
}
class A: public Base {
public:
   int a1;
   void init() { a1 = 0;}
}
class B: public Base {
public:
   int b1;
   void init() { b1 = 1;}
}

Body:
Maybe you could use the template class skills to solve the problem. Like:

template <typename T> class Base {
public :
  virtual void init( T t ) = 0;
};

class A: public Base<T> {
public:
   T a1;
   void init( T t ) { a1 = t;}
}

class B: public Base<T> {
public:
   T b1;
   void init( T t ) { b1 = t;}
}

You could have a try.


问:
Bootstrap 4 fixed bottom navbar
My current navbar is:

page 1

page 2

page 3

```

How do I make it so that, even if there is not enough content to "push" it down, it is still at the bottom? navbar-fixed-bottom does not work because it overlaps with content if it reaches the bottom.

答:
That's what "fixed" does, it goes in front of the other elements not below them. Just put a couple of blank lines at the bottom of your page, or better, add a CSS padding-bottom to your page container.

Here is an example, adjust the padding value to what you want:

.page-container {
  padding-bottom: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" />
<nav class="navbar navbar-inverse navbar-fixed-bottom">
  <div class="container">
    <ul class="nav navbar-nav">
      <li>page 1</li>
      <li>page 2</li>
      <li>page 3</li>
    </ul>
  </div>
</nav>
<div class="page-container">
  <p>first line</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>last line</p>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: Bootstrap 4 fixed bottom navbar

Body:
My current navbar is:

page 1

page 2

page 3

How do I make it so that, even if there is not enough content to "push" it down, it is still at the bottom? navbar-fixed-bottom does not work because it overlaps with content if it reaches the bottom.

Body:
That's what "fixed" does, it goes in front of the other elements not below them. Just put a couple of blank lines at the bottom of your page, or better, add a CSS padding-bottom to your page container.

Here is an example, adjust the padding value to what you want:

.page-container {
  padding-bottom: 200px;
}

<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" />
<nav class="navbar navbar-inverse navbar-fixed-bottom">
  <div class="container">
    <ul class="nav navbar-nav">
      <li><a href="">page 1</a></li>
      <li><a href="">page 2</a></li>
      <li><a href="">page 3</a></li>
    </ul>
  </div>
</nav>
<div class="page-container">
  <p>first line</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>content</p>
  <p>last line</p>
</div>


问:
Spring Cloud Data Flow does not work how is expected for file sink and curl client
In Mac, working with Spring XD

1.3.2.RELEASE

The following works fine:

stream create --name orderFilter --definition "http --port=9090 | filter --expression=#jsonPath(payload,'$.countryCode').equals('US') | file --name=manolito.txt --dir=/Users/manueljordan/Desktop --mode=APPEND" --deploy

Through its own shell the following works:

```<code>http post --target http://localhost:9090 --data "{\"id\":\"2773\",\"countryCode\":\"US\",\"orderAmt\":\"100\"}"
http post --target http://localhost:9090 --data "{\"id\":\"2774\",\"countryCode\":\"CA\",\"orderAmt\":\"125\"}"
http post --target http://localhost:9090 --data "{\"id\":\"2775\",\"countryCode\":\"US\",\"orderAmt\":\"110\"}"
</code>```

The data is filtered and the output is located in /Users/manueljordan/Desktop how is expected.

Until here all is ok.

Now migrating to Spring Cloud Data Flow working with

spring-cloud-dataflow-server-local-1.2.2.RELEASE.jar

spring-cloud-dataflow-shell-1.2.2.RELEASE.jar

Through the GUI (http://localhost:9393/dashboard/index.html#/streams/definitions) I can create the same stream.

Again through the shell (from spring-cloud-dataflow-shell) the following works:

```<code>  http post --target http://localhost:9090 --data "{\"id\":\"2773\",\"countryCode\":\"US\",\"orderAmt\":\"100\"}"
  http post --target http://localhost:9090 --data "{\"id\":\"2774\",\"countryCode\":\"CA\",\"orderAmt\":\"125\"}"
  http post --target http://localhost:9090 --data "{\"id\":\"2775\",\"countryCode\":\"US\",\"orderAmt\":\"110\"}"
</code>```

The same http post used for Spring XD

Situation 01 even when the three http post from above work about the filter behaviour, the output file is not created in /Users/manueljordan/Desktop, it is created in /private/var/folders/nf/ql69b5zd7w54jw6nb5zmvck80000gn/T/dataflow/output instead

Observe the dataflow directory within ql69b5zd7w54jw6nb5zmvck80000gn

Why this behaviour? How fix this?, some special configuration missing?

Situation 02 about cURL, according with the reference documentation, in the 10.1. Endpoints section, just practically below the Figure 3. The Spring Cloud Data Flow Server shows that cURL can be used too.

Through iterm 2 if I use the following commands: (it according with How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?)

```<code>curl -H "Content-Type: application/json" -X POST -d '"{\"id\":\"2773\",\"countryCode\":\"US\",\"orderAmt\":\"100\"}"' http://localhost:9090
curl -H "Content-Type: application/json" -X POST -d '"{\"id\":\"2774\",\"countryCode\":\"CA\",\"orderAmt\":\"125\"}"' http://localhost:9090
curl -H "Content-Type: application/json" -X POST -d '"{\"id\":\"2775\",\"countryCode\":\"US\",\"orderAmt\":\"110\"}"' http://localhost:9090
</code>```

Nothing happens (I press enter to execute the command and just pass to the new line prompt, that's all). Why? what is missing?

答:
See answer here: https://github.com/spring-cloud/spring-cloud-dataflow/issues/1587#issuecomment-313266803

We monitor both SO and GitHub issues so no need to cross-post.

-Thomas

Body:
In Mac, working with Spring XD

1.3.2.RELEASE

The following works fine:

stream create --name orderFilter --definition "http --port=9090 | filter --expression=#jsonPath(payload,'$.countryCode').equals('US') | file --name=manolito.txt --dir=/Users/manueljordan/Desktop --mode=APPEND" --deploy

Through its own shell the following works:

http post --target http://localhost:9090 --data "{\"id\":\"2773\",\"countryCode\":\"US\",\"orderAmt\":\"100\"}"
http post --target http://localhost:9090 --data "{\"id\":\"2774\",\"countryCode\":\"CA\",\"orderAmt\":\"125\"}"
http post --target http://localhost:9090 --data "{\"id\":\"2775\",\"countryCode\":\"US\",\"orderAmt\":\"110\"}"

The data is filtered and the output is located in /Users/manueljordan/Desktop how is expected.

Until here all is ok.

Now migrating to Spring Cloud Data Flow working with

spring-cloud-dataflow-server-local-1.2.2.RELEASE.jar

spring-cloud-dataflow-shell-1.2.2.RELEASE.jar

Through the GUI (http://localhost:9393/dashboard/index.html#/streams/definitions) I can create the same stream.

Again through the shell (from spring-cloud-dataflow-shell) the following works:

  http post --target http://localhost:9090 --data "{\"id\":\"2773\",\"countryCode\":\"US\",\"orderAmt\":\"100\"}"
  http post --target http://localhost:9090 --data "{\"id\":\"2774\",\"countryCode\":\"CA\",\"orderAmt\":\"125\"}"
  http post --target http://localhost:9090 --data "{\"id\":\"2775\",\"countryCode\":\"US\",\"orderAmt\":\"110\"}"

The same http post used for Spring XD

Situation 01 even when the three http post from above work about the filter behaviour, the output file is not created in /Users/manueljordan/Desktop, it is created in /private/var/folders/nf/ql69b5zd7w54jw6nb5zmvck80000gn/T/dataflow/output instead

Observe the dataflow directory within ql69b5zd7w54jw6nb5zmvck80000gn

Why this behaviour? How fix this?, some special configuration missing?

Situation 02 about cURL, according with the reference documentation, in the 10.1. Endpoints section, just practically below the Figure 3. The Spring Cloud Data Flow Server shows that cURL can be used too.

Through iterm 2 if I use the following commands: (it according with How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?)

curl -H "Content-Type: application/json" -X POST -d '"{\"id\":\"2773\",\"countryCode\":\"US\",\"orderAmt\":\"100\"}"' http://localhost:9090
curl -H "Content-Type: application/json" -X POST -d '"{\"id\":\"2774\",\"countryCode\":\"CA\",\"orderAmt\":\"125\"}"' http://localhost:9090
curl -H "Content-Type: application/json" -X POST -d '"{\"id\":\"2775\",\"countryCode\":\"US\",\"orderAmt\":\"110\"}"' http://localhost:9090

Nothing happens (I press enter to execute the command and just pass to the new line prompt, that's all). Why? what is missing?