问:
Python: Calling a function inside another function with returned values: Error Handling?
I have created the following Python module that converts 24hr time (00:00 to 23:59) into words. Function1() tests that the input string matches the correct 24hr format before trying to extract the 12hours, minutes and period (i.e. am = 'before midday' and pm = 'after midday'). The following works perfectly as a standalone function, but fails when I call it from function3() when the input string doesn't match the correct format and the try statement doens't execute therefore the return values are not returned. Function3() therefore fails as the following return values don't exist. How do I restructure function1() so that if the pattern doesn't match, the Python module stops running and only executes the else statement in function1() letting the end user know that the input string doesn't match the correct format?

```<code>"""
Created on 29 May 2017

Convert 24hr format time

into time as words

@author: PeterW
"""
# import site-packages and modules
import re
import time
import argparse

def function1(input_time):
    """convert time from 24hr format
    into 12hours, minutes, period"""
    period_type = {'AM': 'before midday', 'PM': 'after midday'}
    regexp_object = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|23:59)$')
    if regexp_object.match(input_time):
        try:
            time_object = time.strptime(input_time, '%H:%M')
            suffix = time.strftime('%p', time_object)
            hours = int(time.strftime('%I', time_object))
            minutes = time_object[4]
            period = period_type.get(suffix)
            print("{0}:{1} {2}".format(hours, str(minutes).zfill(2), period))
            return hours, minutes, period
        except ValueError as err:
            print(err)
    else:
        print("{0} doesn't match required format 00:00 to 23:59"
              .format(input_time))

def function2():
    """create dictionary
    to lookup equivalent word
    of integer number"""
    words_lookup = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
                    6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
                    11: 'eleven', 12: 'twelve', 13: 'thirteen',
                    14: 'fourteen', 16: 'sixteen', 17: 'seventeen',
                    18: 'eighteen', 19: 'nineteen', 20: 'twenty',
                    21: 'twenty one', 22: 'twenty two', 23: 'twenty three',
                    24: 'twenty four', 25: 'twenty five', 26: 'twenty six',
                    27: 'twenty seven', 28: 'twenty eight', 29: 'twenty nine'}
    return words_lookup

def function3(input_time):
    """convert 24hr format time
    into time as words"""
    hours, minutes, period = function1(input_time)
    words_lookup = function2()
    if hours == 12:
        hours2 = words_lookup.get(1)
    else:
        hours2 = words_lookup.get(hours+1)
    if hours == 12 and minutes == 0 and period == 'before midday':
        time = 'Midnight'
    elif hours == 12 and minutes == 0 and period == 'after midday':
        time = 'Midday'
    elif minutes == 0:
        time = "{0} o'clock {1}.".format(str(words_lookup.get(hours)).title(),
                                         period)
    elif minutes == 15:
        time = "Quarter past {0} {1}.".format(words_lookup.get(hours),
                                              period)
    elif minutes == 30:
        time = "Half past {0} {1}.".format(words_lookup.get(hours),
                                           period)
    elif minutes == 45:
        time = "Quarter to {0} {1}.".format(hours2,
                                            period)
    elif minutes < 30:
        minutes = str(words_lookup.get(minutes)).capitalize()
        time = "{0} minutes past {1} {2}.".format(minutes,
                                                  words_lookup.get(hours),
                                                  period)
    else:
        minutes = str(words_lookup.get(60 - minutes)).capitalize()
        time = '{0} minutes to {1} {2}.'.format(minutes,
                                                hours2,
                                                period)
    print(time)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Convert 24hr format time into time as words")
    parser.add_argument('--input_time', metavar='string', required=True,
                        help='input time in following format 00:00 to 23:59')
    args = parser.parse_args()
    function3(input_time=args.input_time)
</code>```

Final version below, thanks for the help.

```<code>"""
Created on 04 June 2017

Convert 24hr format time

into time as words

@author: PeterW
"""
# import site-packages and modules
import sys
import re
import time
import argparse

def validate_time_format(input_time):
    """Validate that input string
    matches require 24hr time format"""
    regexp_object = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|23:59)$')
    if regexp_object.match(input_time):
        print("Processing: {0} into words".format(input_time))
        time_str = input_time
    else:
        print("{0} doesn't match required input format: 00:00 to 23:59".format(input_time))
        sys.exit()
    return time_str

def extract_time(time_str):
    """convert time from 24hr format
    into 12hours, minutes, period"""
    period_type = {'AM': 'before midday', 'PM': 'after midday'}
    try:
        time_object = time.strptime(time_str, '%H:%M')
        suffix = time.strftime('%p', time_object)
        hours = int(time.strftime('%I', time_object))
        minutes = time_object[4]
        period = period_type.get(suffix)
#         print("{0}:{1} {2}".format(hours, str(minutes).zfill(2), period))
        return hours, minutes, period
    except ValueError as err:
        print(err)

def time_lookup():
    """create dictionary
    to lookup equivalent word
    of integer number"""
    words_lookup = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
                    6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
                    11: 'eleven', 12: 'twelve', 13: 'thirteen',
                    14: 'fourteen', 16: 'sixteen', 17: 'seventeen',
                    18: 'eighteen', 19: 'nineteen', 20: 'twenty',
                    21: 'twenty one', 22: 'twenty two', 23: 'twenty three',
                    24: 'twenty four', 25: 'twenty five', 26: 'twenty six',
                    27: 'twenty seven', 28: 'twenty eight', 29: 'twenty nine'}
    return words_lookup

def time_as_words(input_time):
    """convert 24hr format time
    into time as words"""
    time_str = validate_time_format(input_time)
    hours, minutes, period = extract_time(time_str)
    words_lookup = time_lookup()
    if hours == 12:
        hours2 = words_lookup.get(1)
    else:
        hours2 = words_lookup.get(hours+1)
    if hours == 12 and minutes == 0 and period == 'before midday':
        time = 'Midnight'
    elif hours == 12 and minutes == 0 and period == 'after midday':
        time = 'Midday'
    elif minutes == 0:
        time = "{0} o'clock {1}.".format(str(words_lookup.get(hours)).title(),
                                         period)
    elif minutes == 15:
        time = "Quarter past {0} {1}.".format(words_lookup.get(hours),
                                              period)
    elif minutes == 30:
        time = "Half past {0} {1}.".format(words_lookup.get(hours),
                                           period)
    elif minutes == 45:
        time = "Quarter to {0} {1}.".format(hours2,
                                            period)
    elif minutes < 30:
        min_str = str(words_lookup.get(minutes)).capitalize()
        time = "{0} minute{1} past {2} {3}.".format(min_str,
                                                    "" if minutes == 1 else "s",
                                                    words_lookup.get(hours),
                                                    period)
    else:
        min_str = str(words_lookup.get(60 - minutes)).capitalize()
        time = '{0} minute{1} to {2} {3}.'.format(min_str,
                                                  "" if 60 - minutes == 1 else "s",
                                                  hours2,
                                                  period)
    print(time)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Convert 24hr format time into time as words")
    parser.add_argument("-t", "--input_time", metavar="time", type=str, required=True,
                        help='input time in the following format 00:00 to 23:59')
    args = parser.parse_args()
    time_as_words(input_time=args.input_time)
</code>```

答:
When your function1 fails, it implicitly returns a None. The caller has to be aware of this possibility:

```<code>retval = function1(input_time)
if retval is None:
    # do something - say, exit
else:
    hours, minutes, period = retval
</code>```

Body:
I have created the following Python module that converts 24hr time (00:00 to 23:59) into words. Function1() tests that the input string matches the correct 24hr format before trying to extract the 12hours, minutes and period (i.e. am = 'before midday' and pm = 'after midday'). The following works perfectly as a standalone function, but fails when I call it from function3() when the input string doesn't match the correct format and the try statement doens't execute therefore the return values are not returned. Function3() therefore fails as the following return values don't exist. How do I restructure function1() so that if the pattern doesn't match, the Python module stops running and only executes the else statement in function1() letting the end user know that the input string doesn't match the correct format?

"""
Created on 29 May 2017

Convert 24hr format time

into time as words

@author: PeterW
"""
# import site-packages and modules
import re
import time
import argparse

def function1(input_time):
    """convert time from 24hr format
    into 12hours, minutes, period"""
    period_type = {'AM': 'before midday', 'PM': 'after midday'}
    regexp_object = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|23:59)$')
    if regexp_object.match(input_time):
        try:
            time_object = time.strptime(input_time, '%H:%M')
            suffix = time.strftime('%p', time_object)
            hours = int(time.strftime('%I', time_object))
            minutes = time_object[4]
            period = period_type.get(suffix)
            print("{0}:{1} {2}".format(hours, str(minutes).zfill(2), period))
            return hours, minutes, period
        except ValueError as err:
            print(err)
    else:
        print("{0} doesn't match required format 00:00 to 23:59"
              .format(input_time))

def function2():
    """create dictionary
    to lookup equivalent word
    of integer number"""
    words_lookup = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
                    6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
                    11: 'eleven', 12: 'twelve', 13: 'thirteen',
                    14: 'fourteen', 16: 'sixteen', 17: 'seventeen',
                    18: 'eighteen', 19: 'nineteen', 20: 'twenty',
                    21: 'twenty one', 22: 'twenty two', 23: 'twenty three',
                    24: 'twenty four', 25: 'twenty five', 26: 'twenty six',
                    27: 'twenty seven', 28: 'twenty eight', 29: 'twenty nine'}
    return words_lookup

def function3(input_time):
    """convert 24hr format time
    into time as words"""
    hours, minutes, period = function1(input_time)
    words_lookup = function2()
    if hours == 12:
        hours2 = words_lookup.get(1)
    else:
        hours2 = words_lookup.get(hours+1)
    if hours == 12 and minutes == 0 and period == 'before midday':
        time = 'Midnight'
    elif hours == 12 and minutes == 0 and period == 'after midday':
        time = 'Midday'
    elif minutes == 0:
        time = "{0} o'clock {1}.".format(str(words_lookup.get(hours)).title(),
                                         period)
    elif minutes == 15:
        time = "Quarter past {0} {1}.".format(words_lookup.get(hours),
                                              period)
    elif minutes == 30:
        time = "Half past {0} {1}.".format(words_lookup.get(hours),
                                           period)
    elif minutes == 45:
        time = "Quarter to {0} {1}.".format(hours2,
                                            period)
    elif minutes < 30:
        minutes = str(words_lookup.get(minutes)).capitalize()
        time = "{0} minutes past {1} {2}.".format(minutes,
                                                  words_lookup.get(hours),
                                                  period)
    else:
        minutes = str(words_lookup.get(60 - minutes)).capitalize()
        time = '{0} minutes to {1} {2}.'.format(minutes,
                                                hours2,
                                                period)
    print(time)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Convert 24hr format time into time as words")
    parser.add_argument('--input_time', metavar='string', required=True,
                        help='input time in following format 00:00 to 23:59')
    args = parser.parse_args()
    function3(input_time=args.input_time)

Final version below, thanks for the help.

"""
Created on 04 June 2017

Convert 24hr format time

into time as words

@author: PeterW
"""
# import site-packages and modules
import sys
import re
import time
import argparse

def validate_time_format(input_time):
    """Validate that input string
    matches require 24hr time format"""
    regexp_object = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|23:59)$')
    if regexp_object.match(input_time):
        print("Processing: {0} into words".format(input_time))
        time_str = input_time
    else:
        print("{0} doesn't match required input format: 00:00 to 23:59".format(input_time))
        sys.exit()
    return time_str

def extract_time(time_str):
    """convert time from 24hr format
    into 12hours, minutes, period"""
    period_type = {'AM': 'before midday', 'PM': 'after midday'}
    try:
        time_object = time.strptime(time_str, '%H:%M')
        suffix = time.strftime('%p', time_object)
        hours = int(time.strftime('%I', time_object))
        minutes = time_object[4]
        period = period_type.get(suffix)
#         print("{0}:{1} {2}".format(hours, str(minutes).zfill(2), period))
        return hours, minutes, period
    except ValueError as err:
        print(err)

def time_lookup():
    """create dictionary
    to lookup equivalent word
    of integer number"""
    words_lookup = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
                    6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
                    11: 'eleven', 12: 'twelve', 13: 'thirteen',
                    14: 'fourteen', 16: 'sixteen', 17: 'seventeen',
                    18: 'eighteen', 19: 'nineteen', 20: 'twenty',
                    21: 'twenty one', 22: 'twenty two', 23: 'twenty three',
                    24: 'twenty four', 25: 'twenty five', 26: 'twenty six',
                    27: 'twenty seven', 28: 'twenty eight', 29: 'twenty nine'}
    return words_lookup

def time_as_words(input_time):
    """convert 24hr format time
    into time as words"""
    time_str = validate_time_format(input_time)
    hours, minutes, period = extract_time(time_str)
    words_lookup = time_lookup()
    if hours == 12:
        hours2 = words_lookup.get(1)
    else:
        hours2 = words_lookup.get(hours+1)
    if hours == 12 and minutes == 0 and period == 'before midday':
        time = 'Midnight'
    elif hours == 12 and minutes == 0 and period == 'after midday':
        time = 'Midday'
    elif minutes == 0:
        time = "{0} o'clock {1}.".format(str(words_lookup.get(hours)).title(),
                                         period)
    elif minutes == 15:
        time = "Quarter past {0} {1}.".format(words_lookup.get(hours),
                                              period)
    elif minutes == 30:
        time = "Half past {0} {1}.".format(words_lookup.get(hours),
                                           period)
    elif minutes == 45:
        time = "Quarter to {0} {1}.".format(hours2,
                                            period)
    elif minutes < 30:
        min_str = str(words_lookup.get(minutes)).capitalize()
        time = "{0} minute{1} past {2} {3}.".format(min_str,
                                                    "" if minutes == 1 else "s",
                                                    words_lookup.get(hours),
                                                    period)
    else:
        min_str = str(words_lookup.get(60 - minutes)).capitalize()
        time = '{0} minute{1} to {2} {3}.'.format(min_str,
                                                  "" if 60 - minutes == 1 else "s",
                                                  hours2,
                                                  period)
    print(time)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Convert 24hr format time into time as words")
    parser.add_argument("-t", "--input_time", metavar="time", type=str, required=True,
                        help='input time in the following format 00:00 to 23:59')
    args = parser.parse_args()
    time_as_words(input_time=args.input_time)

Body:
When your function1 fails, it implicitly returns a None. The caller has to be aware of this possibility:

retval = function1(input_time)
if retval is None:
    # do something - say, exit
else:
    hours, minutes, period = retval


来源: stackexchange

问:
Microservices: model sharing between bounded contexts
I am currently building a microservices-based application developed with the mean stack and am running into several situations where I need to share models between bounded contexts.

As an example, I have a User service that handles the registration process as well as login(generate jwt), logout, etc.  I also have an File service which handles the uploading of profile pics and other images the user happens to upload.  Additionally, I have an Friends service that keeps track of the associations between members.

Currently, I am adding the guid of the user from the user table used by the User service as well as the first, middle and last name fields to the File table and the Friend table.  This way I can query for these fields whenever I need them in the other services(Friend and File) without needing to make any rest calls to get the information every time it is queried.

Here is the caveat:

The downside seems to be that I have to, I chose seneca with rabbitmq, notify the File and Friend tables whenever a user updates their information from the User table.

1) Should I be worried about the services getting too chatty?

2) Could this lead to any performance issues, if alot of updates take place over an hour, let's say?

3) in trying to isolate boundaries, I just am not seeing another way of pulling this off.  What is the recommended approach to solving this issue and am I on the right track?

答:
If you are worry about a high volume of messages and high TPS for example 100,000 TPS for producing and consuming events I suggest that Instead of using RabbitMQ use apache Kafka or NATS (Go version because NATS has Rubby version also) in order to support a high volume of messages per second.

Also Regarding Database design you should design each micro-service base business capabilities and bounded-context according to domain driven design (DDD). so because unlike SOA it is suggested that each micro-service should has its own database then you should not be worried about normalization because you may have to repeat many structures, fields, tables and features for each microservice in order to keep them Decoupled from each other and letting them work independently to raise Availability and having scalability.

Also you can use Event sourcing + CQRS technique or Transaction Log Tailing to circumvent 2PC (2 Phase Commitment) - which is not recommended when implementing microservices - in order to exchange events between your microservices and manipulating states to have Eventual Consistency according to CAP theorem.

ContentLicense: CC BY-SA 3.0


问:
Invalid JSON, 400 Bad request in Angular $http.post
This is my data object -

var bill = {
                 "type":"insert",
                 "args": {
                    "table": "finance_data",
                    "objects": [
                    {
                      "title": $scope.data.title,
                      "url": $scope.data.url,
                      "type":"payments"
                    }
                  ]
                }
            };```
</div>
</div>
</p>

<p>This is my config object-</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var config = {
                  headers:{
                    'Authorization' : "Bearer "+ $localStorage.auth_token,
                }
             };</code>```

I'm doing a POST request to my server to insert data into a table ( db: PostgreSQL)
This is my http request code-

$http.post('https://data.saarang.org/v1/query', bill, config).then(function(response){
                console.log('success');
                alert('Successfully uploaded the Payment Receipt!');
                $state.reload();
             }).catch(function(err){
                console.log(err);
            });```
</div>
</div>

This is the err object -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Object { data: Object, status: 400, headers: headersGetter/<(), config: Object, statusText: "Bad Request" }</code>```

The err.data object has an error message - 'invalid JSON'
The bill object has all the fields that are required but still the server throws back an "invalid JSON" error
Please Help !

答: I found the solution myself, it wasn't any backend/server related issue, the url key in the object was supposed to be Url. The typo caused an invalid JSON error.

Body:
This is my data object -

var bill = {
                 "type":"insert",
                 "args": {
                    "table": "finance_data",
                    "objects": [
                    {
                      "title": $scope.data.title,
                      "url": $scope.data.url,
                      "type":"payments"
                    }
                  ]
                }
            };

This is my config object-

var config = {
                  headers:{
                    'Authorization' : "Bearer "+ $localStorage.auth_token,
                }
             };

I'm doing a POST request to my server to insert data into a table ( db: PostgreSQL)
This is my http request code-

$http.post('https://data.saarang.org/v1/query', bill, config).then(function(response){
                console.log('success');
                alert('Successfully uploaded the Payment Receipt!');
                $state.reload();
             }).catch(function(err){
                console.log(err);
            });

This is the err object -

Object { data: Object, status: 400, headers: headersGetter/<(), config: Object, statusText: "Bad Request" }

The err.data object has an error message - 'invalid JSON'
The bill object has all the fields that are required but still the server throws back an "invalid JSON" error
Please Help !


问:
Onclick event on a div not working
Here is my code :

```<code><script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
function klikaj() {
var title = $('inlineBlock _2tga _3e2a').attr('title');
document.getElementById('log').innerHTML += " "+ title + "titi" ;
};
$('.fbb').click(function (evt) {
 alert('123');
});
</script>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9&appId=132911310473896";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
  <!-- Load Facebook SDK for JavaScript -->
<div class="fbb">
  <div id="fb-root"></div>

  <!-- Your like button code -->
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="like" data-size="large" data-show-faces="true" data-share="true" ></div>
</div>
<div id="log">initial content</div>
</code>```

I would like to activate the alert('123') when everything in the fbb div is clicked.

I've tried to add the .click(function (evt) but it's not working

if anyone have any idea

Thanks and regards

答: There's no content in the div, so there's no way to click in it. Either add some content, or set its width and height through css/style attribute </p>

Title: Onclick event on a div not working

Body:
Here is my code :

initial content

I would like to activate the alert('123') when everything in the fbb div is clicked.

I've tried to add the .click(function (evt) but it's not working

if anyone have any idea

Thanks and regards


问:
How to Per-Request caching in ASP.net core
My old code looks like this:

public static class DbHelper {
    // One conection per request
    public static Database CurrentDb() {
        if (HttpContext.Current.Items["CurrentDb"] == null) {
            var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
            HttpContext.Current.Items["CurrentDb"] = retval;
            return retval;
        }
        return (Database)HttpContext.Current.Items["CurrentDb"];
    }
}
```

Since we don't have HttpContext anymore easily accesible in core, how can I achieve the same thing?

I need to access CurrentDb() easily from everywhere

Would like to use something like MemoryCache, but with Request lifetime. DI it's not an option for this project

答:
There are at least 3 options to store an object per-request in ASP.NET Core:

1. Dependency Injection

You could totally re-design that old code: use the built-in DI and register a Database instance as scoped (per web-request) with the following factory method:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<Database>((provider) =>
    {
        return new DatabaseWithMVCMiniProfiler("MainConnectionString");
    });
}
</code>```

Introduction to Dependency Injection in ASP.NET Core

.NET Core Dependency Injection Lifetimes Explained

2. HttpContext.Items

This collection is available from the start of an HttpRequest and is discarded at the end of each request.

Working with HttpContext.Items

3. AsyncLocal<T>

Store a value per a current async context (a kind of [ThreadStatic] with async support). This is how HttpContext is actually stored: HttpContextAccessor.

What's the effect of AsyncLocal<T> in non async/await code?

ThreadStatic in asynchronous ASP.NET Web API

ContentLicense: CC BY-SA 4.0

Body:
My old code looks like this:

public static class DbHelper {
    // One conection per request
    public static Database CurrentDb() {
        if (HttpContext.Current.Items["CurrentDb"] == null) {
            var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
            HttpContext.Current.Items["CurrentDb"] = retval;
            return retval;
        }
        return (Database)HttpContext.Current.Items["CurrentDb"];
    }
}

Since we don't have HttpContext anymore easily accesible in core, how can I achieve the same thing?

I need to access CurrentDb() easily from everywhere

Would like to use something like MemoryCache, but with Request lifetime. DI it's not an option for this project

Body:
There are at least 3 options to store an object per-request in ASP.NET Core:

1. Dependency Injection

You could totally re-design that old code: use the built-in DI and register a Database instance as scoped (per web-request) with the following factory method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<Database>((provider) =>
    {
        return new DatabaseWithMVCMiniProfiler("MainConnectionString");
    });
}

Introduction to Dependency Injection in ASP.NET Core

.NET Core Dependency Injection Lifetimes Explained

2. HttpContext.Items

This collection is available from the start of an HttpRequest and is discarded at the end of each request.

Working with HttpContext.Items

3. AsyncLocal<T>

Store a value per a current async context (a kind of [ThreadStatic] with async support). This is how HttpContext is actually stored: HttpContextAccessor.

What's the effect of AsyncLocal<T> in non async/await code?

ThreadStatic in asynchronous ASP.NET Web API


问:
How to reverse modified string back into MD5 hash given the method used to modify the string?
I am working with some MD5 hashes that have been turned into number sequences using the methods shown below. Given the code and example hash below, how can I "reverse" the effect of the getString() method and turn a numerical sequence back into an MD5 hash?

For example, encrypt("umadbro"); returns "1518918615824625494170109603025017352201241" because the MD5 hash is passed through the getString() method. The MD5 hash for "umadbro" is 9759ba9ef6fe5eaa6d3c1efaad34c9f1. I need a method that takes a string of numbers modified by the getString() method and converts it into its MD5 hash. For example: reverseMethod("1518918615824625494170109603025017352201241"); should output "9759ba9ef6fe5eaa6d3c1efaad34c9f1" (The input parameter is the modified string of numbers and the output is the MD5 hash of the original string). NOTE: I am not looking for a method to crack the MD5 hash. I only need a method that reverses the effect of the getString() method shown below.

```<code>    public String encrypt(String source)
        {
            try
            {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] bytes = md.digest(source.getBytes());
                return getString(bytes);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

    private String getString(byte[] bytes) //this takes an md5 hash and turns it into a string of numbers.
    // How can I reverse the effect of this method?
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++)
        {
            byte b = bytes[i];
            sb.append(0xFF & b);
        }
        return sb.toString();
}
</code>```

答:
I tried to write some code that finds all possible combinations and it turned out there are a lot less then I anticipated. Only 2 in this case. And it takes very little time to find them.

```<code>import java.util.ArrayList;
import java.util.Arrays;

public class Comb {
  static long combinations(String str, int startIdx, int numBytes, ArrayList<byte[]> combinations, byte[] combination) {
    if(startIdx >= str.length()) {
       if(numBytes == 16) {
         combinations.add(combination.clone());
         return 1;
       } else return 0;
    }
    if(numBytes > 15) return 0;
    combination[numBytes] = (byte)(str.charAt(startIdx) - '0');
    long result = combinations(str, startIdx + 1, numBytes + 1, combinations, combination);
    if(startIdx < str.length() - 1 && str.charAt(startIdx) != '0') {
      combination[numBytes] = (byte)((str.charAt(startIdx) - '0') * 10 + (str.charAt(startIdx + 1) - '0'));
      result += combinations(str, startIdx + 2, numBytes + 1, combinations, combination);
    }
    if(startIdx < str.length() - 2) {
      combination[numBytes] = (byte)((str.charAt(startIdx) - '0') * 100 + (str.charAt(startIdx + 1) - '0') * 10 + (str.charAt(startIdx + 2) - '0'));
      if(str.charAt(startIdx) == '1') result += combinations(str, startIdx + 3, numBytes + 1, combinations, combination);
      if(str.charAt(startIdx) == '2' &&
        (str.charAt(startIdx + 1) < '5' || str.charAt(startIdx + 1) == '5' && str.charAt(startIdx + 2) < '6')) {
          result += combinations(str, startIdx + 3, numBytes + 1, combinations, combination);
      }
    }
    return result;
  }

  public static void main(String[] args) {
    ArrayList<byte[]> combinations = new ArrayList<>();
    System.out.println(combinations("1518918615824625494170109603025017352201241", 0, 0, combinations, new byte[16]));
    for(byte[] c: combinations) {
      System.out.println(Arrays.toString(c));
    }
  }
}
</code>```

The output of this is:

```<code>2
[15, -67, -70, -98, -10, -2, 94, -86, 109, 60, 30, -6, -83, 52, -55, -15]
[-105, 89, -70, -98, -10, -2, 94, -86, 109, 60, 30, -6, -83, 52, -55, -15]
</code>```

And the second solution it found is indeed the correct one.

Body:
I am working with some MD5 hashes that have been turned into number sequences using the methods shown below. Given the code and example hash below, how can I "reverse" the effect of the getString() method and turn a numerical sequence back into an MD5 hash?

For example, encrypt("umadbro"); returns "1518918615824625494170109603025017352201241" because the MD5 hash is passed through the getString() method. The MD5 hash for "umadbro" is 9759ba9ef6fe5eaa6d3c1efaad34c9f1. I need a method that takes a string of numbers modified by the getString() method and converts it into its MD5 hash. For example: reverseMethod("1518918615824625494170109603025017352201241"); should output "9759ba9ef6fe5eaa6d3c1efaad34c9f1" (The input parameter is the modified string of numbers and the output is the MD5 hash of the original string). NOTE: I am not looking for a method to crack the MD5 hash. I only need a method that reverses the effect of the getString() method shown below.

    public String encrypt(String source)
        {
            try
            {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] bytes = md.digest(source.getBytes());
                return getString(bytes);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

    private String getString(byte[] bytes) //this takes an md5 hash and turns it into a string of numbers.
    // How can I reverse the effect of this method?
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++)
        {
            byte b = bytes[i];
            sb.append(0xFF & b);
        }
        return sb.toString();
}

Body:
I tried to write some code that finds all possible combinations and it turned out there are a lot less then I anticipated. Only 2 in this case. And it takes very little time to find them.

import java.util.ArrayList;
import java.util.Arrays;

public class Comb {
  static long combinations(String str, int startIdx, int numBytes, ArrayList<byte[]> combinations, byte[] combination) {
    if(startIdx >= str.length()) {
       if(numBytes == 16) {
         combinations.add(combination.clone());
         return 1;
       } else return 0;
    }
    if(numBytes > 15) return 0;
    combination[numBytes] = (byte)(str.charAt(startIdx) - '0');
    long result = combinations(str, startIdx + 1, numBytes + 1, combinations, combination);
    if(startIdx < str.length() - 1 && str.charAt(startIdx) != '0') {
      combination[numBytes] = (byte)((str.charAt(startIdx) - '0') * 10 + (str.charAt(startIdx + 1) - '0'));
      result += combinations(str, startIdx + 2, numBytes + 1, combinations, combination);
    }
    if(startIdx < str.length() - 2) {
      combination[numBytes] = (byte)((str.charAt(startIdx) - '0') * 100 + (str.charAt(startIdx + 1) - '0') * 10 + (str.charAt(startIdx + 2) - '0'));
      if(str.charAt(startIdx) == '1') result += combinations(str, startIdx + 3, numBytes + 1, combinations, combination);
      if(str.charAt(startIdx) == '2' &&
        (str.charAt(startIdx + 1) < '5' || str.charAt(startIdx + 1) == '5' && str.charAt(startIdx + 2) < '6')) {
          result += combinations(str, startIdx + 3, numBytes + 1, combinations, combination);
      }
    }
    return result;
  }

  public static void main(String[] args) {
    ArrayList<byte[]> combinations = new ArrayList<>();
    System.out.println(combinations("1518918615824625494170109603025017352201241", 0, 0, combinations, new byte[16]));
    for(byte[] c: combinations) {
      System.out.println(Arrays.toString(c));
    }
  }
}

The output of this is:

2
[15, -67, -70, -98, -10, -2, 94, -86, 109, 60, 30, -6, -83, 52, -55, -15]
[-105, 89, -70, -98, -10, -2, 94, -86, 109, 60, 30, -6, -83, 52, -55, -15]

And the second solution it found is indeed the correct one.


答:
Switch the if regexp_object.match(input_time) for an if not regexp_object.match(input_time), and switch the logic around too:

```<code>def function1(input_time):
    """convert time from 24hr format
    into 12hours, minutes, period"""
    period_type = {'AM': 'before midday', 'PM': 'after midday'}
    regexp_object = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|23:59)$')
    # Switch to checking if it isn't valid instead, and exit early if that's the case
    if not regexp_object.match(input_time):
        print("{0} doesn't match required format 00:00 to 23:59"
              .format(input_time))
        exit(-1)

    # Since we already returned if the regex didn't match, we know if it reaches this point it'll match
    try:
        time_object = time.strptime(input_time, '%H:%M')
        suffix = time.strftime('%p', time_object)
        hours = int(time.strftime('%I', time_object))
        minutes = time_object[4]
        period = period_type.get(suffix)
        print("{0}:{1} {2}".format(hours, str(minutes).zfill(2), period))
        return hours, minutes, period
    except ValueError as err:
        print(err)
</code>```

Note that exit actually exits the program altogether. If you merely wanted to return something (such as None, to sign that something went wrong) to a further function, you could instead do return None and the function would return then and there.

Title: Python: Calling a function inside another function with returned values: Error Handling?

Body:
Switch the if regexp_object.match(input_time) for an if not regexp_object.match(input_time), and switch the logic around too:

def function1(input_time):
    """convert time from 24hr format
    into 12hours, minutes, period"""
    period_type = {'AM': 'before midday', 'PM': 'after midday'}
    regexp_object = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|23:59)$')
    # Switch to checking if it isn't valid instead, and exit early if that's the case
    if not regexp_object.match(input_time):
        print("{0} doesn't match required format 00:00 to 23:59"
              .format(input_time))
        exit(-1)

    # Since we already returned if the regex didn't match, we know if it reaches this point it'll match
    try:
        time_object = time.strptime(input_time, '%H:%M')
        suffix = time.strftime('%p', time_object)
        hours = int(time.strftime('%I', time_object))
        minutes = time_object[4]
        period = period_type.get(suffix)
        print("{0}:{1} {2}".format(hours, str(minutes).zfill(2), period))
        return hours, minutes, period
    except ValueError as err:
        print(err)

Note that exit actually exits the program altogether. If you merely wanted to return something (such as None, to sign that something went wrong) to a further function, you could instead do return None and the function would return then and there.


问:
Dynamic list for country and city in GUI
I want to create two drop down list for country and city. So if the user selects a country from drop-down list the other drop down list should automatically be refreshed to show its corresponding cities.

```<code> public void fillCombo(){
        String sql = " select * from sallytimes.table_name " ;
        try {
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery(sql);

            while (rs.next()){
               jComboBox_Country.addItem(rs.getString("_id"));
               jComboBox_City.addItem(rs.getString("city"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Location.class.getName()).log(Level.SEVERE, null, ex);
        }
}
</code>```

How do I progress this?

答:
You need to add an ActionListener to the first combo box to perform an Action when an Item is selected. In the ActionListener you want to replace the model of the second combo box with the new data.

Something like:

```<code>import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class ComboBoxTwo extends JPanel implements ActionListener
{
    private JComboBox<String> mainComboBox;
    private JComboBox<String> subComboBox;
    private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();

    public ComboBoxTwo()
    {
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        mainComboBox = new JComboBox<String>( items );
        mainComboBox.addActionListener( this );

        //  prevent action events from being fired when the up/down arrow keys are used
        mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        add( mainComboBox );

        //  Create sub combo box with multiple models

        subComboBox = new JComboBox<String>();
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        add( subComboBox );

        JButton arrow = SwingUtils.getDescendantOfType(JButton.class, subComboBox, "Text", "");
        Dimension d = arrow.getPreferredSize();
        System.out.println(arrow.getClass());
        System.out.println(d);
        d.width = 35;
        arrow.setPreferredSize(d);

        String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
        subItems.put(items[1], subItems1);

        String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
        subItems.put(items[2], subItems2);

        String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
        subItems.put(items[3], subItems3);
    }

    public void actionPerformed(ActionEvent e)
    {
        String item = (String)mainComboBox.getSelectedItem();
        Object o = subItems.get( item );

        if (o == null)
        {
            subComboBox.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
        }
    }

    private static void createAndShowUI()
    {
        try
        {
//          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) { }
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new ComboBoxTwo() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}
</code>```

So you would need to modify the code in the ActionListener to get the cities from the database based on the selected country.

Body:
I want to create two drop down list for country and city. So if the user selects a country from drop-down list the other drop down list should automatically be refreshed to show its corresponding cities.

 public void fillCombo(){
        String sql = " select * from sallytimes.table_name " ;
        try {
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery(sql);

            while (rs.next()){
               jComboBox_Country.addItem(rs.getString("_id"));
               jComboBox_City.addItem(rs.getString("city"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Location.class.getName()).log(Level.SEVERE, null, ex);
        }
}

How do I progress this?

Body:
You need to add an ActionListener to the first combo box to perform an Action when an Item is selected. In the ActionListener you want to replace the model of the second combo box with the new data.

Something like:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class ComboBoxTwo extends JPanel implements ActionListener
{
    private JComboBox<String> mainComboBox;
    private JComboBox<String> subComboBox;
    private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();

    public ComboBoxTwo()
    {
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        mainComboBox = new JComboBox<String>( items );
        mainComboBox.addActionListener( this );

        //  prevent action events from being fired when the up/down arrow keys are used
        mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        add( mainComboBox );

        //  Create sub combo box with multiple models

        subComboBox = new JComboBox<String>();
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        add( subComboBox );

        JButton arrow = SwingUtils.getDescendantOfType(JButton.class, subComboBox, "Text", "");
        Dimension d = arrow.getPreferredSize();
        System.out.println(arrow.getClass());
        System.out.println(d);
        d.width = 35;
        arrow.setPreferredSize(d);

        String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
        subItems.put(items[1], subItems1);

        String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
        subItems.put(items[2], subItems2);

        String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
        subItems.put(items[3], subItems3);
    }

    public void actionPerformed(ActionEvent e)
    {
        String item = (String)mainComboBox.getSelectedItem();
        Object o = subItems.get( item );

        if (o == null)
        {
            subComboBox.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
        }
    }

    private static void createAndShowUI()
    {
        try
        {
//          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) { }
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new ComboBoxTwo() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

So you would need to modify the code in the ActionListener to get the cities from the database based on the selected country.


问:
retrieve parent text on click (jQuery)
I'm trying to select first td element, when button "Add" is clicked.

```<code>              <tr>
                <td>tt3783958</td>
                <td>La La Land</td>
                <td>2016</td>
                <td>Comedy, Drama, Music</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
</code>```

I can't figure out what I'm doing wrong here.

```<code>$(document).ready(function() {
  $(".btn.btn-outline-success").eq(0).click(function() {
    var test = $(this).parent().parent().find("td").first()
    console.log(test)
    var fest = $(this).find("td").first()
    console.log(fest)
  });
});
</code>```

Live Demo: https://jsfiddle.net/ma1Lac9v/2/

答:
You don't need eq(0). eq(0) means selector with zero index, so add event to only first button. You can use closest() function to select first parent element with your selector.

$(document).ready(function() {
  $(".btn.btn-outline-success").click(function() {
    var test = $(this).closest("tr").find('td').first().text()
    console.log(test)
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link data-require="bootstrap@4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col">
          <table class="table">
            <thead class="thead-inverse">
              <tr>
                <th>id</th>
                <th>Title</th>
                <th>Year</th>
                <th>Type</th>
                <th>Option</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>tt3783958</td>
                <td>La La Land</td>
                <td>2016</td>
                <td>Comedy, Drama, Music</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt0488120</td>
                <td>Fracture</td>
                <td>2007</td>
                <td>Crime, Drama, Mystery</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt3569230</td>
                <td>Legend</td>
                <td>2015</td>
                <td>Biography, Crime, Drama</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt2692904</td>
                <td>Locke</td>
                <td>2013</td>
                <td>Drama</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt1392190</td>
                <td>Mad Max: Fury Road</td>
                <td>2015</td>
                <td>Action, Adventure, Sci-Fi</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt0993846</td>
                <td>The Wolf of Wall Street</td>
                <td>2013</td>
                <td>Biography, Comedy, Crime</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </body>

</html></code>```

Title: retrieve parent text on click (jQuery)

Body:
I'm trying to select first td element, when button "Add" is clicked.

                tt3783958
                La La Land
                2016
                Comedy, Drama, Music

                  <button class="btn btn-outline-success">Add</button>

I can't figure out what I'm doing wrong here.

$(document).ready(function() {
  $(".btn.btn-outline-success").eq(0).click(function() {
    var test = $(this).parent().parent().find("td").first()
    console.log(test)
    var fest = $(this).find("td").first()
    console.log(fest)
  });
});

Live Demo: https://jsfiddle.net/ma1Lac9v/2/

Body:
You don't need eq(0). eq(0) means selector with zero index, so add event to only first button. You can use closest() function to select first parent element with your selector.

$(document).ready(function() {
  $(".btn.btn-outline-success").click(function() {
    var test = $(this).closest("tr").find('td').first().text()
    console.log(test)
  });
});

<!DOCTYPE html>
<html>
  <head>
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link data-require="bootstrap@4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col">
          <table class="table">
            <thead class="thead-inverse">
              <tr>
                <th>id</th>
                <th>Title</th>
                <th>Year</th>
                <th>Type</th>
                <th>Option</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>tt3783958</td>
                <td>La La Land</td>
                <td>2016</td>
                <td>Comedy, Drama, Music</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt0488120</td>
                <td>Fracture</td>
                <td>2007</td>
                <td>Crime, Drama, Mystery</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt3569230</td>
                <td>Legend</td>
                <td>2015</td>
                <td>Biography, Crime, Drama</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt2692904</td>
                <td>Locke</td>
                <td>2013</td>
                <td>Drama</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt1392190</td>
                <td>Mad Max: Fury Road</td>
                <td>2015</td>
                <td>Action, Adventure, Sci-Fi</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
              <tr>
                <td>tt0993846</td>
                <td>The Wolf of Wall Street</td>
                <td>2013</td>
                <td>Biography, Comedy, Crime</td>
                <td>
                  <button class="btn btn-outline-success">Add</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </body>

</html>


问:
URL just isn't displaying what I want

Possible Duplicate:

  How can I accomplish this type of URL in ASP.Net MVC2?

I want to create HTML links like:

```<code>/Auctions/Clothes
/Auctions/Electronics
/Auctions/Real Estate
</code>```

Here's how I'm constructing the links:

```<code><li>@Html.ActionLink("Ropa", "Index", "Anuncios", new { category = "Ropa" }, new { })</li>
<li>@Html.ActionLink("Libros", "Index", "Anuncios", new { category = "Libros" }, new { })</li>
</code>```

The problems is the links are being used like this:

```<code>http://localhost:8589/Anuncios?category=Libros
</code>```

I want my URLS to be nice looking, as such I'd like the above to be like:

```<code>/Anuncios/Libros
</code>```

Any suggestions on how to fix this? Here's the ActionResult method, and to clarify, this is doing exactly what I want it to do. It works, except the URL is horrible.

```<code>public ActionResult Index(string category)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions().Where(a => a.Subcategory.Category.Name == category);
    return View(auctions);
}
</code>```

答:
please have a look at this question for implementing your requirement.

MVC 2.0 dynamic routing for category names in an e-store

EDIT:

create a new HTML helper that you will use to render the menu like this

```<code>public static class MyMenuHelper {
    public static string MyMenu(this HtmlHelper helper) {
        List<Category> categories = GetCategories();
        foreach ( Category c in categories ) {
            helper.RouteLink( c.Name, "AuctionCategoryDetails", new { categoryName = c.Name } );
        }
    }
}
</code>```

Finally in your _Layout page use it like this

```<code>@Html.MyMenu
</code>```

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Title: URL just isn't displaying what I want

Body:
Possible Duplicate:

  How can I accomplish this type of URL in ASP.Net MVC2?

I want to create HTML links like:

/Auctions/Clothes
/Auctions/Electronics
/Auctions/Real Estate

Here's how I'm constructing the links:

@Html.ActionLink("Ropa", "Index", "Anuncios", new { category = "Ropa" }, new { })

@Html.ActionLink("Libros", "Index", "Anuncios", new { category = "Libros" }, new { })

The problems is the links are being used like this:

http://localhost:8589/Anuncios?category=Libros

I want my URLS to be nice looking, as such I'd like the above to be like:

/Anuncios/Libros

Any suggestions on how to fix this? Here's the ActionResult method, and to clarify, this is doing exactly what I want it to do. It works, except the URL is horrible.

public ActionResult Index(string category)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions().Where(a => a.Subcategory.Category.Name == category);
    return View(auctions);
}

Body:
please have a look at this question for implementing your requirement.

MVC 2.0 dynamic routing for category names in an e-store

EDIT:

create a new HTML helper that you will use to render the menu like this

public static class MyMenuHelper {
    public static string MyMenu(this HtmlHelper helper) {
        List<Category> categories = GetCategories();
        foreach ( Category c in categories ) {
            helper.RouteLink( c.Name, "AuctionCategoryDetails", new { categoryName = c.Name } );
        }
    }
}

Finally in your _Layout page use it like this

@Html.MyMenu


问:
Seemingly correct type signature refused in where block
I have been messing around with continuation passing style in Haskell. Taking the Cont monad apart and removing the type wrappers helped me in understanding the implementation. Here is the code:

{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad (ap)

newtype Cont r a = Cont {runCont :: (a -> r) -> r}

instance Functor (Cont r) where
  fmap f ka = ka >>= pure . f

instance Applicative (Cont r) where
  (<*>) = ap
  pure = return

instance Monad (Cont r) where

  ka >>= kab = Cont kb'
    where
      -- kb' :: (b -> r) -> r
      kb' hb = ka' ha
        where
          -- ha :: (a -> r)
          ha a = (kab' a) hb

      -- ka' :: (a -> r) -> r
      ka' = runCont ka

      -- kab' :: a -> (b -> r) -> r
      kab' a = runCont (kab a)

  return a = Cont ka'
    where
      -- ka' :: (a -> r) -> r
      ka' ha = ha a
```

<p>This code compiles (using GHC 8.0.2) and everything seems fine. However, as soon as I uncomment any of the (now commented) type signatures in the where block I get an error. For exapmle, if I uncomment the line</p>

<pre class="lang-hs prettyprint-override"><code>      -- ka' :: (a -> r) -> r
</code>```

I get:

    • Couldn't match type ‘a’ with ‘a1’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b
        at cont.hs:19:6
      ‘a1’ is a rigid type variable bound by
        the type signature for:
          ka' :: forall a1. (a1 -> r) -> r
        at cont.hs:27:14
      Expected type: (a1 -> r) -> r
        Actual type: (a -> r) -> r
    • In the expression: runCont ka
      In an equation for ‘ka'’: ka' = runCont ka
      In an equation for ‘>>=’:
          ka >>= kab
            = Cont kb'
            where
                kb' hb
                  = ka' ha
                  where
                      ha a = (kab' a) hb
                ka' :: (a -> r) -> r
                ka' = runCont ka
                kab' a = runCont (kab a)
    • Relevant bindings include
        ka' :: (a1 -> r) -> r (bound at cont.hs:28:7)
        kab' :: a -> (b -> r) -> r (bound at cont.hs:31:7)
        kab :: a -> Cont r b (bound at cont.hs:19:10)
        ka :: Cont r a (bound at cont.hs:19:3)
        (>>=) :: Cont r a -> (a -> Cont r b) -> Cont r b
          (bound at cont.hs:19:3)
Failed, modules loaded: none.
```

<p>So I tried using a type wildcard to let the compiler tell me what type signature I should put there. As such I tried the following signature:</p>

<pre class="lang-hs prettyprint-override"><code>      ka' :: _
</code>```

Which gave the following error:

    • Found type wildcard ‘_’ standing for ‘(a -> r) -> r’
      Where: ‘r’ is a rigid type variable bound by
               the instance declaration at cont.hs:15:10
             ‘a’ is a rigid type variable bound by
               the type signature for:
                 (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b
               at cont.hs:19:6
      To use the inferred type, enable PartialTypeSignatures
    • In the type signature:
        ka' :: _
      In an equation for ‘>>=’:
          ka >>= kab
            = Cont kb'
            where
                kb' hb
                  = ka' ha
                  where
                      ha a = (kab' a) hb
                ka' :: _
                ka' = runCont ka
                kab' a = runCont (kab a)
      In the instance declaration for ‘Monad (Cont r)’
    • Relevant bindings include
        ka' :: (a -> r) -> r (bound at cont.hs:28:7)
        kab' :: a -> (b -> r) -> r (bound at cont.hs:31:7)
        kab :: a -> Cont r b (bound at cont.hs:19:10)
        ka :: Cont r a (bound at cont.hs:19:3)
        (>>=) :: Cont r a -> (a -> Cont r b) -> Cont r b
          (bound at cont.hs:19:3)
Failed, modules loaded: none.
```

Now I am really confused, the compiler tells me the type of ka' is (a -> r) -> r but as soon as I try to explicitely annotate ka' with this type,
compiling fails. First I thought I was missing ScopedTypeVariables but it does not seem to make a difference.

What is going on here?

EDIT
This is similar to the question " Why does this function that uses a scoped type variable in a where clause not typecheck? " in that it requires an explicit forall to bind type variables. However it is not a duplicate since the answer to this question also requires the InstanceSigs extension.

答:
Makes sense. After all, where did those as and bs come from? We have no way to know they're connected to the polymorphism of (>>=) and return. It's easy to fix, though, as mentioned in the comments: give (>>=) and return type signatures that mention a and b, toss in the requisite language extension, and hey presto:

```<code>{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE InstanceSigs #-}

import Control.Monad (ap)

newtype Cont r a = Cont {runCont :: (a -> r) -> r}

instance Functor (Cont r) where
  fmap f ka = ka >>= pure . f

instance Applicative (Cont r) where
  (<*>) = ap
  pure = return

instance Monad (Cont r) where

  (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b
  ka >>= kab = Cont kb'
    where
      kb' :: (b -> r) -> r
      kb' hb = ka' ha
        where
          ha :: (a -> r)
          ha a = (kab' a) hb

      ka' :: (a -> r) -> r
      ka' = runCont ka

      kab' :: a -> (b -> r) -> r
      kab' a = runCont (kab a)

  return :: forall a. a -> Cont r a
  return a = Cont ka'
    where
      ka' :: (a -> r) -> r
      ka' ha = ha a
</code>```

I feel like there's a Dragonball joke in all these kas and has, but the joke escapes me.

Body:
I have been messing around with continuation passing style in Haskell. Taking the Cont monad apart and removing the type wrappers helped me in understanding the implementation. Here is the code:

{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad (ap)

newtype Cont r a = Cont {runCont :: (a -> r) -> r}

instance Functor (Cont r) where
  fmap f ka = ka >>= pure . f

instance Applicative (Cont r) where
  (<*>) = ap
  pure = return

instance Monad (Cont r) where

  ka >>= kab = Cont kb'
    where
      -- kb' :: (b -> r) -> r
      kb' hb = ka' ha
        where
          -- ha :: (a -> r)
          ha a = (kab' a) hb

      -- ka' :: (a -> r) -> r
      ka' = runCont ka

      -- kab' :: a -> (b -> r) -> r
      kab' a = runCont (kab a)

  return a = Cont ka'
    where
      -- ka' :: (a -> r) -> r
      ka' ha = ha a

This code compiles (using GHC 8.0.2) and everything seems fine. However, as soon as I uncomment any of the (now commented) type signatures in the where block I get an error. For exapmle, if I uncomment the line

      -- ka' :: (a -> r) -> r

I get:

    • Couldn't match type ‘a’ with ‘a1’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b
        at cont.hs:19:6
      ‘a1’ is a rigid type variable bound by
        the type signature for:
          ka' :: forall a1. (a1 -> r) -> r
        at cont.hs:27:14
      Expected type: (a1 -> r) -> r
        Actual type: (a -> r) -> r
    • In the expression: runCont ka
      In an equation for ‘ka'’: ka' = runCont ka
      In an equation for ‘>>=’:
          ka >>= kab
            = Cont kb'
            where
                kb' hb
                  = ka' ha
                  where
                      ha a = (kab' a) hb
                ka' :: (a -> r) -> r
                ka' = runCont ka
                kab' a = runCont (kab a)
    • Relevant bindings include
        ka' :: (a1 -> r) -> r (bound at cont.hs:28:7)
        kab' :: a -> (b -> r) -> r (bound at cont.hs:31:7)
        kab :: a -> Cont r b (bound at cont.hs:19:10)
        ka :: Cont r a (bound at cont.hs:19:3)
        (>>=) :: Cont r a -> (a -> Cont r b) -> Cont r b
          (bound at cont.hs:19:3)
Failed, modules loaded: none.

So I tried using a type wildcard to let the compiler tell me what type signature I should put there. As such I tried the following signature:

      ka' :: _

Which gave the following error:

    • Found type wildcard ‘_’ standing for ‘(a -> r) -> r’
      Where: ‘r’ is a rigid type variable bound by
               the instance declaration at cont.hs:15:10
             ‘a’ is a rigid type variable bound by
               the type signature for:
                 (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b
               at cont.hs:19:6
      To use the inferred type, enable PartialTypeSignatures
    • In the type signature:
        ka' :: _
      In an equation for ‘>>=’:
          ka >>= kab
            = Cont kb'
            where
                kb' hb
                  = ka' ha
                  where
                      ha a = (kab' a) hb
                ka' :: _
                ka' = runCont ka
                kab' a = runCont (kab a)
      In the instance declaration for ‘Monad (Cont r)’
    • Relevant bindings include
        ka' :: (a -> r) -> r (bound at cont.hs:28:7)
        kab' :: a -> (b -> r) -> r (bound at cont.hs:31:7)
        kab :: a -> Cont r b (bound at cont.hs:19:10)
        ka :: Cont r a (bound at cont.hs:19:3)
        (>>=) :: Cont r a -> (a -> Cont r b) -> Cont r b
          (bound at cont.hs:19:3)
Failed, modules loaded: none.

Now I am really confused, the compiler tells me the type of ka' is (a -> r) -> r but as soon as I try to explicitely annotate ka' with this type,
compiling fails. First I thought I was missing ScopedTypeVariables but it does not seem to make a difference.

What is going on here?

EDIT
This is similar to the question " Why does this function that uses a scoped type variable in a where clause not typecheck? " in that it requires an explicit forall to bind type variables. However it is not a duplicate since the answer to this question also requires the InstanceSigs extension.

Body:
Makes sense. After all, where did those as and bs come from? We have no way to know they're connected to the polymorphism of (>>=) and return. It's easy to fix, though, as mentioned in the comments: give (>>=) and return type signatures that mention a and b, toss in the requisite language extension, and hey presto:

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE InstanceSigs #-}

import Control.Monad (ap)

newtype Cont r a = Cont {runCont :: (a -> r) -> r}

instance Functor (Cont r) where
  fmap f ka = ka >>= pure . f

instance Applicative (Cont r) where
  (<*>) = ap
  pure = return

instance Monad (Cont r) where

  (>>=) :: forall a b. Cont r a -> (a -> Cont r b) -> Cont r b
  ka >>= kab = Cont kb'
    where
      kb' :: (b -> r) -> r
      kb' hb = ka' ha
        where
          ha :: (a -> r)
          ha a = (kab' a) hb

      ka' :: (a -> r) -> r
      ka' = runCont ka

      kab' :: a -> (b -> r) -> r
      kab' a = runCont (kab a)

  return :: forall a. a -> Cont r a
  return a = Cont ka'
    where
      ka' :: (a -> r) -> r
      ka' ha = ha a

I feel like there's a Dragonball joke in all these kas and has, but the joke escapes me.


问:
Visual Composer giving ReferenceError: id is not defined error when adding an image
I was asked to look into a problem on a WordPress page that I didn't make. It uses Visual Composer and for a few days they can't add any images to the pages in the backend. The Single Image component loads, you can select the picture, but when you add it nothing happens.

Checking the console it gives the following error:

```<code>ReferenceError: id is not defined
</code>```

in the following location: /wp-admin/load-scripts.php?c=0&load%5B%5D=jquery-core,jquery-migrate,utils,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-draggable,jquery-ui-slider,jquery-tou&load%5B%5D=ch-punch,iris,wp-color-picker,jquery-ui-sortable,underscore,wp-a11y,thickbox,shortcode,plupload,jquery-ui-position,jquery-ui-men&load%5B%5D=u,jquery-ui-autocomplete,jquery-ui-tabs,farbtastic,media-upload&ver=4.5.2 line 98 > Function

```<code>var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='\n    <li class="added">\n        <div class="inner" style="width: 75px; height: 75px; overflow: hidden;text-align: center;">\n            <img rel="'+
((__t=( id ))==null?'':__t)+
'" src="'+
((__t=( url ))==null?'':__t)+
'" />\n        </div>\n        <a href="#" class="icon-remove"></a>\n    </li>\n';
}
return __p;
</code>```

Tried to fix it by this, this, this and this solution, but nothing worked.

答: My friend had the same problem but with customized visual composer for Salient theme. I created full wp backup, enabled default theme, deleted Salient theme, downloaded zip file with original theme (from themeforest.net where he purchased it) and uploaded it in the Appearance / Themes / Add new / Upload theme view and enabled Salient Visual Composer plugin in the Plugins area...

Body:
I was asked to look into a problem on a WordPress page that I didn't make. It uses Visual Composer and for a few days they can't add any images to the pages in the backend. The Single Image component loads, you can select the picture, but when you add it nothing happens.

Checking the console it gives the following error:

ReferenceError: id is not defined

in the following location: /wp-admin/load-scripts.php?c=0&load%5B%5D=jquery-core,jquery-migrate,utils,jquery-ui-core,jquery-ui-widget,jquery-ui-mouse,jquery-ui-draggable,jquery-ui-slider,jquery-tou&load%5B%5D=ch-punch,iris,wp-color-picker,jquery-ui-sortable,underscore,wp-a11y,thickbox,shortcode,plupload,jquery-ui-position,jquery-ui-men&load%5B%5D=u,jquery-ui-autocomplete,jquery-ui-tabs,farbtastic,media-upload&ver=4.5.2 line 98 > Function

var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='\n
\n
\n            \n
\n        \n
\n';
}
return __p;

Tried to fix it by this, this, this and this solution, but nothing worked.


问:
Send data to Angular2 component from a Directive
How can I register to an Input of a component in Angular2 from a Directive?

To be specific, I already know about this solution, But I'd like to do this without parent envelopment.

I have this snippet code from Angular2 site, but I cannot get it to work to send data to the component:

// Directive
import { Directive, ElementRef, Input, Output, EventEmitter } from '@angular/core';

@Directive({ selector: '[dirTest]' })
export class dirTestDirective {
    @Output() refresh = new EventEmitter<number>();
    constructor(private element: ElementRef) {
        setInterval(() => {
            this.refresh.emit( Math.random() );
        }, 1000);
    }
}

// Component
import {
    Input,
    Output,
    Component,
    OnChanges,
    SimpleChanges,
} from '@angular/core';

@Component({
    selector: 'simple',
    template: '

',
})
export class SimpleComponent implements OnChanges {
    @Input() refresh: number;

    // This never gets triggered
    ngOnChanges(changes: SimpleChanges) {
        console.log(changes);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Get this together -->
<simple dirTest></simple></code>```

Eventually I ended up with this solution which is not that bad, but I still think the input is better.

Please if anyone has a better solution post it.

```<code>http://plnkr.co/edit/FZsIfLfvtf3EjkGGGBlC
</code>```

答:
i can think about passing value to component through "Input" only from parent container:

```<code><simple dirTest (refresh)="mySub($event)" [refresh]="name"></simple>
</code>```

When "mySub" and "name" is method and property of parent container:

```<code>  mySub($event){
    this.name = $event;
 }
</code>```

see this plunk

Body:
How can I register to an Input of a component in Angular2 from a Directive?

To be specific, I already know about this solution, But I'd like to do this without parent envelopment.

I have this snippet code from Angular2 site, but I cannot get it to work to send data to the component:

// Directive
import { Directive, ElementRef, Input, Output, EventEmitter } from '@angular/core';

@Directive({ selector: '[dirTest]' })
export class dirTestDirective {
    @Output() refresh = new EventEmitter<number>();
    constructor(private element: ElementRef) {
        setInterval(() => {
            this.refresh.emit( Math.random() );
        }, 1000);
    }
}

// Component
import {
    Input,
    Output,
    Component,
    OnChanges,
    SimpleChanges,
} from '@angular/core';

@Component({
    selector: 'simple',
    template: '

',
})
export class SimpleComponent implements OnChanges {
    @Input() refresh: number;

    // This never gets triggered
    ngOnChanges(changes: SimpleChanges) {
        console.log(changes);
    }
}

<simple dirTest></simple>

Eventually I ended up with this solution which is not that bad, but I still think the input is better.

Please if anyone has a better solution post it.

http://plnkr.co/edit/FZsIfLfvtf3EjkGGGBlC

Body:
i can think about passing value to component through "Input" only from parent container:

<simple dirTest (refresh)="mySub($event)" [refresh]="name"></simple>

When "mySub" and "name" is method and property of parent container:

  mySub($event){
    this.name = $event;
 }

see this plunk


问:
Creating vector managed JNI threads [C++]
In short I've been trying to accomplish the following: I want to be able to effectively manage a lot(in the billions/they don't take long to finish, but I am creating arrays to process at a high pace, and if i don't pass stuff to the thread right away, the array gets so large it causes segfaults) of threads which pass data to JNI if necessary and need to be stored in a vector.

I've been facing two problems:

The first one is, that if I try to spawn more than around 45 threads all running JNI simultaneously, Java crashes. If they aren't running all at the same time, it works fine, but I get lots of complaints from the GC that it wasn't getting enough memory which doesn't seem to affect anything though.

The second is, that if I spawn the threads at the speed I am at the moment, the vector which I use to manage and later join them, gets too large.

So in conclusion I need a fast way to keep track of the threads I am creating without sacrificing any time pretty much.

```<code>//g++ -std=c++11 -I/usr/lib/jvm/java-8-openjdk/include -I/usr/lib/jvm/java-8-openjdk/include/linux cpptest/Test.cpp -L/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server -ljvm -lpthread
#include <jni.h>
#include <iostream>
#include <thread>
#include <string.h>
#include <vector>
#include <chrono>
#include <mutex>
#include <fstream>
#include <algorithm>

jclass cls;
jmethodID mid;
JNIEnv* env;
JavaVM* jvm;
std::mutex m;

typedef struct {
    long seed;
    int chunkX;
    int chunkZ;
    int eyes;
} Stronghold;

void ThreadFunc(Stronghold strhld, std::ofstream *outfile) {
  jvm->AttachCurrentThread((void**)&env, NULL);
  jlongArray rt = (jlongArray)env->CallStaticLongMethod(cls, mid, (jlong)strhld.seed, (jint)strhld.chunkX, (jint)strhld.chunkZ, (jint)strhld.eyes);
  jsize size = env->GetArrayLength(rt);
  std::vector<long> rtVec(size);
  env->GetLongArrayRegion(rt, 0, size, &rtVec[0]);
    jvm->DetachCurrentThread();
    std::string write;
    m.lock();
  for(long &element : rtVec) {
        write = std::to_string(element) + "; ";
    *outfile << write;
  }
    *outfile << std::endl;
    m.unlock();
}

int main(int argc, char* argv[]) {
  std::ofstream outfile("./new.txt",std::ofstream::binary);
    std::vector<std::thread> threads;

  const int kNumOptions = 3;
  JavaVMOption options[kNumOptions] = {
    { const_cast<char*>("-Xmx512m"), NULL },
    { const_cast<char*>("-verbose:gc"), NULL },
    { const_cast<char*>("-Djava.class.path=/home/jewe37/Desktop/"), NULL }
  };

  JavaVMInitArgs vm_args;
  vm_args.version = JNI_VERSION_1_8;
  vm_args.options = options;
  vm_args.nOptions = sizeof(options) / sizeof(JavaVMOption);

  env = NULL;
  jvm = NULL;
  JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args);

  const char* kClassName = "Processor";
  cls = env->FindClass(kClassName);
  if (cls == NULL) {
    std::cerr << "FINDCLASS" << std::endl;
        return 1;
    }

  const char* kMethodName = "ProcessSeed";
  mid = env->GetStaticMethodID(cls, kMethodName, "(JIII)[J");
  if (mid == NULL) {
    std::cerr << "FINDMETHOD" << std::endl;
        return 1;
    }

  Stronghold strhld;

    for(int i = 0; i < std::stoi(argv[1]); i++) {
        strhld = {i, i*2, i*3, i*4};
        threads.emplace_back(ThreadFunc, strhld, &outfile);
        std::this_thread::sleep_for(std::chrono::microseconds(50));
    }

    std::cout << threads.size() << std::endl;

    for (std::thread &thread : threads) if (thread.joinable()) thread.join();

  jvm->DestroyJavaVM();

  outfile.close();
  return 0;
}
</code>```

答: You cannot share JNIEnv between threads.  It must be per-thread.  Make env local to ThreadFunc().  This question is answered thoroughly here.  Also do not forget to detach your native thread before it quits.</p>

Body:
In short I've been trying to accomplish the following: I want to be able to effectively manage a lot(in the billions/they don't take long to finish, but I am creating arrays to process at a high pace, and if i don't pass stuff to the thread right away, the array gets so large it causes segfaults) of threads which pass data to JNI if necessary and need to be stored in a vector.

I've been facing two problems:

The first one is, that if I try to spawn more than around 45 threads all running JNI simultaneously, Java crashes. If they aren't running all at the same time, it works fine, but I get lots of complaints from the GC that it wasn't getting enough memory which doesn't seem to affect anything though.

The second is, that if I spawn the threads at the speed I am at the moment, the vector which I use to manage and later join them, gets too large.

So in conclusion I need a fast way to keep track of the threads I am creating without sacrificing any time pretty much.

//g++ -std=c++11 -I/usr/lib/jvm/java-8-openjdk/include -I/usr/lib/jvm/java-8-openjdk/include/linux cpptest/Test.cpp -L/usr/lib/jvm/java-8-openjdk/jre/lib/amd64/server -ljvm -lpthread
#include <jni.h>
#include <iostream>
#include <thread>
#include <string.h>
#include <vector>
#include <chrono>
#include <mutex>
#include <fstream>
#include <algorithm>

jclass cls;
jmethodID mid;
JNIEnv* env;
JavaVM* jvm;
std::mutex m;

typedef struct {
    long seed;
    int chunkX;
    int chunkZ;
    int eyes;
} Stronghold;

void ThreadFunc(Stronghold strhld, std::ofstream *outfile) {
  jvm->AttachCurrentThread((void**)&env, NULL);
  jlongArray rt = (jlongArray)env->CallStaticLongMethod(cls, mid, (jlong)strhld.seed, (jint)strhld.chunkX, (jint)strhld.chunkZ, (jint)strhld.eyes);
  jsize size = env->GetArrayLength(rt);
  std::vector<long> rtVec(size);
  env->GetLongArrayRegion(rt, 0, size, &rtVec[0]);
    jvm->DetachCurrentThread();
    std::string write;
    m.lock();
  for(long &element : rtVec) {
        write = std::to_string(element) + "; ";
    *outfile << write;
  }
    *outfile << std::endl;
    m.unlock();
}

int main(int argc, char* argv[]) {
  std::ofstream outfile("./new.txt",std::ofstream::binary);
    std::vector<std::thread> threads;

  const int kNumOptions = 3;
  JavaVMOption options[kNumOptions] = {
    { const_cast<char*>("-Xmx512m"), NULL },
    { const_cast<char*>("-verbose:gc"), NULL },
    { const_cast<char*>("-Djava.class.path=/home/jewe37/Desktop/"), NULL }
  };

  JavaVMInitArgs vm_args;
  vm_args.version = JNI_VERSION_1_8;
  vm_args.options = options;
  vm_args.nOptions = sizeof(options) / sizeof(JavaVMOption);

  env = NULL;
  jvm = NULL;
  JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args);

  const char* kClassName = "Processor";
  cls = env->FindClass(kClassName);
  if (cls == NULL) {
    std::cerr << "FINDCLASS" << std::endl;
        return 1;
    }

  const char* kMethodName = "ProcessSeed";
  mid = env->GetStaticMethodID(cls, kMethodName, "(JIII)[J");
  if (mid == NULL) {
    std::cerr << "FINDMETHOD" << std::endl;
        return 1;
    }

  Stronghold strhld;

    for(int i = 0; i < std::stoi(argv[1]); i++) {
        strhld = {i, i*2, i*3, i*4};
        threads.emplace_back(ThreadFunc, strhld, &outfile);
        std::this_thread::sleep_for(std::chrono::microseconds(50));
    }

    std::cout << threads.size() << std::endl;

    for (std::thread &thread : threads) if (thread.joinable()) thread.join();

  jvm->DestroyJavaVM();

  outfile.close();
  return 0;
}


问:
Scrolling of multiple recycler view in an activity. (how to make it smooth)
I have 2 recyclerviews in my activity 1st one is horizontally scrollable and the 2nd one is vertically scrollable. (XML code given below)
But the scrolling is not smooth.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    android:clickable="true"
    >
    <ProgressBar
        android:id="@+id/progressBarCircularIndetermininatesearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateTintMode="src_atop"
        android:indeterminateTint="#f44336"
        android:layout_centerInParent="true"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/progressbacklin"
        android:scrollbars="none"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_alignParentTop="true"
        android:scrollbars="none"
        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_below="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:scrollbars="none"
        />
        </RelativeLayout>
</ScrollView>
    <LinearLayout
        android:id="@+id/progressbacklin"
        android:layout_above="@+id/adViewsearch"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginBottom="90dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/white"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        >
        <ProgressBar
            android:id="@+id/progressBarCircularIndetermininate"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="#f44336"
            android:layout_centerInParent="true"/>
    </LinearLayout>
    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adViewsearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

</RelativeLayout>
</code>```

i use

```<code>setNestedScrollingEnabled(false);
</code>```

for both recycler view.

Any ideas to implement this with a smooth scrolling?

答:
Change ScrollView to NestedScrollView.

In order this to work, you need to have RecyclerView with height wrap_content inside  NestedScrollView and you need to set recyclerView.setNestedScrollingEnabled(false) from code.

Body:
I have 2 recyclerviews in my activity 1st one is horizontally scrollable and the 2nd one is vertically scrollable. (XML code given below)
But the scrolling is not smooth.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    android:clickable="true"
    >
    <ProgressBar
        android:id="@+id/progressBarCircularIndetermininatesearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateTintMode="src_atop"
        android:indeterminateTint="#f44336"
        android:layout_centerInParent="true"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/progressbacklin"
        android:scrollbars="none"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_alignParentTop="true"
        android:scrollbars="none"
        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_below="@+id/videolist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:scrollbars="none"
        />
        </RelativeLayout>
</ScrollView>
    <LinearLayout
        android:id="@+id/progressbacklin"
        android:layout_above="@+id/adViewsearch"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginBottom="90dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/white"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        >
        <ProgressBar
            android:id="@+id/progressBarCircularIndetermininate"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="#f44336"
            android:layout_centerInParent="true"/>
    </LinearLayout>
    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adViewsearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

</RelativeLayout>

i use

setNestedScrollingEnabled(false);

for both recycler view.

Any ideas to implement this with a smooth scrolling?