问:
AJAX dont update page
I have strange problem  in my project. Can someone say why it happens and how to fix it.

I have function in view for edit/update object (function_edit). Also I use AJAX to update list of objects (function_list) after success edit and also I use django-reversion app to controll the changes of each object. The function_list has part which is visable only to users with a special role (request_user_is_business_analyst). When I use request_user_is_business_analyst in view it raise error and when I dont use it view function works fine. Also when I didnt use django-reversion request_user_is_business_analyst worked fine.

urs.py:

```<code>url(r'^(?P<project_code>[0-9a-f-]+)/(?P<function_code>[0-9a-f-]+)/edit/$',
    function_edit,
    name='function_edit'),
</code>```

views.py:

```<code>@reversion.create_revision()
def function_edit(request, project_code, function_code):
    data = dict()
    project = get_object_or_404(Project, pk=project_code)
    request_user_is_business_analyst = project.member_set.filter(user=request.user, role='business_analyst').exists()
    function = get_object_or_404(Function, pk=function_code)
    if request.method == 'POST':
        form = FunctionAddForm(request.POST, instance=function)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            functions = Function.objects.filter(project=project_code)
            data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst})
            # Store some meta-information for reversion.
            reversion.set_user(request.user)
            reversion.set_comment('EDIT')
        else:
            data['form_is_valid'] = False
    else:
        form = FunctionAddForm(instance=function)
    context = {'project': project, 'function': function, 'form': form}
    data['html_function_form'] = render_to_string('project/function_edit.html', context, request=request)
    return JsonResponse(data)
</code>```

function_list.html:

```<code>{% for function in functions %}
    <tr>
        <td class="text-center">{{ function.code }}</td>
        <td>{{ function.name }}</td>
        {% if request_user_is_business_analyst %}
            <td>
                <a class="btn btn-warning button-handlers" id="js-edit-function-button" data-url="{% url 'project:function_edit' project_code=project.code function_code=function.code %}"><i class="fa fa-pencil" aria-hidden="true"></i> {% trans 'EDIT' %}</a>
                <a class="btn btn-info open-button-handler" href="{{ function.get_absolute_url }}"><i class="fa fa-sign-in" aria-hidden="true"></i> {% trans 'REVERSION' %}</a>
            </td>
        {% endif %}
    </tr>
{% endfor %}
</code>```

ERROR:

```<code>Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 296, in do_revision_context
    return func(*args, **kwargs)
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 252, in function_edit
    data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst})
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\loader.py", line 68, in render_to_string
    return template.render(context, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\backends\django.py", line 66, in render
    return self.template.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 208, in render
    return self._render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py", line 315, in render
    return nodelist.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py", line 439, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\base.py", line 91, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 392, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
django.urls.exceptions.NoReverseMatch: Reverse for 'function_edit' with arguments '()' and keyword arguments '{'project_code': '', 'function_code': UUID('08abfad3-58a5-4953-8b8f-82bd1f66fecb')}' not found. 1 pattern(s) tried: ['ru/account/dashboard/projects/(?P<project_code>[0-9a-f-]+)/(?P<function_code>[0-9a-f-]+)/edit/$']
</code>```

答:
I think that your problem is here
First check this line
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 252,

data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst})

and print request_user_is_business_analyst to see what returns

EDIT:
Solve:
must be like this:

```<code>data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst, 'project':project, 'function':function})
</code>```

Title: AJAX dont update page

Body:
I have strange problem  in my project. Can someone say why it happens and how to fix it.

I have function in view for edit/update object (function_edit). Also I use AJAX to update list of objects (function_list) after success edit and also I use django-reversion app to controll the changes of each object. The function_list has part which is visable only to users with a special role (request_user_is_business_analyst). When I use request_user_is_business_analyst in view it raise error and when I dont use it view function works fine. Also when I didnt use django-reversion request_user_is_business_analyst worked fine.

urs.py:

url(r'^(?P<project_code>[0-9a-f-]+)/(?P<function_code>[0-9a-f-]+)/edit/$',
    function_edit,
    name='function_edit'),

views.py:

@reversion.create_revision()
def function_edit(request, project_code, function_code):
    data = dict()
    project = get_object_or_404(Project, pk=project_code)
    request_user_is_business_analyst = project.member_set.filter(user=request.user, role='business_analyst').exists()
    function = get_object_or_404(Function, pk=function_code)
    if request.method == 'POST':
        form = FunctionAddForm(request.POST, instance=function)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            functions = Function.objects.filter(project=project_code)
            data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst})
            # Store some meta-information for reversion.
            reversion.set_user(request.user)
            reversion.set_comment('EDIT')
        else:
            data['form_is_valid'] = False
    else:
        form = FunctionAddForm(instance=function)
    context = {'project': project, 'function': function, 'form': form}
    data['html_function_form'] = render_to_string('project/function_edit.html', context, request=request)
    return JsonResponse(data)

function_list.html:

{% for function in functions %}

        {{ function.code }}
        {{ function.name }}
        {% if request_user_is_business_analyst %}

                 {% trans 'EDIT' %}
                 {% trans 'REVERSION' %}

        {% endif %}

{% endfor %}

ERROR:

Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 296, in do_revision_context
    return func(*args, **kwargs)
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 252, in function_edit
    data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst})
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\loader.py", line 68, in render_to_string
    return template.render(context, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\backends\django.py", line 66, in render
    return self.template.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 208, in render
    return self._render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 199, in _render
    return self.nodelist.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py", line 315, in render
    return nodelist.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 994, in render
    bit = node.render_annotated(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py", line 439, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\base.py", line 91, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 392, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
django.urls.exceptions.NoReverseMatch: Reverse for 'function_edit' with arguments '()' and keyword arguments '{'project_code': '', 'function_code': UUID('08abfad3-58a5-4953-8b8f-82bd1f66fecb')}' not found. 1 pattern(s) tried: ['ru/account/dashboard/projects/(?P<project_code>[0-9a-f-]+)/(?P<function_code>[0-9a-f-]+)/edit/$']

Body:
I think that your problem is here
First check this line
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 252,

data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst})

and print request_user_is_business_analyst to see what returns

EDIT:
Solve:
must be like this:

data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst, 'project':project, 'function':function})


来源: stackexchange

问:
In what cases superclass shouldn't be abstract?
In this thread I found some interesting moment, If class uses only as superclass there isn't rule to make it abstract. Why so?

Thanks

答:
It all depends on whether or not it makes sense to have instances of the class.

Suppose you for instance have one class Dog and one class Cat. They both extend Animal. Now an Animal may have a name and a few methods, but it doesn't make sense to have Animals running around. An Animal is... well an abstract notion.

In other circumstances you may have subclasses (the LinkedHashSet for instance extends HashSet) but it still makes a lot of sense to instantiate the super class (HashSet in this case).

To answer your comment, "Does it make sense to make a class non-abstract even if you don't want to instantiate it."

Well I'd say if you, today, simply don't know of any use-cases in which it should be instantiated, the same rule applies: Does it make sense (logically) to have an instance of the class? If so, make it non-abstract.

If the situation is more like "If you've created an instance of this class, you're probably doing it wrong!" then I'd clarify this by making the class abstract.

ContentLicense: CC BY-SA 2.5


问:
Unable to update to Xcode 8.3
When I tried to update to Xcode 8.3, the following happened in App Store (it has been like this for over an hour):

So it just says "loading" and nothing happens.

What I already tried:

Mac restart

Logoff and Login to the App Store

Any ideas?

btw: My Apple membership expires in 5 days - could this be a problem?

答:
Xcode 8.3 requires macOs Sierra
release notes Xcode 8

I was facing the same issue with macOs El Capitan

ContentLicense: CC BY-SA 3.0

Title: Unable to update to Xcode 8.3


问:
Find the most frequent items among the arrays - PHP
I have 3 arrays in my code.

```<code>array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];
</code>```

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

```<code>array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];
</code>```

答:
Try this,

```<code>$array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
$array2 = ['apple', 'jackfruits', 'banana', 'malta'];
$array3 = ['banana', 'grapes', 'apple'];

$arr = array_merge($array1,$array2,$array3);
$count_arr = array_count_values($arr);
arsort($count_arr);
print_r($count_arr);
print_r(array_keys($count_arr));
</code>```

array_count_values states  Counts all the values of an array.

arsort states Sort an array in reverse order and maintain index association.

array_merge states Merge one or more arrays.

array_keys states Return all the keys or a subset of the keys of an array.

Here is working demo.

Give it a try this should work.

Body:
I have 3 arrays in my code.

array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];

Body:
Try this,

$array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
$array2 = ['apple', 'jackfruits', 'banana', 'malta'];
$array3 = ['banana', 'grapes', 'apple'];

$arr = array_merge($array1,$array2,$array3);
$count_arr = array_count_values($arr);
arsort($count_arr);
print_r($count_arr);
print_r(array_keys($count_arr));

array_count_values states  Counts all the values of an array.

arsort states Sort an array in reverse order and maintain index association.

array_merge states Merge one or more arrays.

array_keys states Return all the keys or a subset of the keys of an array.

Here is working demo.

Give it a try this should work.


问:
How to create column chart with percentage Highcharts Angular 2
Hi have the following chart configuration:

```<code>private InputData: any = {
            chart: { type: 'column' },
            title : { text : 'some title' },
            xAxis: {
                categories: ['Monday', 'Tuesday']
            },
            yAxis: {
                allowDecimals: false,
                title: { text: ''}
            },
            series: [
                {
                    name: 'Students',
                    data: [100,80],
                    color: '#3366cc'
                }
            ],
            plotOptions: {
                column: {
                    dataLabels: {
                    enabled: true,
                    formatter: function(){
                        // return Highcharts.numberFormat(this.y,0);
                        }
                    }
                }
            }
        };
</code>```

It works fine. But is there anyway I can make the chart in percentage format? Do I need to use any events or is there any configuration available?

答:
try something like this

Plunker demo

```<code>plotOptions: {
            column: {
                dataLabels: {
                enabled: true,
                formatter: function(){
                  var seriesData=this.series.data;
                  var total=0;
                  for(var i=0;i<seriesData.length;i++){
                    total+=seriesData[i].y
                  }
                  return (100 * this.y / total).toFixed(2) + "%";
                 }
              }
            }
        },
</code>```

Body:
Hi have the following chart configuration:

private InputData: any = {
            chart: { type: 'column' },
            title : { text : 'some title' },
            xAxis: {
                categories: ['Monday', 'Tuesday']
            },
            yAxis: {
                allowDecimals: false,
                title: { text: ''}
            },
            series: [
                {
                    name: 'Students',
                    data: [100,80],
                    color: '#3366cc'
                }
            ],
            plotOptions: {
                column: {
                    dataLabels: {
                    enabled: true,
                    formatter: function(){
                        // return Highcharts.numberFormat(this.y,0);
                        }
                    }
                }
            }
        };

It works fine. But is there anyway I can make the chart in percentage format? Do I need to use any events or is there any configuration available?

Body:
try something like this

Plunker demo

plotOptions: {
            column: {
                dataLabels: {
                enabled: true,
                formatter: function(){
                  var seriesData=this.series.data;
                  var total=0;
                  for(var i=0;i<seriesData.length;i++){
                    total+=seriesData[i].y
                  }
                  return (100 * this.y / total).toFixed(2) + "%";
                 }
              }
            }
        },


问:
Detect a Missing file based on its Date
I need to manually monitor a random windows-based backup program for failures and the only way to do this is via checking for the daily backup file it makes.

A batch file would be simplest for me to implement.  It would need to scan a directory for a certain file type and then do X if a file doesn't exist that was created/modified yesterday.

```<code>C:\backups\random-named-file.tib 27/03/2017
C:\backups\random-named-file.tib 28/03/2017
C:\backups\random-named-file.tib 29/03/2017
</code>```

So if a random-named-file.tib wasnt created or modified yesterday, it means the backup failed and I would write output to the console saying "Backup Failed"

Does anyone please have any ideas ?

EDIT :
To clarify, the backup files are coming from a custom application that has no way to check for missed backups.  The batch file solution I'm looking for will be integrated into our RMM platform, which will take the results of the batch file and raise a support desk ticket for our Service desk to action.

The backup application will apply its own retention policies and delete any backups older then 4 days.
I'm just trying to detect if a backup was missed the previous day.  The filenames are variable, the only constant is the file extension ( *.tib)

This backup app doesn't write eventlogs, nor does it create its own log files I can parse for Failure messages.

答:
I manged to do what you asked. On a quick note, since it's Windows backup program there should be a way to automatically alert when backup fails.

Note about this example: I did this in a specific folder structure. If you want to change the location of batch file, second line of code inside batch file needs to be updated with appropriate path. In this example the path is relative, but it's easy to change, so I leave that up to you.

Here is my folder structure:

```<code>\---batch                          # Folder with batch file
        backups.txt                       # check_backups.bat creates this file
        check_backups.bat                 # Batch file that does the job
|   filename1.tib
|   filename2.tib
|   filename3.tib
|   filename5.tib
</code>```

Here is the code of batch file (check_backups.bat):

```<code>@echo off
dir ..\* /a-d /b > "%~dp0\backups.txt"
set count=1
setlocal EnableDelayedExpansion
FOR /F "delims=*" %%A IN (backups.txt) DO (
    SET fl=%%~nA
    IF !fl:~8! NEQ !count! (
        echo Backup Failed: Missing file is 'filename!count!.tib'
        goto failed
    )
    SET /A count=!count!+1
)

echo All is good

:failed

pause
</code>```

If filename9.tib is missing you will get a message: "Backup failed: Missing file is filename9.tib".

If everyhing is good you will get a message: "All is good".

Title: Detect a Missing file based on its Date

Body:
I need to manually monitor a random windows-based backup program for failures and the only way to do this is via checking for the daily backup file it makes.

A batch file would be simplest for me to implement.  It would need to scan a directory for a certain file type and then do X if a file doesn't exist that was created/modified yesterday.

C:\backups\random-named-file.tib 27/03/2017
C:\backups\random-named-file.tib 28/03/2017
C:\backups\random-named-file.tib 29/03/2017

So if a random-named-file.tib wasnt created or modified yesterday, it means the backup failed and I would write output to the console saying "Backup Failed"

Does anyone please have any ideas ?

EDIT :
To clarify, the backup files are coming from a custom application that has no way to check for missed backups.  The batch file solution I'm looking for will be integrated into our RMM platform, which will take the results of the batch file and raise a support desk ticket for our Service desk to action.

The backup application will apply its own retention policies and delete any backups older then 4 days.
I'm just trying to detect if a backup was missed the previous day.  The filenames are variable, the only constant is the file extension ( *.tib)

This backup app doesn't write eventlogs, nor does it create its own log files I can parse for Failure messages.

Body:
I manged to do what you asked. On a quick note, since it's Windows backup program there should be a way to automatically alert when backup fails.

Note about this example: I did this in a specific folder structure. If you want to change the location of batch file, second line of code inside batch file needs to be updated with appropriate path. In this example the path is relative, but it's easy to change, so I leave that up to you.

Here is my folder structure:

\---batch                          # Folder with batch file
        backups.txt                       # check_backups.bat creates this file
        check_backups.bat                 # Batch file that does the job
|   filename1.tib
|   filename2.tib
|   filename3.tib
|   filename5.tib

Here is the code of batch file (check_backups.bat):

@echo off
dir ..\* /a-d /b > "%~dp0\backups.txt"
set count=1
setlocal EnableDelayedExpansion
FOR /F "delims=*" %%A IN (backups.txt) DO (
    SET fl=%%~nA
    IF !fl:~8! NEQ !count! (
        echo Backup Failed: Missing file is 'filename!count!.tib'
        goto failed
    )
    SET /A count=!count!+1
)

echo All is good

:failed

pause

If filename9.tib is missing you will get a message: "Backup failed: Missing file is filename9.tib".

If everyhing is good you will get a message: "All is good".


问:
which left join is better in laravel
I have a users table and follows table and two models for both. I have user left join to fetch the data from the table, but I am confused to use which model and join table (i.e).

```<code>$user = Follows::select( 'users.id', 'users.username', 'users.photo' )
            ->leftJoin('users', 'follows.fk_users_id', '=', 'users.id')
            ->where('follows.follower_users_id' ,'=', $id)
            ->get();
</code>```

or

```<code>$user = Users::select( 'users.id', 'users.username', 'users.photo' )
            ->leftJoin('follows', 'follows.fk_users_id', '=', 'users.id')
            ->where('follows.follower_users_id' ,'=', $id)
            ->get();
</code>```

I am coding this in Follows model But I only need data from users table where it meets the condition with follows table, need your help as I am new to laravel.

My question is whether to use Follows model and left join users table or use Users model and left join follows table

答:
Both the SQL JOINS are same in terms of SQL but when we look at ORM level in Laravel things change.

If we are using the Follows model then you will only be able to call the relationships defined in Follows model. If you use the Users model then you will be able to use the relationships defined against Users model.

NOTE Use explain in SQL and you will find the query execution path are same.

Title: which left join is better in laravel

Body:
I have a users table and follows table and two models for both. I have user left join to fetch the data from the table, but I am confused to use which model and join table (i.e).

$user = Follows::select( 'users.id', 'users.username', 'users.photo' )
            ->leftJoin('users', 'follows.fk_users_id', '=', 'users.id')
            ->where('follows.follower_users_id' ,'=', $id)
            ->get();

or

$user = Users::select( 'users.id', 'users.username', 'users.photo' )
            ->leftJoin('follows', 'follows.fk_users_id', '=', 'users.id')
            ->where('follows.follower_users_id' ,'=', $id)
            ->get();

I am coding this in Follows model But I only need data from users table where it meets the condition with follows table, need your help as I am new to laravel.

My question is whether to use Follows model and left join users table or use Users model and left join follows table


问:
Can't name column in SQL Server after merge
I cannot save my results from the below (in the form of a view) as the second column has no name and I cannot add a "as" name to it or it no longer works.

The statement below is merging like rows and concatenating the different values where there are multiple results, regarding the bank details.

```<code>select [Pers#No#],
        stuff(( Select distinct ', ' +
                        cast( [Bank Account] as varchar(20) ) +  ' ' +
                        cast( [Bank Keys] as varchar(20) )
                FROM     [DATA].[dbo].[PA0009]                  as      S
                where   S.[Pers#No#] = T.[Pers#No#]
                For     XML PATH('')),1,1,''    )
from    [DATA].[dbo].[PA0009]
group by [Pers#No#]
</code>```

答:
Personally, I find this a lot clearer and you also exccute the XMLPath once per [Pers#No#] value

```<code>select
    p.[Pers#No#],
    MyColumnName = STUFF(X.CSVValue, 1, 2, '')
from
    (SELECT DISTINCT [Pers#No#] FROM [DATA].[dbo].[PA0009]) S
    CROSS APPLY
    (
    Select distinct
        CSVValue = ', ' + cast( [Bank Account] as varchar(20) ) +  ' ' +  CAST( [Bank Keys] as varchar(20) )
    FROM     [DATA].[dbo].[PA0009] T
    where   S.[Pers#No#] = T.[Pers#No#]
    For     XML PATH('')
    ) X
</code>```

(Untested)

Body:
I cannot save my results from the below (in the form of a view) as the second column has no name and I cannot add a "as" name to it or it no longer works.

The statement below is merging like rows and concatenating the different values where there are multiple results, regarding the bank details.

select [Pers#No#],
        stuff(( Select distinct ', ' +
                        cast( [Bank Account] as varchar(20) ) +  ' ' +
                        cast( [Bank Keys] as varchar(20) )
                FROM     [DATA].[dbo].[PA0009]                  as      S
                where   S.[Pers#No#] = T.[Pers#No#]
                For     XML PATH('')),1,1,''    )
from    [DATA].[dbo].[PA0009]
group by [Pers#No#]

Body:
Personally, I find this a lot clearer and you also exccute the XMLPath once per [Pers#No#] value

select
    p.[Pers#No#],
    MyColumnName = STUFF(X.CSVValue, 1, 2, '')
from
    (SELECT DISTINCT [Pers#No#] FROM [DATA].[dbo].[PA0009]) S
    CROSS APPLY
    (
    Select distinct
        CSVValue = ', ' + cast( [Bank Account] as varchar(20) ) +  ' ' +  CAST( [Bank Keys] as varchar(20) )
    FROM     [DATA].[dbo].[PA0009] T
    where   S.[Pers#No#] = T.[Pers#No#]
    For     XML PATH('')
    ) X

(Untested)


问:
Visual Studio adding DLL as reference error
I'm adding a library to a project, and I get the following error:

Mixed mode assembly is built against
  version 'v2.0.50727' of the runtime
  and cannot be loaded in the 4.0
  runtime without additional
  configuration information.

I'm not too sure about what I have to tweak in order fro this to run. Anyone know what the changes should be?

Thanks,

PM

答:
As Marc says, ideally you'd rebuild in .NET 4, or make your project target .NET 3.5 or lower. Mixed-mode assemblies built for the v2 CLR use "legacy" runtime activation techniques which don't work well with the v4 CLR's ability to run multiple CLRs in the same process.

Alternatively, you can add this information to your app.config:

```<code><configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
  </startup>
</configuration>
</code>```

See this question, this documentation and this blog post for details.

Body:
As Marc says, ideally you'd rebuild in .NET 4, or make your project target .NET 3.5 or lower. Mixed-mode assemblies built for the v2 CLR use "legacy" runtime activation techniques which don't work well with the v4 CLR's ability to run multiple CLRs in the same process.

Alternatively, you can add this information to your app.config:

<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
  </startup>
</configuration>

See this question, this documentation and this blog post for details.


问:
Collapse tableView rows on a row select in swift
i have a tableView where i show user created circle name and i want when the user select a circle name rest circle name collapse and show only one circle name. but i don't know how to do that. please help help me guys.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if indexPath.section == 0
    {
        // here is the code to collapse the row
    }
 }
</code>```

Section == 0 have the rows of circle names.

答:
Custom other cell for collapsed circel name cell.
such as CollapsedCell</p>

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "kCollapsedCell", for: indexPath) as CollapsedCell {
            cell.doSomething()
        }
    }
}
</code>```

Body:
i have a tableView where i show user created circle name and i want when the user select a circle name rest circle name collapse and show only one circle name. but i don't know how to do that. please help help me guys.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if indexPath.section == 0
    {
        // here is the code to collapse the row
    }
 }

Section == 0 have the rows of circle names.

Body:
Custom other cell for collapsed circel name cell.
such as CollapsedCell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "kCollapsedCell", for: indexPath) as CollapsedCell {
            cell.doSomething()
        }
    }
}


问:
Running multiple threads concurrenty using ScheduledExecutorService
The below code executes a file transfer task periodically. I want to do another file copy task at same time from different location by calling the same method.For that i created another runnable2 and executor2 instances and executed. How to do multiple tasks using a single instance instead of creating multiple instances.</p>

```<code>public static void main(String[] args) {

        Runnable runnable = new Runnable() {
          public void run() {

            File srcFolder = new File("c:\\location1\\Test1\\");
            File destFolder = new File("d:\\location1\\Test1\\");

            if(!srcFolder.exists()){
               System.out.println("Directory does not exist.");
               System.exit(0);
            }else{
               try{
                copyFolder(srcFolder,destFolder);
               }catch(IOException e){
                e.printStackTrace();
                System.exit(0);
               }
            }
            System.out.println("Done");
            }
        };

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(runnable, 0, 300, TimeUnit.SECONDS);
}
</code>```

答:
if you are going to do the same operation more than one time, then creating a class is better than anonymous class (make it have 2 params in constructor):

```<code>public class FileCopy implements Runnable {

    private String src="", dest = "";
    public FileCopy(String src, String dest){
        this.src  = src;
        this.dest = dest;
    }

    @override
    public void run(){
        File srcFolder = new File(src);
        File destFolder = new File(dest);

        if(!srcFolder.exists()){
           System.out.println("Directory does not exist.");
           //System.exit(0);
        }else{
           try{
            copyFolder(srcFolder,destFolder);
           }catch(IOException e){
            e.printStackTrace();
            //System.exit(0);
           }
        }
        System.out.println("Done");
    }//run
}
</code>```

now you can make as many instances as you want, pass different params each time, and execute the Runnable

```<code>ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new FileCopy(src1, dest1), 0, 300, TimeUnit.SECONDS);
executor.scheduleAtFixedRate(new FileCopy(src2, dest2), 0, 300, TimeUnit.SECONDS);
</code>```

Notes: :

may be you need to change this newScheduledThreadPool(1) to newScheduledThreadPool(2)? not so sure

System.exit(0); is not an option now, in case of errors, because you have multiple instances running, if one has a problem, that should not mean closing the whole app, you need to implement another way to handle errors

Body:
The below code executes a file transfer task periodically. I want to do another file copy task at same time from different location by calling the same method.For that i created another runnable2 and executor2 instances and executed. How to do multiple tasks using a single instance instead of creating multiple instances.

public static void main(String[] args) {

        Runnable runnable = new Runnable() {
          public void run() {

            File srcFolder = new File("c:\\location1\\Test1\\");
            File destFolder = new File("d:\\location1\\Test1\\");

            if(!srcFolder.exists()){
               System.out.println("Directory does not exist.");
               System.exit(0);
            }else{
               try{
                copyFolder(srcFolder,destFolder);
               }catch(IOException e){
                e.printStackTrace();
                System.exit(0);
               }
            }
            System.out.println("Done");
            }
        };

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(runnable, 0, 300, TimeUnit.SECONDS);
}

Body:
if you are going to do the same operation more than one time, then creating a class is better than anonymous class (make it have 2 params in constructor):

public class FileCopy implements Runnable {

    private String src="", dest = "";
    public FileCopy(String src, String dest){
        this.src  = src;
        this.dest = dest;
    }

    @override
    public void run(){
        File srcFolder = new File(src);
        File destFolder = new File(dest);

        if(!srcFolder.exists()){
           System.out.println("Directory does not exist.");
           //System.exit(0);
        }else{
           try{
            copyFolder(srcFolder,destFolder);
           }catch(IOException e){
            e.printStackTrace();
            //System.exit(0);
           }
        }
        System.out.println("Done");
    }//run
}

now you can make as many instances as you want, pass different params each time, and execute the Runnable

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new FileCopy(src1, dest1), 0, 300, TimeUnit.SECONDS);
executor.scheduleAtFixedRate(new FileCopy(src2, dest2), 0, 300, TimeUnit.SECONDS);

Notes: :

may be you need to change this newScheduledThreadPool(1) to newScheduledThreadPool(2)? not so sure

System.exit(0); is not an option now, in case of errors, because you have multiple instances running, if one has a problem, that should not mean closing the whole app, you need to implement another way to handle errors


答:
You should specify an alias to the column returning from the subquery:</p>

```<code>select [Pers#No#],
        stuff(( Select distinct ', ' +
                        cast( [Bank Account] as varchar(20) ) +  ' ' +
                        cast( [Bank Keys] as varchar(20) )
                FROM     [DATA].[dbo].[PA0009]                  as      S
                where   S.[Pers#No#] = T.[Pers#No#]
                For     XML PATH('')),1,1,''    )  as whatever
from    [DATA].[dbo].[PA0009]
group by [Pers#No#]
</code>```

Title: Can't name column in SQL Server after merge

Body:
You should specify an alias to the column returning from the subquery:

select [Pers#No#],
        stuff(( Select distinct ', ' +
                        cast( [Bank Account] as varchar(20) ) +  ' ' +
                        cast( [Bank Keys] as varchar(20) )
                FROM     [DATA].[dbo].[PA0009]                  as      S
                where   S.[Pers#No#] = T.[Pers#No#]
                For     XML PATH('')),1,1,''    )  as whatever
from    [DATA].[dbo].[PA0009]
group by [Pers#No#]


问:
Android : How to write camera intent in android nougat
In my android application I have to take images using the camera when a button is clicked. It is working perfectly in all Android versions except Android 7 (Nougat). When I choose the camera option, the app is exiting even if the permissions are granted. I think the problem is in the camera-calling Intent. Below is my code.

```<code>camera = (ImageView) dialog.findViewById(R.id.camera);

camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        clickCamera();
        dialog.dismiss();
    }
});

private void clickCamera() { // 1 for icon and 2 for attachment
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.CAMERA }, MY_REQUEST_CODE);
    } else {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
        } else {
            currentImageUri = getImageFileUri();
            Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
            // start the image capture Intent
            startActivityForResult(intentPicture, REQUEST_CAMERA);  // 1 for REQUEST_CAMERA (icon) and 2 for REQUEST_CAMERA_ATT (attachment)
        }
    }
}

private static Uri getImageFileUri(){
    // Create a storage directory for the images
    // To be safe(r), you should check that the SD card is mounted
    // using Environment.getExternalStorageState() before doing this

    imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyProject");
    if (!imagePath.exists()) {
        if (!imagePath.mkdirs()) {
            return null;
        } else {
            // create new folder
        }
    }

    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File image = new File(imagePath, "MyProject_" + timeStamp + ".jpg");

    if (!image.exists()) {
        try {
            image.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Create an File Uri
    return Uri.fromFile(image);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
                } else {
                    currentImageUri = getImageFileUri();
                    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                    // start the image capture Intent
                    startActivityForResult(intentPicture, REQUEST_CAMERA);
                }
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission... ", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case MY_REQUEST_CODE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                currentImageUri = getImageFileUri();
                Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                // start the image capture Intent
                startActivityForResult(intentPicture, REQUEST_CAMERA);
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission...", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}
</code>```

What is the problem here for Nougat? Is it because of the Uri returned by getImageFileUri()?

答:
Try this its not the intent that create the problem once you take the picture and save to the sd card and getting back the uri is different in Nougat....

It is quite easy to implement FileProvider on your application. First you need to add a FileProvider tag in AndroidManifest.xml under tag like below: AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>
</code>```

And then create a provider_paths.xml file in xml folder under res folder. Folder may be needed to create if it doesn't exist.

res/xml/provider_paths.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
</code>```

Done! FileProvider is now declared and be ready to use.

The final step is to change the line of code below in MainActivity.java

```<code>Uri photoURI = Uri.fromFile(createImageFile());
</code>```

to

```<code>Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
            BuildConfig.APPLICATION_ID + ".provider",
            createImageFile());
</code>```

And .... done ! Your application should now work perfectly fine on any Android version including Android Nougat. Cheers  !

ContentLicense: CC BY-SA 4.0

Body:
In my android application I have to take images using the camera when a button is clicked. It is working perfectly in all Android versions except Android 7 (Nougat). When I choose the camera option, the app is exiting even if the permissions are granted. I think the problem is in the camera-calling Intent. Below is my code.

camera = (ImageView) dialog.findViewById(R.id.camera);

camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        clickCamera();
        dialog.dismiss();
    }
});

private void clickCamera() { // 1 for icon and 2 for attachment
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.CAMERA }, MY_REQUEST_CODE);
    } else {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
        } else {
            currentImageUri = getImageFileUri();
            Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
            // start the image capture Intent
            startActivityForResult(intentPicture, REQUEST_CAMERA);  // 1 for REQUEST_CAMERA (icon) and 2 for REQUEST_CAMERA_ATT (attachment)
        }
    }
}

private static Uri getImageFileUri(){
    // Create a storage directory for the images
    // To be safe(r), you should check that the SD card is mounted
    // using Environment.getExternalStorageState() before doing this

    imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyProject");
    if (!imagePath.exists()) {
        if (!imagePath.mkdirs()) {
            return null;
        } else {
            // create new folder
        }
    }

    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File image = new File(imagePath, "MyProject_" + timeStamp + ".jpg");

    if (!image.exists()) {
        try {
            image.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Create an File Uri
    return Uri.fromFile(image);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_REQUEST_CODE_STORAGE);
                } else {
                    currentImageUri = getImageFileUri();
                    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                    // start the image capture Intent
                    startActivityForResult(intentPicture, REQUEST_CAMERA);
                }
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission... ", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case MY_REQUEST_CODE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                currentImageUri = getImageFileUri();
                Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri); // set the image file name
                // start the image capture Intent
                startActivityForResult(intentPicture, REQUEST_CAMERA);
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "Doesn't have permission...", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}

What is the problem here for Nougat? Is it because of the Uri returned by getImageFileUri()?

Body:
Try this its not the intent that create the problem once you take the picture and save to the sd card and getting back the uri is different in Nougat....

It is quite easy to implement FileProvider on your application. First you need to add a FileProvider tag in AndroidManifest.xml under tag like below: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>

And then create a provider_paths.xml file in xml folder under res folder. Folder may be needed to create if it doesn't exist.

res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Done! FileProvider is now declared and be ready to use.

The final step is to change the line of code below in MainActivity.java

Uri photoURI = Uri.fromFile(createImageFile());

to

Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
            BuildConfig.APPLICATION_ID + ".provider",
            createImageFile());

And .... done ! Your application should now work perfectly fine on any Android version including Android Nougat. Cheers  !


问:
Python how to share package between multiple projects
I have a package that contains protocols for specific hardware from multiple vendors. This is basically a collection of multiple different protocols that have similar interface. It is ported to python by me. But now I have two projects that handle communication with this equipment using different transport protocols one is over TCP another is over RS-485/232. How to share the package with protocols between this two projects so that I don't need to copy it after I add new functionality support or bug fixes.</p>

答:
You can build a python package (more info here: https://python-packaging.readthedocs.io/en/latest/)

Once you have created your package containing a setup.py file, you can install it on your machine using the:

pip install -e myPackage

command. (Where "myPacakge" is the folder containing the setup.py file). The advantage of using the -e flag is that changes made to your package are directly included in the installed version.

Once your package is installed, you can share it across multiple projects, simply by importing your package in Python, e.g.

```<code>import myPackage as myPackge
</code>```

Body:
You can build a python package (more info here: https://python-packaging.readthedocs.io/en/latest/)

Once you have created your package containing a setup.py file, you can install it on your machine using the:

pip install -e myPackage

command. (Where "myPacakge" is the folder containing the setup.py file). The advantage of using the -e flag is that changes made to your package are directly included in the installed version.

Once your package is installed, you can share it across multiple projects, simply by importing your package in Python, e.g.

import myPackage as myPackge


问:
Extract Substring from String java
I want to extract specific substrings from a string:

```<code>String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+
"info2 info2ContentA";
</code>```

The result should be:

```<code>String info1 ="info1ContentA info1ContentB";
String info2 ="info2ContentA";
String info3 ="info3ContentA info3ContentB";
</code>```

For me it's very difficult to extract the informations, because sometimes after "info" their are one, two or more content informations. Another problem that occurs is, that the order of info1, info2 etc. is not sorted and the "real data" doesn't contain a ascending number.

My first idea was to add info1, info2, info3 etc to an ArrayList.

```<code>private ArrayList<String> arr = new ArrayList<String>();
arr.add("info1");
arr.add("info2");
arr.add("info3");
</code>```

Now I want to extract the substring with the method StringUtils.substringBetween() from Apache Commons (https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4):

```<code>String result = StringUtils.substringBetween(source, arr.get(0), arr.get(1));
</code>```

This works, if info1 is in the string before info2, but like I said the "real data" is not sorted.

Any idea how I can fix this?

答:
You can use a regular expression, like this:</p>

```<code>String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB info2 info2ContentA";
for (int i = 1; i < 3; i++) {
    Pattern pattern = Pattern.compile("info" + i + "Content[A-Z]");
    Matcher matcher = pattern.matcher(source);
    List<String> matches = new ArrayList<>();
    while (matcher.find()) {
        matches.add(matcher.group());
    }
    // process the matches list
}
</code>```

Title: Extract Substring from String java

Body:
I want to extract specific substrings from a string:

String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+
"info2 info2ContentA";

The result should be:

String info1 ="info1ContentA info1ContentB";
String info2 ="info2ContentA";
String info3 ="info3ContentA info3ContentB";

For me it's very difficult to extract the informations, because sometimes after "info" their are one, two or more content informations. Another problem that occurs is, that the order of info1, info2 etc. is not sorted and the "real data" doesn't contain a ascending number.

My first idea was to add info1, info2, info3 etc to an ArrayList.

private ArrayList<String> arr = new ArrayList<String>();
arr.add("info1");
arr.add("info2");
arr.add("info3");

Now I want to extract the substring with the method StringUtils.substringBetween() from Apache Commons (https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4):

String result = StringUtils.substringBetween(source, arr.get(0), arr.get(1));

This works, if info1 is in the string before info2, but like I said the "real data" is not sorted.

Any idea how I can fix this?

Body:
You can use a regular expression, like this:

String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB info2 info2ContentA";
for (int i = 1; i < 3; i++) {
    Pattern pattern = Pattern.compile("info" + i + "Content[A-Z]");
    Matcher matcher = pattern.matcher(source);
    List<String> matches = new ArrayList<>();
    while (matcher.find()) {
        matches.add(matcher.group());
    }
    // process the matches list
}


问:
Pass route parameter to controller in ExpressJS
I'm using passport JS to authenticate my user account. Passing the passport variable from app.js to routes.js and controller.js. When I pass between routes.js and controller.js, I have no idea how to implement. I tried different approaches but didn't work. My first priority was stored all the implementation codes inside controller instead of routes.

App.js

```<code>var userRouter = require('./api/routes/userRoutes.js')(app,passport);
</code>```

Routes.js

```<code>module.exports = function(app,passport){
  var UserRouter = express.Router();
  users = require('./../controllers/UserController')
  UserRouter.post('/users', users.authenticate);
}
</code>```

Controller.js

```<code>exports.authenticate = function(req, res, next){
    // How do I get passport variable here?
}
</code>```

答:
Not sure that it is the best way in this case, but like an option you can try this:

In App.js:

```<code>global. passport = passport;
var userRouter = require('./api/routes/userRoutes.js')(app, passport);
</code>```

In Controller.js:

```<code>exports.authenticate = function(req, res, next) {
    console.log(global.passport);
}
</code>```

Body:
I'm using passport JS to authenticate my user account. Passing the passport variable from app.js to routes.js and controller.js. When I pass between routes.js and controller.js, I have no idea how to implement. I tried different approaches but didn't work. My first priority was stored all the implementation codes inside controller instead of routes.

App.js

var userRouter = require('./api/routes/userRoutes.js')(app,passport);

Routes.js

module.exports = function(app,passport){
  var UserRouter = express.Router();
  users = require('./../controllers/UserController')
  UserRouter.post('/users', users.authenticate);
}

Controller.js

exports.authenticate = function(req, res, next){
    // How do I get passport variable here?
}

Body:
Not sure that it is the best way in this case, but like an option you can try this:

In App.js:

global. passport = passport;
var userRouter = require('./api/routes/userRoutes.js')(app, passport);

In Controller.js:

exports.authenticate = function(req, res, next) {
    console.log(global.passport);
}


问:
HTML Send selected option to PHP via Ajax on same page
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

```<code><div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <tr>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </tr>
                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "<tr>";
                            echo "<th>" . $i . "</th>";
                            echo "<th>" . $row['userName'] . "</th>";
                            echo "<th>" . $row['score'] . "</th>";
                            echo "</tr>";
                        }
                    ?>
                </table>
            </div>
        </div>
</code>```

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

答:
Use JQuery AJAX something like so:

Make two pages one where you display data(index.php) and other from where you fetch data (process.php).

The content of index.php would be something like:

```<code><div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select onChange="getData();" id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <thead>
                    <th>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </th>
                    </thead>
                    <tbody id="data"></tbody>
                </table>
            </div>
        </div>
</code>```

The code of process.php should be something liek:

```<code>            <?php
                $i = 0;
                if($_REQUEST['sortBy'] == "score ASC")
                {
                $choice = "score ASC";
                }
                 else if ()//and so on

                $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice) or die(mysqli_error($connect));

                while($row = mysqli_fetch_array($search)){
                    $i++;
                    echo "<tr>";
                    echo "<th>" . $i . "</th>";
                    echo "<th>" . $row['userName'] . "</th>";
                    echo "<th>" . $row['score'] . "</th>";
                    echo "</tr>";
                }
            ?>
</code>```

Your Javascript should be like:

```<code>            function getData()
            {
            $.ajax({
                url     : 'process.php',
                method    : 'GET',
                data:{ sortBy:$('#selectForm').val() }
                success   : function(response)
                {
                   $('#data').html(response);
                },
                error : function(e)
                {
                    alert('error');
                }
            });
          }
</code>```

Body:
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

Highscores

                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>

                        Position
                        Name
                        Score

                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "
";
                            echo "" . $i . "	";
                            echo "" . $row['userName'] . "	";
                            echo "" . $row['score'] . "	";
                            echo "
";
                        }
                    ?>

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

Body:
Use JQuery AJAX something like so:

Make two pages one where you display data(index.php) and other from where you fetch data (process.php).

The content of index.php would be something like:

<div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select onChange="getData();" id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <thead>
                    <th>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </th>
                    </thead>
                    <tbody id="data"></tbody>
                </table>
            </div>
        </div>

The code of process.php should be something liek:

            <?php
                $i = 0;
                if($_REQUEST['sortBy'] == "score ASC")
                {
                $choice = "score ASC";
                }
                 else if ()//and so on

                $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice) or die(mysqli_error($connect));

                while($row = mysqli_fetch_array($search)){
                    $i++;
                    echo "<tr>";
                    echo "<th>" . $i . "</th>";
                    echo "<th>" . $row['userName'] . "</th>";
                    echo "<th>" . $row['score'] . "</th>";
                    echo "</tr>";
                }
            ?>

Your Javascript should be like:

            function getData()
            {
            $.ajax({
                url     : 'process.php',
                method    : 'GET',
                data:{ sortBy:$('#selectForm').val() }
                success   : function(response)
                {
                   $('#data').html(response);
                },
                error : function(e)
                {
                    alert('error');
                }
            });
          }


答:
Untested, but maybe (from MSDN)</p>

```<code><?xml version="1.0"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>
</code>```

Title: Visual Studio adding DLL as reference error

Body:
I'm adding a library to a project, and I get the following error:

Mixed mode assembly is built against
  version 'v2.0.50727' of the runtime
  and cannot be loaded in the 4.0
  runtime without additional
  configuration information.

I'm not too sure about what I have to tweak in order fro this to run. Anyone know what the changes should be?

Thanks,

PM

Body:
Untested, but maybe (from MSDN)

<?xml version="1.0"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>


问:
Count the exact number of children with jQuery
Im trying to find count the exact number of a child and then add a class to another element matching that class, in this example the parent (it wont be the direct parent where I'm trying to achieve this).

$(".test").each(function(index, elem) {
  var countchild = $(this).find(".child");
  if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
</div></code>```

答:
Try this:

```<code>$('.test').find('.child').length;
</code>```

On the basic of child count you can add class like:

```<code>var arr = ['zero', 'one', 'two', 'three', 'four'];
var count = $('.test').find('.child').length;
$('.test').addClass('one');
</code>```

Updated Fiddle

Body:
Im trying to find count the exact number of a child and then add a class to another element matching that class, in this example the parent (it wont be the direct parent where I'm trying to achieve this).

$(".test").each(function(index, elem) {
  var countchild = $(this).find(".child");
  if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {}
});

1

2

3

4

Body:
Try this:

$('.test').find('.child').length;

On the basic of child count you can add class like:

var arr = ['zero', 'one', 'two', 'three', 'four'];
var count = $('.test').find('.child').length;
$('.test').addClass('one');

Updated Fiddle


问:
Allow access to Named Pipe Server from remote clients
I would like to ask you how to set up possible access to my named pipe server from remote clients. Until now I thought that NamedPipes can be used just for inter-process communication on same computer, but based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa365150%28v=vs.85%29.aspx it should be possible by setting PIPE_ACCEPT_REMOTE_CLIENTS / PIPE_REJECT_REMOTE_CLIENTS to allow/ not allow to access from remote computers. I did not find simple way how to setup this functionality in .NET. I suppose that PipeSecurity could be somehow used for it but I did not find a simple way.

My current solution allows to access all users to my named pipe on current machine. Can somebody improve my solution to allow access from another machine as well?

Thanks.

```<code>    public NamedPipeServerStream CreateNamedPipeServer(string pipeName)
    {
            const int BufferSize = 65535;
            var pipeSecurity = new PipeSecurity();
            pipeSecurity.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite, AccessControlType.Allow));
            pipeSecurity.AddAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.ReadWrite, AccessControlType.Allow));

            return new NamedPipeServerStream(pipeName, PipeDirection.InOut, countOfServerInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.Asynchronous,
                                                               BufferSize,
                                                               BufferSize);
    }
</code>```

答:
this

var transmissionMode =
      (PipeTransmissionMode)((int)PipeTransmissionMode.Byte | (0x8 >> 1));

shouldn't work since the PipeStream ctr is implemented like this:

if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
          throw new ArgumentOutOfRangeException("transmissionMode", SR.GetString("ArgumentOutOfRange_TransmissionModeByteOrMsg"));

Body:
I would like to ask you how to set up possible access to my named pipe server from remote clients. Until now I thought that NamedPipes can be used just for inter-process communication on same computer, but based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa365150%28v=vs.85%29.aspx it should be possible by setting PIPE_ACCEPT_REMOTE_CLIENTS / PIPE_REJECT_REMOTE_CLIENTS to allow/ not allow to access from remote computers. I did not find simple way how to setup this functionality in .NET. I suppose that PipeSecurity could be somehow used for it but I did not find a simple way.

My current solution allows to access all users to my named pipe on current machine. Can somebody improve my solution to allow access from another machine as well?

Thanks.

    public NamedPipeServerStream CreateNamedPipeServer(string pipeName)
    {
            const int BufferSize = 65535;
            var pipeSecurity = new PipeSecurity();
            pipeSecurity.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite, AccessControlType.Allow));
            pipeSecurity.AddAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.ReadWrite, AccessControlType.Allow));

            return new NamedPipeServerStream(pipeName, PipeDirection.InOut, countOfServerInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.Asynchronous,
                                                               BufferSize,
                                                               BufferSize);
    }


问:
http://schemas.android.com/apk/res/android where does this URL point...?
I am not getting where is url: http://schemas.android.com/apk/res/android ?
Can somebody please let me know where does this point to?
Why cannot we access this URL mentioned in xmlns:android namespace for android xml ?

答:
It specifies XML namespace.
So we have to understand what a XML namespace is:
https://www.w3schools.com/xml/xml_namespaces.asp

And why we use URI in name space:
Why are URLs in XML namespaces?


问:
Moment.js with Vuejs
I try to print out date time using like the following in vue-for

{{ moment().format('MMMM Do YYYY, h:mm:ss a') }}
```

but, it does not appear. It's just a blank. How I can try to use moment in vue?

答:
If your project is a single page application, (eg project created by vue init webpack myproject),
I found this way is most intuitive and simple:

In main.js

import moment from 'moment'

Vue.prototype.moment = moment
```
<p>Then in your template, simply use</p>
<pre class="lang-html prettyprint-override"><code><span>{{moment(date).format('YYYY-MM-DD')}}</span>
</code>```

Title: Moment.js with Vuejs

Body:
I try to print out date time using like the following in vue-for

{{ moment().format('MMMM Do YYYY, h:mm:ss a') }}

but, it does not appear. It's just a blank. How I can try to use moment in vue?

Body:
If your project is a single page application, (eg project created by vue init webpack myproject),
I found this way is most intuitive and simple:

In main.js

import moment from 'moment'

Vue.prototype.moment = moment

Then in your template, simply use

<span>{{moment(date).format('YYYY-MM-DD')}}</span>


问:
GROUP BY clause ignoring first column value if second and third are the same
Database server is MySQL

I have an SQL query that does a select with a "GROUP BY" clause as follows:

```<code>SELECT col1, col2, col3, SUM(col4), SUM(col5) where col6 = 20 GROUP BY col1, col2, col3
</code>```

All works well when col2 and col3 have different values but when col2 and col3 have the same value as follows

```<code>col1    col2   col3   col4   col5
a       1      2       1      1
b       1      2       2      2
b       1      2       3      3
c       1      2       4      4
</code>```

the query result is

```<code>c       1      2       10     10
</code>```

I was expecting

```<code>a       1      2       1     1
b       1      2       5     5
c       1      2       4     4
</code>```

Why does the "GROUP BY" ignore the fact that the col1 values are not all the same and just displays that last one it finds?

Thanks in advance

答:
User error - turn out I was aliasing col1 and there was a column of the same name in the table so the GROUP BY was using the column name and not the alias. The column name is question was not even part of the query.

The pitfalls of working on a system that someone else wrote.

Thanks for all your suggestions/comments

Body:
Database server is MySQL

I have an SQL query that does a select with a "GROUP BY" clause as follows:

SELECT col1, col2, col3, SUM(col4), SUM(col5) where col6 = 20 GROUP BY col1, col2, col3

All works well when col2 and col3 have different values but when col2 and col3 have the same value as follows

col1    col2   col3   col4   col5
a       1      2       1      1
b       1      2       2      2
b       1      2       3      3
c       1      2       4      4

the query result is

c       1      2       10     10

I was expecting

a       1      2       1     1
b       1      2       5     5
c       1      2       4     4

Why does the "GROUP BY" ignore the fact that the col1 values are not all the same and just displays that last one it finds?

Thanks in advance


答:
Are you sure? It worked for me:

```<code>CREATE TABLE PA0009 ([Pers#No#] INT , [Bank Account] VARCHAR(10), [Bank Keys] VARCHAR(10))

SELECT [Pers#No#]
    ,stuff((
            SELECT DISTINCT ', ' + cast([Bank Account] AS VARCHAR(20)) + ' ' + cast([Bank Keys] AS VARCHAR(20))
            FROM  [PA0009] AS S
            WHERE S.[Pers#No#] = 132
            FOR XML PATH('')
            ), 1, 1, '')  AS X
FROM  [PA0009]
GROUP BY [Pers#No#]
</code>```

Output:

```<code>Pers#No#    X
----------- ---------
</code>```

Body:
I cannot save my results from the below (in the form of a view) as the second column has no name and I cannot add a "as" name to it or it no longer works.

The statement below is merging like rows and concatenating the different values where there are multiple results, regarding the bank details.

select [Pers#No#],
        stuff(( Select distinct ', ' +
                        cast( [Bank Account] as varchar(20) ) +  ' ' +
                        cast( [Bank Keys] as varchar(20) )
                FROM     [DATA].[dbo].[PA0009]                  as      S
                where   S.[Pers#No#] = T.[Pers#No#]
                For     XML PATH('')),1,1,''    )
from    [DATA].[dbo].[PA0009]
group by [Pers#No#]

Body:
Are you sure? It worked for me:

CREATE TABLE PA0009 ([Pers#No#] INT , [Bank Account] VARCHAR(10), [Bank Keys] VARCHAR(10))

SELECT [Pers#No#]
    ,stuff((
            SELECT DISTINCT ', ' + cast([Bank Account] AS VARCHAR(20)) + ' ' + cast([Bank Keys] AS VARCHAR(20))
            FROM  [PA0009] AS S
            WHERE S.[Pers#No#] = 132
            FOR XML PATH('')
            ), 1, 1, '')  AS X
FROM  [PA0009]
GROUP BY [Pers#No#]

Output:

Pers#No#    X
----------- ---------


问:
Max columns in html table
what is the max. no of columns and rows in a html table? Are there any browser issues while viewing the table?</p>

答:
No. There is no as such limit to rows & columns. But

It will definitely add horizontal & vertical scroll to your page. Too much scrolling can make your page practically impossible to view.

Also your page size will increase a lot causing performance issue.

Use will loose interest in your page, due to too much contents & bad user experience

Title: Max columns in html table


问:
EntityFramework Interceptor not working in Config File
I am trying to integrate IDbCommandInterceptor to my project. I am using EntityFramework version 6.0. I created interceptor class like this:

```<code>namespace MyApp.Data
{
    public class EFCommandInterceptor : IDbCommandInterceptor
    {
        public void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        private void LogInfo(string command, string commandText)
        {
            Console.WriteLine("Intercepted on: {0} :- {1} ", command, commandText);
        }
    }
}
</code>```

When I try to add this interceptor class using code configuration then its working fine. But I want to add this interceptor using config setting as mention in article Interception. My config file looks like this:

```<code><entityFramework>
<interceptors>
  <interceptor type="MyApp.Data.EFCommandInterceptor, MyApp.Data"></interceptor>
</interceptors>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</code>```

But it is giving error that:

Unrecognized element 'interceptors'

I have entity config setting in app config file:

```<code><configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</code>```

Note: My data access layer is in separate class library. EDMX file is present in Data project. Presentation layer has reference to Data layer. Entity framework is present in both the project and has same version.

答:
I have resolved the issue by just updating the version of Entity Framework.

Older Version: 6.0.2
Updated Version: 6.1.3

Body:
I am trying to integrate IDbCommandInterceptor to my project. I am using EntityFramework version 6.0. I created interceptor class like this:

namespace MyApp.Data
{
    public class EFCommandInterceptor : IDbCommandInterceptor
    {
        public void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        private void LogInfo(string command, string commandText)
        {
            Console.WriteLine("Intercepted on: {0} :- {1} ", command, commandText);
        }
    }
}

When I try to add this interceptor class using code configuration then its working fine. But I want to add this interceptor using config setting as mention in article Interception. My config file looks like this:

<entityFramework>
<interceptors>
  <interceptor type="MyApp.Data.EFCommandInterceptor, MyApp.Data"></interceptor>
</interceptors>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>

But it is giving error that:

Unrecognized element 'interceptors'

I have entity config setting in app config file:

<configSections>

Note: My data access layer is in separate class library. EDMX file is present in Data project. Presentation layer has reference to Data layer. Entity framework is present in both the project and has same version.


问:
Adding color to Polar Scatter plot data points
I'm trying to make a polar plot with Python, of which I've been somewhat successful so far

polar scatter plot example

I did have a few questions for which I was hoping to get some ideas/suggestions:

is it possible set the color of the circles to a specific value (e.g.: "n" in the sample code below)? If so, can I set specific color ranges? E.g: 0-30: red color, 31-40: yellow; 41-60: green

Note: following the examples from Plot with conditional colors based on values in R, I tried ax.scatter(ra,dec,c = ifelse(n < 30,’red','green'), pch = 19 ) without success =(

how can I make the data circles a little bit bigger?

can I move the "90" label so that the graph title does not overlap? I tried:
x.set_rlabel_position(-22.5) but I get an error ("AttributeError: 'PolarAxes' object has no attribute 'set_rlabel_position'")

Is it possible to only show the 0,30, and 60 elevation labels? Can these be oriented horizontally (e.g.: along the 0 azimuth line)?

Thank you so much! Looking forward to hearing your suggestions =)

```<code>import numpy
import matplotlib.pyplot as pyplot

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*3.141593 for x in ra]
fig = pyplot.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8],polar=True)
ax.set_ylim(0,90)
ax.set_yticks(numpy.arange(0,90,10))
ax.scatter(ra,dec,c ='r')
ax.set_title("Graph Title here", va='bottom')
pyplot.show()
</code>```

答:
1. colorize points

Using the c argument of scatter allows to colorize the points. In thei caase you may supply the n array to it and let the color be chosen accoring to a colormap. The colormap would consist of the different colors (31 times red, 10 times yellow, 20 times green).
The advantage of using a colormap is that it allows to easily use a colorbar.

2. making circles bigger can be done using the s argument.

3. adding space between label and title This would best be done by moving the title a bit upwards, using  the y argument to set_title. In order for the title not to go outside the figure, we can use the subplots_adjust method and make top a little smaller. (Note that this works only if the axes are created via subplots.)

4.  Only show certain ticks can be accomplished by setting
the ticks as ax.set_yticks([0,30,60]) and orienting ylabels along a horizontal line is done by ax.set_rlabel_position(0). (Note that set_rlabel_position is available from version 1.4 on, if you have an earlier version, consider updating).

```<code>import numpy as np
import matplotlib.pyplot as plt # don't use pylab
import matplotlib.colors
import matplotlib.cm

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*np.pi for x in ra]
fig = plt.figure()
ax = fig.add_subplot(111,polar=True)
ax.set_ylim(0,90)

# 4. only show 0,30, 60 ticks
ax.set_yticks([0,30,60])
# 4. orient ylabels along horizontal line
ax.set_rlabel_position(0)

# 1. prepare cmap and norm
colors= ["red"] * 31 + ["gold"] * 10 + ["limegreen"] * 20
cmap=matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.Normalize(vmin=0, vmax=60)
# 2. make circles bigger, using `s` argument
# 1. set different colors according to `n`
sc = ax.scatter(ra,dec,c =n, s=49, cmap=cmap, norm=norm, zorder=2)

# 1. make colorbar
cax = fig.add_axes([0.8,0.1,0.01,0.2])
fig.colorbar(sc, cax=cax, label="n", ticks=[0,30,40,60])
# 3. move title upwards, then adjust top spacing
ax.set_title("Graph Title here", va='bottom', y=1.1)
plt.subplots_adjust(top=0.8)

plt.show()
</code>```

Body:
I'm trying to make a polar plot with Python, of which I've been somewhat successful so far

polar scatter plot example

I did have a few questions for which I was hoping to get some ideas/suggestions:

is it possible set the color of the circles to a specific value (e.g.: "n" in the sample code below)? If so, can I set specific color ranges? E.g: 0-30: red color, 31-40: yellow; 41-60: green

Note: following the examples from Plot with conditional colors based on values in R, I tried ax.scatter(ra,dec,c = ifelse(n < 30,’red','green'), pch = 19 ) without success =(

how can I make the data circles a little bit bigger?

can I move the "90" label so that the graph title does not overlap? I tried:
x.set_rlabel_position(-22.5) but I get an error ("AttributeError: 'PolarAxes' object has no attribute 'set_rlabel_position'")

Is it possible to only show the 0,30, and 60 elevation labels? Can these be oriented horizontally (e.g.: along the 0 azimuth line)?

Thank you so much! Looking forward to hearing your suggestions =)

import numpy
import matplotlib.pyplot as pyplot

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*3.141593 for x in ra]
fig = pyplot.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8],polar=True)
ax.set_ylim(0,90)
ax.set_yticks(numpy.arange(0,90,10))
ax.scatter(ra,dec,c ='r')
ax.set_title("Graph Title here", va='bottom')
pyplot.show()

Body:
1. colorize points

Using the c argument of scatter allows to colorize the points. In thei caase you may supply the n array to it and let the color be chosen accoring to a colormap. The colormap would consist of the different colors (31 times red, 10 times yellow, 20 times green).
The advantage of using a colormap is that it allows to easily use a colorbar.

2. making circles bigger can be done using the s argument.

3. adding space between label and title This would best be done by moving the title a bit upwards, using  the y argument to set_title. In order for the title not to go outside the figure, we can use the subplots_adjust method and make top a little smaller. (Note that this works only if the axes are created via subplots.)

4.  Only show certain ticks can be accomplished by setting
the ticks as ax.set_yticks([0,30,60]) and orienting ylabels along a horizontal line is done by ax.set_rlabel_position(0). (Note that set_rlabel_position is available from version 1.4 on, if you have an earlier version, consider updating).

import numpy as np
import matplotlib.pyplot as plt # don't use pylab
import matplotlib.colors
import matplotlib.cm

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*np.pi for x in ra]
fig = plt.figure()
ax = fig.add_subplot(111,polar=True)
ax.set_ylim(0,90)

# 4. only show 0,30, 60 ticks
ax.set_yticks([0,30,60])
# 4. orient ylabels along horizontal line
ax.set_rlabel_position(0)

# 1. prepare cmap and norm
colors= ["red"] * 31 + ["gold"] * 10 + ["limegreen"] * 20
cmap=matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.Normalize(vmin=0, vmax=60)
# 2. make circles bigger, using `s` argument
# 1. set different colors according to `n`
sc = ax.scatter(ra,dec,c =n, s=49, cmap=cmap, norm=norm, zorder=2)

# 1. make colorbar
cax = fig.add_axes([0.8,0.1,0.01,0.2])
fig.colorbar(sc, cax=cax, label="n", ticks=[0,30,40,60])
# 3. move title upwards, then adjust top spacing
ax.set_title("Graph Title here", va='bottom', y=1.1)
plt.subplots_adjust(top=0.8)

plt.show()