问:
No Module Named xlutils.copy and pip install fail
I am getting an error message that says "no module named xlutils.copy". When I got to do the pip install of xlutils.copy I get an error message "could not find a version that satifies the requirement". I downloaded xlutils 2.0.0 which contains xlutils.copy but I am not sure if it needs to be put in a certain directory?</p>

```<code>from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook('Excel FDT Master_01_update.xlsx')
wb = copy(rb)
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(rowx = r, colx = 1).value = test
    r += 1
wb.save('comeonenow.xls')
</code>```

答:
Perhaps you have multiple installations of Python, and the pip installed the xlutils in a different installation.  If you try just:

```<code>import xlutils
</code>```

I expect you'll get the same results as before.  I feel this may be getting overlooked by some of the other posters.  Your error message says it can't find the xlutils module, not some submodule or variable.  Is this still the case?

When you have multiple installations of Python, only one is the "default", so to speak, and any module installations will install into that default Python installation. I am careful to only run two installations: Python 2.7 and 3.6. And I go into each installation and make sure that I have a pip2 and a python2, and a pip3 and python3, so that I can just reference directly to the Py version I want to use, either to run or to install new packages.  Otherwise, if I just run pip, I'm not 1000% sure where it will go.  (Okay, I'm exaggerating. I know Python 2 is my default. Just trying to make a point.) :)

Also, just because you think you only have one Python installation, that may not be the case. On Windows, yes. But on Mac, there is a preloaded Python installation, and updating the Python and getting new packages into the new version instead of the preloaded version can be tricky, depending on what you've done.  Also, when you install an IDE like PyCharm, it wants to install a Python version, as well.

Last comment -- Sometimes (not usually but sometimes), an installed package will have a different name than you would think. That is not the case with xlutils. But, with fonttools, you install fonttools but you must import fontTools (note the capital 'T') into  your Py script. Again, not the case with xlutils, but just be aware of this for the future.

Body:
I am getting an error message that says "no module named xlutils.copy". When I got to do the pip install of xlutils.copy I get an error message "could not find a version that satifies the requirement". I downloaded xlutils 2.0.0 which contains xlutils.copy but I am not sure if it needs to be put in a certain directory?

from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook('Excel FDT Master_01_update.xlsx')
wb = copy(rb)
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(rowx = r, colx = 1).value = test
    r += 1
wb.save('comeonenow.xls')

Body:
Perhaps you have multiple installations of Python, and the pip installed the xlutils in a different installation.  If you try just:

import xlutils

I expect you'll get the same results as before.  I feel this may be getting overlooked by some of the other posters.  Your error message says it can't find the xlutils module, not some submodule or variable.  Is this still the case?

When you have multiple installations of Python, only one is the "default", so to speak, and any module installations will install into that default Python installation. I am careful to only run two installations: Python 2.7 and 3.6. And I go into each installation and make sure that I have a pip2 and a python2, and a pip3 and python3, so that I can just reference directly to the Py version I want to use, either to run or to install new packages.  Otherwise, if I just run pip, I'm not 1000% sure where it will go.  (Okay, I'm exaggerating. I know Python 2 is my default. Just trying to make a point.) :)

Also, just because you think you only have one Python installation, that may not be the case. On Windows, yes. But on Mac, there is a preloaded Python installation, and updating the Python and getting new packages into the new version instead of the preloaded version can be tricky, depending on what you've done.  Also, when you install an IDE like PyCharm, it wants to install a Python version, as well.

Last comment -- Sometimes (not usually but sometimes), an installed package will have a different name than you would think. That is not the case with xlutils. But, with fonttools, you install fonttools but you must import fontTools (note the capital 'T') into  your Py script. Again, not the case with xlutils, but just be aware of this for the future.


来源: stackexchange

问:
Design efficient user interactive event log so that I won't exceed my 10000 user object limit.
I have a problem: in my application I get some event-related information, so for event x I should get a form window in which I do some sort of things (enter some text and click on a button)

My problem is that for my application there is a 10,000 user objects limit (as for all c# apps), and for my existing code there are already 3000 user objects occupied (so that leaves around 7000 user objects free). I receive from 200 clients info about events regarding some stuff going on each of the clients.

When I receive info about an event from a client I would like to somehow display this as a label in an event log window and when I click on the label the specific form window (that I mentioned earlier) should pop-up so that I may enter some text and click on a button.

I need to be able to display this event log window efficiently (because I could receive up to 1000 events from every client and if every label in this log occupies 1 object that means that for every client there will be 1000 objects (max, but possible) so I would exceed very much my 10000 limit).

How can I do something about it efficiently?

Currently for every event I launch a form window in which I enter text and click on a button but this is not efficient (because my form window occupies already 3 user objects and if I have a max 3 * 200 clients * 1000 user object i exceed my 7000 limit by far).

答:
I struggle to see how you can get thousands of windows from a user interface like this.  If you create one label control for each individual notification then, yes, this can get badly out of hand in a hurry.  Makes it dreadfully slow too.

Don't use label controls, use a ListBox, ListView, TreeView or DataGridView.  Controls that can display multiple items but only consume a single window handle.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
How to log unhandled exception in .net core
With ELMAH feature in web api 2.0 and Centralized logging and error handling , runtime calls logging module and decide if it can be handled then calls the handler else just logs it..
how can this feature be added in web api core. as we don't have inbuilt centralized unhandled logging feature..

One way I got is to use ExceptionHandler middleware and when it gets called, get the exception and log  it or send email.. but what if handler doesn't get called .. how to log those unhandled exceptions ?

答:
Try this port of Elmah to .NET Core. </p>

```<code>services.AddElmah(); // in ConfigureServices

app.UseElmah(); // in Configure, before UseMvc()
</code>```

Body:
Try this port of Elmah to .NET Core.

services.AddElmah(); // in ConfigureServices

app.UseElmah(); // in Configure, before UseMvc()

ContentLicense: CC BY-SA 4.0


问:
Building RESTful API using R
I am thinking about building a RESTful API using the programming language R, mainly to expose my machine learning model to the user in an API format.
I know there are some options like export to PMML, PFA and use other languages to take care of the API part. However, I want to stick to the same programming language and was wondering if there is anything like Flask/Django/Springbook framework in R?

I took a look at servr/shiny but I really don't think RESTful is what they are designed for. Is there any better solution within R that is more easy to use?

答:
This is for those who want to have a comparion of API development with R - plumber, Rserve and rApache.

Basically concurrent requests are queued by httpuv in plumber so that it is not performant by itself. The author recommends multiple docker containers but it can be complicated as well as resource-demanding.

There are other tech eg Rserve and rApache. Rserve forks prosesses and it is possible to configure rApache to pre-fork so as to handle concurrent requests.

See the following posts for comparison

https://www.linkedin.com/pulse/api-development-r-part-i-jaehyeon-kim/
https://www.linkedin.com/pulse/api-development-r-part-ii-jaehyeon-kim/

Title: Building RESTful API using R


问:
How am I supposed to write over an array given the number of times it has to be copied in Java
I am supposed to "multiply" an array for given number of times, using the int copy variable. However, I am stuck on "writing over the array" as arrays can not be modified, and copying the array a given amount of times. Clearer instructions can be found below. Thanks! :)

```<code>int[] arrayMultiplier(int[] arr, int copies)
This method should return an array generated by writing the array arr
several (copies) times in a row.
For example if the array nums = [3, 5, 6]:
arrayMultiplier(nums, 3)
would return the array [3, 5, 6, 3, 5, 6, 3, 5, 6]
</code>```

I should clarify that I found two other posts on how to do this, but they used C++ and Javascript instead of Java

答:
You could use an ArrayList then convert it into an array when you return it. Probably not the most efficient answer, but it works.   </p>

```<code>public int[] arrayMultiplier(int[] arr, int copies) {
    ArrayList<Integer> temp = new ArrayList<Integer>();
    for(int i = 0; i < copies; i++) {
        for(int j = 0; j < arr.length; j++) {
            temp.add(arr[j]);
        }
    }
    return temp.stream().mapToInt(i->i).toArray();
}
</code>```

Body:
I am supposed to "multiply" an array for given number of times, using the int copy variable. However, I am stuck on "writing over the array" as arrays can not be modified, and copying the array a given amount of times. Clearer instructions can be found below. Thanks! :)

int[] arrayMultiplier(int[] arr, int copies)
This method should return an array generated by writing the array arr
several (copies) times in a row.
For example if the array nums = [3, 5, 6]:
arrayMultiplier(nums, 3)
would return the array [3, 5, 6, 3, 5, 6, 3, 5, 6]

I should clarify that I found two other posts on how to do this, but they used C++ and Javascript instead of Java

Body:
You could use an ArrayList then convert it into an array when you return it. Probably not the most efficient answer, but it works.

public int[] arrayMultiplier(int[] arr, int copies) {
    ArrayList<Integer> temp = new ArrayList<Integer>();
    for(int i = 0; i < copies; i++) {
        for(int j = 0; j < arr.length; j++) {
            temp.add(arr[j]);
        }
    }
    return temp.stream().mapToInt(i->i).toArray();
}


问:
Resize View in dp
I'm stuck trying to resize the width of a View in a ListView programmatically, because I want it to be in DP, not pixels.

My ListView generate instances of a RelativeLayout with a View that fills all the screen (match_parent), and a TextView and a button inside.

The View is set to width = match_parent to fill the whole screen, as intended

What I want, is to have different View width in my adapter. Like 25%, 50%, or 75% of the total width of the base View.

```<code>mRelativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(**[VALUE I NEED HERE]**, mRelativeLayout.getLayoutParams().height));
</code>```

The ImageView is set to width = match_parent

So this are the relevant parts of code in my ViewList adapter :

```<code>    RelativeLayout mRelativeLayout = (RelativeLayout) convertView.findViewById(R.id.test_layout);

    mRelativeLayout.setBackgroundResource(arrayListName.myColor);

    if (arrayListName.myColor == R.color.custom ) {
        dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 25% , dayviewLayout.getLayoutParams().height));
    }

    if (days.mMoodColor == R.color.custom2) {
        dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 50% , dayviewLayout.getLayoutParams().height));
    }

    if (days.mMoodColor == R.color.custom3) {
        dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 75% , dayviewLayout.getLayoutParams().height));
    }
</code>```

The 25-50-75% are obviously wrong, as it takes only int values. I want it to fit any screen.

Thanks for your support.

答:
dp units are just px units multiplied by the current screen density, which is available via the DisplayMetrics class:

```<code>float density = [some context].getResources().getDisplayMetrics().density;
int dp = (int) ([your px value] * density);
</code>```

Title: Resize View in dp

Body:
I'm stuck trying to resize the width of a View in a ListView programmatically, because I want it to be in DP, not pixels.

My ListView generate instances of a RelativeLayout with a View that fills all the screen (match_parent), and a TextView and a button inside.

The View is set to width = match_parent to fill the whole screen, as intended

What I want, is to have different View width in my adapter. Like 25%, 50%, or 75% of the total width of the base View.

mRelativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(**[VALUE I NEED HERE]**, mRelativeLayout.getLayoutParams().height));

The ImageView is set to width = match_parent

So this are the relevant parts of code in my ViewList adapter :

    RelativeLayout mRelativeLayout = (RelativeLayout) convertView.findViewById(R.id.test_layout);

    mRelativeLayout.setBackgroundResource(arrayListName.myColor);

    if (arrayListName.myColor == R.color.custom ) {
        dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 25% , dayviewLayout.getLayoutParams().height));
    }

    if (days.mMoodColor == R.color.custom2) {
        dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 50% , dayviewLayout.getLayoutParams().height));
    }

    if (days.mMoodColor == R.color.custom3) {
        dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 75% , dayviewLayout.getLayoutParams().height));
    }

The 25-50-75% are obviously wrong, as it takes only int values. I want it to fit any screen.

Thanks for your support.

Body:
dp units are just px units multiplied by the current screen density, which is available via the DisplayMetrics class:

float density = [some context].getResources().getDisplayMetrics().density;
int dp = (int) ([your px value] * density);


问:
hide() show() jquery
I'm using the following:

$('#info').click(function (){
$('#message').fadeIn(200).show();
return false;
});

How could I change my script so that it would dissapear once clicked apon again?

Tried .fadeout().hide()

But it only show/hide so fast it looks as though nothing is happening.

答: $('#info').click(function (){ $('#message').fadeIn(200).toggle(); return false; });

Title: hide() show() jquery


问:
Sluggish Android Studio Start up
I have Android Studio 3.0.1 with latest JDK installed on my i7 (4th Gen) dual core Win10 machine, 16GB RAM, 850 Pro 512GB SSD. But even with this beastly configuration, when double clicking on the Android Studio icon to launch the application, the software feels very sluggish in starting up. Takes approx. 15-20 odd seconds to just start up and then do the Gradle build of last opened app, which takes another 30-40 seconds.

Have set the vmoptions & gradle.properties to use -Xms2g and -Xmx4g along with parallel build, offline gradle execution and configureondemand.

Is there a way to drastically improve this performance when I have such a good machine configuration, probably tweaking some other Windows / Android Studio level parameters? Please help.

答:
It start in seconds only because of that configuration.It takes few minutes to start in my laptop with 8gb ram.
So the time you mentioned seems pretty good.</p>

Title: Sluggish Android Studio Start up


问:
python: writing data to excel file but "cannot close file"?
so I have this pandas data table that I wish to write into an excel workbook.
I'm using pyexcelerate package.
Here's my code:

```<code>from pyexcelerate import Workbook

def df_to_excel(df, path, sheet_name='Sheet 1'):
    data = [df.columns.tolist(), ] + df.values.tolist()
    wb = Workbook()
    wb.new_sheet(sheet_name, data=data)
    wb.save(path)

df_to_excel(df=MergedDataAll, path=merged_file)
</code>```

I didn't have this problem before when I used this same code; but today this error kept popping up:

```<code>Traceback (most recent call last):
  File "C:/Users/y/Documents/python codes/DataMerging.py", line 71, in <module>
    df_to_excel(df=MergedDataAll, path=merged_file)
  File "C:/Users/y/Documents/python codes/DataMerging.py", line 68, in df_to_excel
    wb.save(path)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Workbook.py", line 82, in save
    self._save(fp)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Workbook.py", line 78, in _save
    self._writer.save(file_handle)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Writer.py", line 58, in save
    for s in sheetStream:
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\environment.py", line 1045, in generate
    yield self.environment.handle_exception(exc_info, True)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\templates\xl\worksheets\sheet.xml", line 11, in top-level template code
    <sheetData>{% for x, row in worksheet.get_xml_data() %}{{ worksheet.get_row_xml_string(x) }}{% for cell in row %}{{ cell }}{% endfor %}</row>{% endfor %}</sheetData>
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Worksheet.py", line 265, in get_xml_data
    row_data.append(self.__get_cell_data(cell, x, y, style))
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Worksheet.py", line 188, in __get_cell_data
    z = '"><v>%s</v></c>' % (DataTypes.to_excel_date(cell))
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\DataTypes.py", line 57, in to_excel_date
    excel_date = delta.days + (float(delta.seconds) + float(delta.microseconds) / 1E6) / (60 * 60 * 24) + 1
AttributeError: 'NaTType' object has no attribute 'days'
Exception ignored in: <bound method ZipFile.__del__ of <zipfile.ZipFile [closed]>>
Traceback (most recent call last):
  File "C:\Users\y\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1663, in __del__
  File "C:\Users\y\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1680, in close
ValueError: seek of closed file
</code>```

I tried googling on this, and used something similar to

```<code>wd.close()
wd._archive_.close()
</code>```

but both are not useful.

here're some reference posts I've looked into:

Openpyxl does not close Excel workbook in read only mode

Python to close a workbook using win32com

Closing files in openpyxl

https://github.com/python-pillow/Pillow/issues/1630

答:
I figured it out finally! So I thought I might as well share my finding.

The answer was from this post:

'NaTType' object has no attribute 'days'

Basically upgrading the pandas library solved this issue...

```<code>pip install --upgrade pandas
</code>```

Special thanks to Blckknght for pointing out the NaTType issue; I wouldn't have looked more into this if he didn't point it out.

Body:
so I have this pandas data table that I wish to write into an excel workbook.
I'm using pyexcelerate package.
Here's my code:

from pyexcelerate import Workbook

def df_to_excel(df, path, sheet_name='Sheet 1'):
    data = [df.columns.tolist(), ] + df.values.tolist()
    wb = Workbook()
    wb.new_sheet(sheet_name, data=data)
    wb.save(path)

df_to_excel(df=MergedDataAll, path=merged_file)

I didn't have this problem before when I used this same code; but today this error kept popping up:

Traceback (most recent call last):
  File "C:/Users/y/Documents/python codes/DataMerging.py", line 71, in <module>
    df_to_excel(df=MergedDataAll, path=merged_file)
  File "C:/Users/y/Documents/python codes/DataMerging.py", line 68, in df_to_excel
    wb.save(path)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Workbook.py", line 82, in save
    self._save(fp)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Workbook.py", line 78, in _save
    self._writer.save(file_handle)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Writer.py", line 58, in save
    for s in sheetStream:
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\environment.py", line 1045, in generate
    yield self.environment.handle_exception(exc_info, True)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\templates\xl\worksheets\sheet.xml", line 11, in top-level template code
    <sheetData>{% for x, row in worksheet.get_xml_data() %}{{ worksheet.get_row_xml_string(x) }}{% for cell in row %}{{ cell }}{% endfor %}</row>{% endfor %}</sheetData>
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Worksheet.py", line 265, in get_xml_data
    row_data.append(self.__get_cell_data(cell, x, y, style))
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Worksheet.py", line 188, in __get_cell_data
    z = '"><v>%s</v></c>' % (DataTypes.to_excel_date(cell))
  File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\DataTypes.py", line 57, in to_excel_date
    excel_date = delta.days + (float(delta.seconds) + float(delta.microseconds) / 1E6) / (60 * 60 * 24) + 1
AttributeError: 'NaTType' object has no attribute 'days'
Exception ignored in: <bound method ZipFile.__del__ of <zipfile.ZipFile [closed]>>
Traceback (most recent call last):
  File "C:\Users\y\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1663, in __del__
  File "C:\Users\y\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1680, in close
ValueError: seek of closed file

I tried googling on this, and used something similar to

wd.close()
wd._archive_.close()

but both are not useful.

here're some reference posts I've looked into:

Openpyxl does not close Excel workbook in read only mode

Python to close a workbook using win32com

Closing files in openpyxl

https://github.com/python-pillow/Pillow/issues/1630

Body:
I figured it out finally! So I thought I might as well share my finding.

The answer was from this post:

'NaTType' object has no attribute 'days'

Basically upgrading the pandas library solved this issue...

pip install --upgrade pandas

Special thanks to Blckknght for pointing out the NaTType issue; I wouldn't have looked more into this if he didn't point it out.


问:
How to setup project using Alea GPU
(Sorry if this is really obvious, I'm completely new to GPU programming.) I have installed all of the dependencies for Alea GPU and the samples are compiling and running as they should. However, I'm not sure how to setup a new console or windows forms project to include the Alea GPU libraries. If I just try to include the files as follows:

```<code>using Alea;
using Alea.Parallel;
</code>```

I get the error:

"The type or namespace name 'Alea' could not be found (are you missing
  a using directive or an assembly reference?)".

How am I supposed to include the Alea GPU libraries when creating a new project? (I'm using Visual Studio 2015)

答: Before the "using" statements will work, you need to add a reference to the project that points to the Alea library so Visual Studio knows where to look for them.</p>

Title: How to setup project using Alea GPU

Body:
(Sorry if this is really obvious, I'm completely new to GPU programming.) I have installed all of the dependencies for Alea GPU and the samples are compiling and running as they should. However, I'm not sure how to setup a new console or windows forms project to include the Alea GPU libraries. If I just try to include the files as follows:

using Alea;
using Alea.Parallel;

I get the error:

"The type or namespace name 'Alea' could not be found (are you missing
  a using directive or an assembly reference?)".

How am I supposed to include the Alea GPU libraries when creating a new project? (I'm using Visual Studio 2015)


问:
Error: Please make sure that "Alexa Skills Kit" is selected for the event source type of arn
Am new to Alexa development. When configuring alexa in amazon developer site am getting Error:

Error: Please make sure that "Alexa Skills Kit" is selected for the event source type of arn:aws:lambda:us-east-1:431036771207:function:HelloWorld?

What am missing here ?

答:
Follow these steps:

Go to the AWS Lambda console

Open your lambda function

Add a trigger of the type Alexa Skills Kit and configure it


问:
dynamic forms in django
i've built my own dynamic form, kind of following james bennetts example.
using the following lines in forms.py

```<code>def make_question_form(request):
fields = { 'venue' : forms.CharField(widget=forms.HiddenInput()),
           'survey' : forms.CharField(widget=forms.HiddenInput())}
return type('Question_Form',(forms.BaseForm,), { 'base_fields': fields })
</code>```

and the following in the view to build it (I know its not truely dynamic, i plan to add the dynamics next.

```<code>question_form = make_question_form(request)
question_form.base_fields['venue'] = this_venue.name
question_form.base_fields['survey'] = this_survey.name
return render_to_response("survey/questions.html", locals(), context_instance=RequestContext(request))
</code>```

but im not sure what to dowith it in the template and this is the bit that isn't really covered in the tutorials.

i've worked out that the following works

```<code>    {% for base_field in question_form.base_fields %}
        {{ base_field.type }}
    {% endfor %}
</code>```

but i thought the point of building it as a form was to be able to do something like

```<code>question_form.as_p
</code>```

and wrap it in my own form tags.

have i missed the point or should as_p work (it doesn't).

答:
You haven't instantiated the form in your view. make_question_form returns a new form class - normally when you use a form class in your view you do form = MyFormClass() or form = MyFormClass(request.POST).

So you need to do form = question_form() before the render_to_response, then you'll be able to do {{ form.as_p }} in the template.

Title: dynamic forms in django

Body:
i've built my own dynamic form, kind of following james bennetts example.
using the following lines in forms.py

def make_question_form(request):
fields = { 'venue' : forms.CharField(widget=forms.HiddenInput()),
           'survey' : forms.CharField(widget=forms.HiddenInput())}
return type('Question_Form',(forms.BaseForm,), { 'base_fields': fields })

and the following in the view to build it (I know its not truely dynamic, i plan to add the dynamics next.

question_form = make_question_form(request)
question_form.base_fields['venue'] = this_venue.name
question_form.base_fields['survey'] = this_survey.name
return render_to_response("survey/questions.html", locals(), context_instance=RequestContext(request))

but im not sure what to dowith it in the template and this is the bit that isn't really covered in the tutorials.

i've worked out that the following works

    {% for base_field in question_form.base_fields %}
        {{ base_field.type }}
    {% endfor %}

but i thought the point of building it as a form was to be able to do something like

question_form.as_p

and wrap it in my own form tags.

have i missed the point or should as_p work (it doesn't).


问:
XSL add the sum of child nodes to a variable
```<code><Recipes>
    <Food A="...">
        <Ingredients>
            <Ingredient Salt="...">
                <Qty> 250 </Qty>
                <Type> g </Type>
            </Ingredient>
             .
             .
        </Ingredients>
    </Food>

    <Food B="...">
        <Ingredients>
            <Ingredient Salt="...">
                <Qty> 30 </Qty>
                <Type> g </Type>
            </Ingredient>
             .
             .
        </Ingredients>
    </Food>

    <Food C="...">
        <Ingredients>
            <Ingredient Salt="...">
                <Qty> 25 </Qty>
                <Type> g </Type>
            </Ingredient>
             .
             .
        </Ingredients>
    </Food>
</Recipes>
</code>```

Hello, i have a similar xml file like the one above and im trying to sum into a variable the amount of salt in differents foods, so for this example the result should be 305.

I tried multiple paths to the sum(), but i am not able to access the way i want. Is it possible to do this?

This is my last try, but it returns 0.

```<code><xsl:variable name="Salt" select="sum(Recipes/*/Ingredients/Ingredient[name()='Salt']/@Qty)"/>
</code>```

答:
This should works</p>

```<code><xsl:variable name="Salt" select="sum(/Recipes/*/Ingredients/Ingredient[@Salt]/Qty)" />
</code>```

Body:
<Recipes>
    <Food A="...">
        <Ingredients>
            <Ingredient Salt="...">
                <Qty> 250 </Qty>
                <Type> g </Type>
            </Ingredient>
             .
             .
        </Ingredients>
    </Food>

    <Food B="...">
        <Ingredients>
            <Ingredient Salt="...">
                <Qty> 30 </Qty>
                <Type> g </Type>
            </Ingredient>
             .
             .
        </Ingredients>
    </Food>

    <Food C="...">
        <Ingredients>
            <Ingredient Salt="...">
                <Qty> 25 </Qty>
                <Type> g </Type>
            </Ingredient>
             .
             .
        </Ingredients>
    </Food>
</Recipes>

Hello, i have a similar xml file like the one above and im trying to sum into a variable the amount of salt in differents foods, so for this example the result should be 305.

I tried multiple paths to the sum(), but i am not able to access the way i want. Is it possible to do this?

This is my last try, but it returns 0.

<xsl:variable name="Salt" select="sum(Recipes/*/Ingredients/Ingredient[name()='Salt']/@Qty)"/>

Body:
This should works

<xsl:variable name="Salt" select="sum(/Recipes/*/Ingredients/Ingredient[@Salt]/Qty)" />


问:
show() and hide() not working but toggle working... If condition wrong?
I have some jQuery code where show() and hide() are not working:

var action = 0;
var toggle = 0;

$(function() {
  $('.button-work1').on('click', function() {
    if ($toggle == 0) {
      $action = 1;
      $toggle = 1;
      $('.showData').show();
    } else {
      $('.showData').hide();
      $toggle = 0
    }
  });
});
```

When I use toggle() and remove the if condition it worke fine. However, I don't want to use toggle() as I need to do few more things based on $toggle value.

答:
You have $ in front of your variable names, this is Javascript not PHP :)

    var action=0;
    var toggle=1;

$(function() {
    $('.button-work1').on('click', function() {
        if(toggle == 0){
        action = 1;
        toggle=1;
        $('.showData').show();}
        else{
        $('.showData').hide();
        toggle=0
        }
    });
});```
<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="showData">Test element</div>

<input type="button" value="click me" class="button-work1"></code>```

Body:
I have some jQuery code where show() and hide() are not working:

var action = 0;
var toggle = 0;

$(function() {
  $('.button-work1').on('click', function() {
    if ($toggle == 0) {
      $action = 1;
      $toggle = 1;
      $('.showData').show();
    } else {
      $('.showData').hide();
      $toggle = 0
    }
  });
});

When I use toggle() and remove the if condition it worke fine. However, I don't want to use toggle() as I need to do few more things based on $toggle value.

Body:
You have $ in front of your variable names, this is Javascript not PHP :)

    var action=0;
    var toggle=1;

$(function() {
    $('.button-work1').on('click', function() {
        if(toggle == 0){
        action = 1;
        toggle=1;
        $('.showData').show();}
        else{
        $('.showData').hide();
        toggle=0
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showData">Test element</div>

<input type="button" value="click me" class="button-work1">


问:
How can I write a Chrome extension on a Chromebook?
Is there any viable development flow that lets me edit, then load, a Chrome extension with nothing more than a Chromebook? </p>

答:
I use Caret and Puresolid IDE for most of my development. Caret is great because you can "collapse" various code such as functions and objects, making editing much easier. Puresolid IDE is great because you can create a project from a variety of templates, it has auto complete, and code suggestion.
As for turning my project folder into a Chrome app/extension I use Chrome Apps & Extensions Developer Tool.</p>


问:
JDBC not returning ResultSet records
Started a new job and need to learn Java (been a .NET developer for over a decade).  A mandate from higher up dictates all new stuff is to be done in Java / Oracle.

So I am running through the PluralSight training and right now I am trying to learn the intricacies of JDBC.

I have the following table in a Oracle Database (also a new tech for me).

```<code>CREATE TABLE "TEST"."ACCOUNT"
(
"ACCOUNT_ID" NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY VALUE,
"ACCOUNT_NAME" VARCHAR2(20)
"ACCOUNT_NUMBER" VARCHAR2(20)
"ACCOUNT_TYPE" VARCHAR2(20)
)
</code>```

I set up some code using the Repository pattern.  But it is fairly simple:

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

IAccountMapper accountMapper = new AccountMapper();
IConfiguration configuration = new OracleConfiguration();

try (
        IDataAccess<ResultSet> dataAccess = new OracleDataAccess(configuration);
        IAccountRepository accountRepo = new AccountRepository(accountMapper, dataAccess);
        ){

    //nothing here
    List<Account> accounts = accountRepo.query(new AllAccountsSpecification());

} catch (Exception e){
    System.err.println(e.getMessage());
}
</code>```

}

The IDataAccess interface:

```<code>public interface IDataAccess<T> {

    T get(String query) throws SQLException;
}
</code>```

All of my implementation is in the base classes and the subclasses are referenced - ie:

```<code>public interface IOracleDataAccess extends IDataAccess<ResultSet>{

}

public class OracleDataAccess extends DataAccessBase<ResultSet> implements IOracleDataAccess {

public OracleDataAccess(IConfiguration configuration) throws SQLException {
    super(configuration);
}
</code>```

The implementation of the IDataAccess (a base class where T is the entity used by the repo):

```<code>public abstract class DataAccessBase<T> implements AutoCloseable {

protected final IConfiguration configuration;
protected Connection connection;
protected PreparedStatement statement;
protected ResultSet resultSet;

    public DataAccessBase(IConfiguration configuration) {
        this.configuration = configuration;
        this.connection = DriverManager.getConnection(configuration.getConnectionString(),
                configuration.getUsername(),  configuration.getPassword());
    }

    public T get(String query) throws SQLException {
        statement = connection.prepareStatement(query);
        return (T)statement.executeQuery();
    }
}
</code>```

This DataAccess class is injected into my Repository class and is used to return the results:

```<code>public abstract class ReadOnlyRepositoryBase<T> implements IReadOnlyRepository<T> {

protected final IMapper<ResultSet, T> mapper;
protected final IDataAccess<ResultSet> database;

public ReadOnlyRepositoryBase(IMapper<ResultSet, T> mapper, IDataAccess<ResultSet> database) {
    this.mapper = mapper;
    this.database = database;
}

public List<T> query(ISpecification specification){
    List<T> entities = new ArrayList<>;

    try {

        System.out.println(specification.toSqlQuery());
        //This is what is output:
        //SELECT * FROM ACCOUNT

        //this returns 1 record when:  "select tablespace_name, table_name from user_tables"
        //returns no records when "select * from account"
        ResultSet rs = database.get(specification.toSqlQuery());

        //loop is never entered for "select * from account"
        //runs once for "select tablespace_name, table_name from user_tables"
        while(rs.next()){
            entities.add(mapper.map(rs));
        }
    } catch (SQLException sqlEx){
        sqlEx.printStackTrace();
    }

    return entities;
}
}
</code>```

The problem is nothing is coming back (the ResultSet next() method returns false) This SQL:

```<code>SELECT * FROM ACCOUNT
</code>```

Returns 2 records from the Oracle SQL Developer IDE - but nothing in code.

If I run this query from code:

```<code>"SELECT TABLESPACE_NAME, TABLE_NAME FROM USER_TABLES"
</code>```

I get 1 record back (TEST, ACCOUNT)

Do I need to further qualify the tables in the SQL to get records back?

I am logged into the database with the same credentials I am connecting with - so I do not think it is a permission thing.

答:
Feel like an idiot - but I imagine I am not the first here.  @AlexPoole was spot on.  I had inserted the records through the IDE - but apparently
I did not commit them.  Coming from SQL Server - I do not need to commit after a

```<code>Insert into [Table] values (stuff)
</code>```

I guess that is different with Oracle.

Title: JDBC not returning ResultSet records

Body:
Started a new job and need to learn Java (been a .NET developer for over a decade).  A mandate from higher up dictates all new stuff is to be done in Java / Oracle.

So I am running through the PluralSight training and right now I am trying to learn the intricacies of JDBC.

I have the following table in a Oracle Database (also a new tech for me).

CREATE TABLE "TEST"."ACCOUNT"
(
"ACCOUNT_ID" NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY VALUE,
"ACCOUNT_NAME" VARCHAR2(20)
"ACCOUNT_NUMBER" VARCHAR2(20)
"ACCOUNT_TYPE" VARCHAR2(20)
)

I set up some code using the Repository pattern.  But it is fairly simple:

public static void main(String[] args) throws IOException {

IAccountMapper accountMapper = new AccountMapper();
IConfiguration configuration = new OracleConfiguration();

try (
        IDataAccess<ResultSet> dataAccess = new OracleDataAccess(configuration);
        IAccountRepository accountRepo = new AccountRepository(accountMapper, dataAccess);
        ){

    //nothing here
    List<Account> accounts = accountRepo.query(new AllAccountsSpecification());

} catch (Exception e){
    System.err.println(e.getMessage());
}

}

The IDataAccess interface:

public interface IDataAccess<T> {

    T get(String query) throws SQLException;
}

All of my implementation is in the base classes and the subclasses are referenced - ie:

public interface IOracleDataAccess extends IDataAccess<ResultSet>{

}

public class OracleDataAccess extends DataAccessBase<ResultSet> implements IOracleDataAccess {

public OracleDataAccess(IConfiguration configuration) throws SQLException {
    super(configuration);
}

The implementation of the IDataAccess (a base class where T is the entity used by the repo):

public abstract class DataAccessBase<T> implements AutoCloseable {

protected final IConfiguration configuration;
protected Connection connection;
protected PreparedStatement statement;
protected ResultSet resultSet;

    public DataAccessBase(IConfiguration configuration) {
        this.configuration = configuration;
        this.connection = DriverManager.getConnection(configuration.getConnectionString(),
                configuration.getUsername(),  configuration.getPassword());
    }

    public T get(String query) throws SQLException {
        statement = connection.prepareStatement(query);
        return (T)statement.executeQuery();
    }
}

This DataAccess class is injected into my Repository class and is used to return the results:

public abstract class ReadOnlyRepositoryBase<T> implements IReadOnlyRepository<T> {

protected final IMapper<ResultSet, T> mapper;
protected final IDataAccess<ResultSet> database;

public ReadOnlyRepositoryBase(IMapper<ResultSet, T> mapper, IDataAccess<ResultSet> database) {
    this.mapper = mapper;
    this.database = database;
}

public List<T> query(ISpecification specification){
    List<T> entities = new ArrayList<>;

    try {

        System.out.println(specification.toSqlQuery());
        //This is what is output:
        //SELECT * FROM ACCOUNT

        //this returns 1 record when:  "select tablespace_name, table_name from user_tables"
        //returns no records when "select * from account"
        ResultSet rs = database.get(specification.toSqlQuery());

        //loop is never entered for "select * from account"
        //runs once for "select tablespace_name, table_name from user_tables"
        while(rs.next()){
            entities.add(mapper.map(rs));
        }
    } catch (SQLException sqlEx){
        sqlEx.printStackTrace();
    }

    return entities;
}
}

The problem is nothing is coming back (the ResultSet next() method returns false) This SQL:

SELECT * FROM ACCOUNT

Returns 2 records from the Oracle SQL Developer IDE - but nothing in code.

If I run this query from code:

"SELECT TABLESPACE_NAME, TABLE_NAME FROM USER_TABLES"

I get 1 record back (TEST, ACCOUNT)

Do I need to further qualify the tables in the SQL to get records back?

I am logged into the database with the same credentials I am connecting with - so I do not think it is a permission thing.

Body:
Feel like an idiot - but I imagine I am not the first here.  @AlexPoole was spot on.  I had inserted the records through the IDE - but apparently
I did not commit them.  Coming from SQL Server - I do not need to commit after a

Insert into [Table] values (stuff)

I guess that is different with Oracle.


问:
Changing file permissions with Applescript when you do not have read permission
Occasionally employees at my company will get a hold of a file that for some reason, they do not have read or write permission to. An example is downloading a file from a client FTP server.

I'm looking to create something very simple, like an applescript droplet, that will change the permissions for the files dropped on it:

```<code>on open filelist
 repeat with i in filelist
  do shell script "chmod -R +wr " & quoted form of POSIX path of i with administrator privileges
 end repeat
end open
</code>```

The problem is that since the user does not have read permissions, the droplet fails instantly at the on open filelist line.

Removing everything between the on open block:

```<code>on open filelist
end open
</code>```

still results in the script failing. By failing, I mean it produces a file permission error.

Thanks in advance.

答:
The problem could be that you are trying to work with files your user can not read - this will result in the Droplet not working, because it depends on being able to read!
You will need to write a proper application using a file chooser. The problem here is that you can choose multiple files, but only either files or folders.
Anyway, I´ve written something similar in the past, so feel free to use this:</p>

```<code>set myUsername to (short user name of (system info))
set myPassword to ""

set fileOrFolder to button returned of (display dialog "Would you like to change permissions on files of folders?" buttons {"Cancel", "Files", "Folders"} default button "Cancel")

if fileOrFolder is "Files" then
set theSelection to choose file with multiple selections allowed without invisibles

repeat with oneFile in theSelection

do shell script "sudo chmod -R u+rwX,go+rX " & quoted form of POSIX path of oneFile password myPassword with administrator privileges
do shell script "sudo chown -R " & myUsername & ":staff " & quoted form of POSIX path of oneFile password myPassword with administrator privileges

end repeat
else if fileOrFolder is "Folders" then
set theSelection to choose folder with multiple selections allowed without invisibles

repeat with oneFile in theSelection

do shell script "sudo chmod -R u+rwX,go+rX " & quoted form of POSIX path of oneFile password myPassword with administrator privileges
do shell script "sudo chown -R " & myUsername & ":staff " & quoted form of POSIX path of oneFile password myPassword with administrator privileges

end repeat
else
display dialog "Error"
end if
</code>```

Body:
Occasionally employees at my company will get a hold of a file that for some reason, they do not have read or write permission to. An example is downloading a file from a client FTP server.

I'm looking to create something very simple, like an applescript droplet, that will change the permissions for the files dropped on it:

on open filelist
 repeat with i in filelist
  do shell script "chmod -R +wr " & quoted form of POSIX path of i with administrator privileges
 end repeat
end open

The problem is that since the user does not have read permissions, the droplet fails instantly at the on open filelist line.

Removing everything between the on open block:

on open filelist
end open

still results in the script failing. By failing, I mean it produces a file permission error.

Thanks in advance.

Body:
The problem could be that you are trying to work with files your user can not read - this will result in the Droplet not working, because it depends on being able to read!
You will need to write a proper application using a file chooser. The problem here is that you can choose multiple files, but only either files or folders.
Anyway, I´ve written something similar in the past, so feel free to use this:

set myUsername to (short user name of (system info))
set myPassword to ""

set fileOrFolder to button returned of (display dialog "Would you like to change permissions on files of folders?" buttons {"Cancel", "Files", "Folders"} default button "Cancel")

if fileOrFolder is "Files" then
set theSelection to choose file with multiple selections allowed without invisibles

repeat with oneFile in theSelection

do shell script "sudo chmod -R u+rwX,go+rX " & quoted form of POSIX path of oneFile password myPassword with administrator privileges
do shell script "sudo chown -R " & myUsername & ":staff " & quoted form of POSIX path of oneFile password myPassword with administrator privileges

end repeat
else if fileOrFolder is "Folders" then
set theSelection to choose folder with multiple selections allowed without invisibles

repeat with oneFile in theSelection

do shell script "sudo chmod -R u+rwX,go+rX " & quoted form of POSIX path of oneFile password myPassword with administrator privileges
do shell script "sudo chown -R " & myUsername & ":staff " & quoted form of POSIX path of oneFile password myPassword with administrator privileges

end repeat
else
display dialog "Error"
end if


问:
Dapper Multipmapping collection within collections
In Dapper, what's the best way to map and object that contains a list and each of those list items have their own lists?

```<code>class Object1 {
    int Object1Id;
    List<Object2> object2s;
}

class Object2 {
    int Object2Id;
    List<Object3> object3s;
}

class Object3 {
    int Object3Id;
}
</code>```

Here's the SQL I wanted to use

```<code>SELECT *
  FROM [Object1] o1
  left join [Object2] o2 on o1.Object1Id = o2.Object1Id
  left join [Object3] o3 on o2.Object2Id = o3.Object2Id
</code>```

Using the Left joins because it's possible Object1 has no Object2's and Object2's may not have any Object3's

I thought about using

```<code>connection.Query<Object1, Object2, Object3, Object1>
</code>```

but keeping track of a dictionary within a dictionary to add them to the list seems like a lot of lines of code.

Would I be better off using QueryMultiple?

答:
If you're using SQL Server 2016 or above I would go with JSON. You can return the data as a JSON document, like this:

```<code>USE tempdb
GO

DROP TABLE IF EXISTS dbo.[Object1]
DROP TABLE IF EXISTS dbo.[Object2]
DROP TABLE IF EXISTS dbo.[Object3]
GO

CREATE TABLE dbo.[Object1] ([Object1Id] INT PRIMARY KEY, [Value1] NVARCHAR(100));
CREATE TABLE dbo.[Object2] ([Object2Id] INT PRIMARY KEY, [Object1Id] INT, [Value2] NVARCHAR(100));
CREATE TABLE dbo.[Object3] ([Object3Id] INT PRIMARY KEY, [Object2Id] INT, [Value3] NVARCHAR(100));
GO

INSERT INTO dbo.[Object1] VALUES (1, 'Object 1 Value 1')
INSERT INTO dbo.[Object1] VALUES (2, 'Object 1 Value 2')
INSERT INTO dbo.[Object1] VALUES (3, 'Object 1 Value 3')
GO

INSERT INTO dbo.[Object2] VALUES (10, 1, 'Object 2 Value 1')
INSERT INTO dbo.[Object2] VALUES (20, 1, 'Object 2 Value 2')
INSERT INTO dbo.[Object2] VALUES (30, 2, 'Object 2 Value 3')
GO

INSERT INTO dbo.[Object3] VALUES (100, 10, 'Object 3 Value 1')
INSERT INTO dbo.[Object3] VALUES (200, 10, 'Object 3 Value 2')
INSERT INTO dbo.[Object3] VALUES  (300, 30, 'Object 3 Value 3')
GO

SELECT
    *
FROM
    [Object1]
LEFT JOIN
    [Object2] AS Object2s ON [Object1].Object1Id = [Object2s].Object1Id
LEFT JOIN
    [Object3] AS Object3s ON [Object2s].Object2Id = [Object3s].Object2Id
WHERE
    [Object1].Object1Id = 1
FOR
    JSON AUTO,WITHOUT_ARRAY_WRAPPER
</code>```

With a JSON as result it is easy to then deserialize it in a class you want:

```<code>class Program
{
    class Object1 {
        public int Object1Id;
        public List<Object2> Object2s;
    }

    class Object2 {
        public int Object2Id;
        public List<Object3> Object3s;
    }

    class Object3 {
        public int Object3Id;
    }

    static void Main(string[] args)
    {
        using(var conn = new SqlConnection("Data Source=localhost; Initial Catalog=tempdb; Integrated Security=SSPI"))
        {
            var json = conn.ExecuteScalar<string>(@"
                SELECT
                    *
                FROM
                    [Object1]
                LEFT JOIN
                    [Object2] AS Object2s ON [Object1].Object1Id = [Object2s].Object1Id
                LEFT JOIN
                    [Object3] AS Object3s ON [Object2s].Object2Id = [Object3s].Object2Id
                WHERE
                    [Object1].Object1Id = 1
                FOR
                    JSON AUTO,WITHOUT_ARRAY_WRAPPER
            ");

            var result = JsonConvert.DeserializeObject<Object1>(json.Replace("\"", "'"));

            Console.WriteLine(result.Object2s.Count);
        }
    }
}
</code>```

Performances are also very good.

Body:
In Dapper, what's the best way to map and object that contains a list and each of those list items have their own lists?

class Object1 {
    int Object1Id;
    List<Object2> object2s;
}

class Object2 {
    int Object2Id;
    List<Object3> object3s;
}

class Object3 {
    int Object3Id;
}

Here's the SQL I wanted to use

SELECT *
  FROM [Object1] o1
  left join [Object2] o2 on o1.Object1Id = o2.Object1Id
  left join [Object3] o3 on o2.Object2Id = o3.Object2Id

Using the Left joins because it's possible Object1 has no Object2's and Object2's may not have any Object3's

I thought about using

connection.Query<Object1, Object2, Object3, Object1>

but keeping track of a dictionary within a dictionary to add them to the list seems like a lot of lines of code.

Would I be better off using QueryMultiple?

Body:
If you're using SQL Server 2016 or above I would go with JSON. You can return the data as a JSON document, like this:

USE tempdb
GO

DROP TABLE IF EXISTS dbo.[Object1]
DROP TABLE IF EXISTS dbo.[Object2]
DROP TABLE IF EXISTS dbo.[Object3]
GO

CREATE TABLE dbo.[Object1] ([Object1Id] INT PRIMARY KEY, [Value1] NVARCHAR(100));
CREATE TABLE dbo.[Object2] ([Object2Id] INT PRIMARY KEY, [Object1Id] INT, [Value2] NVARCHAR(100));
CREATE TABLE dbo.[Object3] ([Object3Id] INT PRIMARY KEY, [Object2Id] INT, [Value3] NVARCHAR(100));
GO

INSERT INTO dbo.[Object1] VALUES (1, 'Object 1 Value 1')
INSERT INTO dbo.[Object1] VALUES (2, 'Object 1 Value 2')
INSERT INTO dbo.[Object1] VALUES (3, 'Object 1 Value 3')
GO

INSERT INTO dbo.[Object2] VALUES (10, 1, 'Object 2 Value 1')
INSERT INTO dbo.[Object2] VALUES (20, 1, 'Object 2 Value 2')
INSERT INTO dbo.[Object2] VALUES (30, 2, 'Object 2 Value 3')
GO

INSERT INTO dbo.[Object3] VALUES (100, 10, 'Object 3 Value 1')
INSERT INTO dbo.[Object3] VALUES (200, 10, 'Object 3 Value 2')
INSERT INTO dbo.[Object3] VALUES  (300, 30, 'Object 3 Value 3')
GO

SELECT
    *
FROM
    [Object1]
LEFT JOIN
    [Object2] AS Object2s ON [Object1].Object1Id = [Object2s].Object1Id
LEFT JOIN
    [Object3] AS Object3s ON [Object2s].Object2Id = [Object3s].Object2Id
WHERE
    [Object1].Object1Id = 1
FOR
    JSON AUTO,WITHOUT_ARRAY_WRAPPER

With a JSON as result it is easy to then deserialize it in a class you want:

class Program
{
    class Object1 {
        public int Object1Id;
        public List<Object2> Object2s;
    }

    class Object2 {
        public int Object2Id;
        public List<Object3> Object3s;
    }

    class Object3 {
        public int Object3Id;
    }

    static void Main(string[] args)
    {
        using(var conn = new SqlConnection("Data Source=localhost; Initial Catalog=tempdb; Integrated Security=SSPI"))
        {
            var json = conn.ExecuteScalar<string>(@"
                SELECT
                    *
                FROM
                    [Object1]
                LEFT JOIN
                    [Object2] AS Object2s ON [Object1].Object1Id = [Object2s].Object1Id
                LEFT JOIN
                    [Object3] AS Object3s ON [Object2s].Object2Id = [Object3s].Object2Id
                WHERE
                    [Object1].Object1Id = 1
                FOR
                    JSON AUTO,WITHOUT_ARRAY_WRAPPER
            ");

            var result = JsonConvert.DeserializeObject<Object1>(json.Replace("\"", "'"));

            Console.WriteLine(result.Object2s.Count);
        }
    }
}

Performances are also very good.


问:
Can uniqid() be the same for 2 concurrently executing scripts?
I am using the following code to save files on server:

```<code><?php
$uuid = uniqid();
$uploaddir = getcwd();
$uploaddir = $uploaddir ."/files/";
$uploadfile = $uploaddir.$uuid. basename($_FILES['image_file']['name']);
$relativePath = "files/".$uuid. basename($_FILES['image_file']['name']);

if (move_uploaded_file($_FILES['image_file']['tmp_name'], $uploadfile)) {
  echo $relativePath;
} else {
   echo "Error";
}
?>
</code>```

I am confused how PHP handles simultaneity.

Lets take this example. 2 users upload the file( with the same name )at exactly the same time and therefore PHP scrips should be executed at the same time.

I am aware that hundred of PHP scripts can run concurrently, but I am not aware if they can in such manner, that uniqid(), which is calculated from current time, is the same for both script executions. If uuid() can be the same, what prefix should I choose for file names?

答:
From the manual

This function does not guarantee uniqueness of return value. Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread. Use more_entropy to increase likelihood of uniqueness.

If, somehow, this happens at the same recorded microsecond in the system, it will be the same.

My go-to approach is to seed something that you know is unique into this kind of string. You can, for example, hash a primary key and a uniqid together. If you aren't worried about exposing your primary key, you can use something as simple as md5 or even prefixing the ID. If you use md5, the resulting string will be longer than uniqid.

Another option is to generate a uniqid and insert it into a relational database with a unique constraint before writing to the file. If the insertion fails due to a unique constraint violation, you can embed it in a loop until successful.

```<code><?php

/**
 * Generates a unique value to be used as a filename.
 * @return string
 */
function getUniqueId(): string
{
    $stmt = $pdo->prepare('INSERT INTO unique_filenames (value) VALUES (?)');
    // thanks to random_int, this should only need to happen once.
    // limit to 10 tries in order to avoid an infinite loop.
    for ($i=0;$i<10;$i++) {
        $unique = uniqid(random_int(1000,9999), true); // second value is more entropy
        try {
            $stmt->execute([$unique]);
            return $unique;
        } catch (\PDOException) {
            error_log('file collision. trying again.');
        }
    }

    throw new MyCustomException('Somehow failed to generate a unique ID');
}
</code>```

Body:
I am using the following code to save files on server:

<?php
$uuid = uniqid();
$uploaddir = getcwd();
$uploaddir = $uploaddir ."/files/";
$uploadfile = $uploaddir.$uuid. basename($_FILES['image_file']['name']);
$relativePath = "files/".$uuid. basename($_FILES['image_file']['name']);

if (move_uploaded_file($_FILES['image_file']['tmp_name'], $uploadfile)) {
  echo $relativePath;
} else {
   echo "Error";
}
?>

I am confused how PHP handles simultaneity.

Lets take this example. 2 users upload the file( with the same name )at exactly the same time and therefore PHP scrips should be executed at the same time.

I am aware that hundred of PHP scripts can run concurrently, but I am not aware if they can in such manner, that uniqid(), which is calculated from current time, is the same for both script executions. If uuid() can be the same, what prefix should I choose for file names?

Body:
From the manual

This function does not guarantee uniqueness of return value. Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread. Use more_entropy to increase likelihood of uniqueness.

If, somehow, this happens at the same recorded microsecond in the system, it will be the same.

My go-to approach is to seed something that you know is unique into this kind of string. You can, for example, hash a primary key and a uniqid together. If you aren't worried about exposing your primary key, you can use something as simple as md5 or even prefixing the ID. If you use md5, the resulting string will be longer than uniqid.

Another option is to generate a uniqid and insert it into a relational database with a unique constraint before writing to the file. If the insertion fails due to a unique constraint violation, you can embed it in a loop until successful.

<?php

/**
 * Generates a unique value to be used as a filename.
 * @return string
 */
function getUniqueId(): string
{
    $stmt = $pdo->prepare('INSERT INTO unique_filenames (value) VALUES (?)');
    // thanks to random_int, this should only need to happen once.
    // limit to 10 tries in order to avoid an infinite loop.
    for ($i=0;$i<10;$i++) {
        $unique = uniqid(random_int(1000,9999), true); // second value is more entropy
        try {
            $stmt->execute([$unique]);
            return $unique;
        } catch (\PDOException) {
            error_log('file collision. trying again.');
        }
    }

    throw new MyCustomException('Somehow failed to generate a unique ID');
}


问:
After Shutting Down compute engine instance do we get new system or the same old one with new IP?
I had a compute engine instance, I shut down that instance from command line. Now the thing is when I started it back the IP got changed, which I guess it was because it was ephemeral.

Now I wanted to ask as I am having now new IP. Does my system got changed or just my IP, because if my previous system is changed then I think that all of my data which I had on that compute engine will be still there and if my previous system got assigned to a new person then maybe he can see my data which will be a security breach.

The second question is, is there any way I can get my previous IP assigned to my new instance which I had before.

答:
You're conflating a couple of things here.  Networking in GCP is a purely software-defined configuration.  As such, the IP of your machine is defined by software and is in no way dependent on things like your instance itself or the disk attached to the instance (where your data actually lives).

To answer your actual questions:

When the machine is restarted, a new ephemeral IP is assigned.  Your data is on the disk attached to the machine, and nobody else has access to it.

You have no control over ephemeral IP addresses.  If you want to maintain an IP address between restarts, you need to reserve a static IP and assign it to your instance.


问:
cordova not installing on windows
I wanted to installed ionic3 so I completely uninstalled nodejs and reinstalled it, then installed ionic,

```<code>C:\Windows\system32>ionic -v
3.19.0

C:\Windows\system32>npm -v
5.5.1

C:\Windows\system32>node -v
v8.9.1
</code>```

now I am trying to install cordova and it is not installing.

```<code>C:\Windows\system32>npm install -g cordova
npm ERR! Unexpected end of JSON input while parsing near '....1.4","ripemd160":"
^2'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\DELL 5521\AppData\Roaming\npm-cache\_logs\2017-12-05T20_46
_55_094Z-debug.log
</code>```

here are contents of log file

// 2017-12-05T20_46_55_094Z-debug.log
https://pastebin.com/7mVNRkC8

答:
I had to uninstall ionic and cordova and reinstall them again, here are steps I did to fix it</p>

```<code>$ npm uninstall -g cordova
$ npm uninstall -g ionic
$ npm cache clean -f
$ npm install -g cordova ionic
</code>```

Title: cordova not installing on windows

Body:
I wanted to installed ionic3 so I completely uninstalled nodejs and reinstalled it, then installed ionic,

C:\Windows\system32>ionic -v
3.19.0

C:\Windows\system32>npm -v
5.5.1

C:\Windows\system32>node -v
v8.9.1

now I am trying to install cordova and it is not installing.

C:\Windows\system32>npm install -g cordova
npm ERR! Unexpected end of JSON input while parsing near '....1.4","ripemd160":"
^2'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\DELL 5521\AppData\Roaming\npm-cache\_logs\2017-12-05T20_46
_55_094Z-debug.log

here are contents of log file

// 2017-12-05T20_46_55_094Z-debug.log
https://pastebin.com/7mVNRkC8

Body:
I had to uninstall ionic and cordova and reinstall them again, here are steps I did to fix it

$ npm uninstall -g cordova
$ npm uninstall -g ionic
$ npm cache clean -f
$ npm install -g cordova ionic


问:
Return mocked up JSON from file (JSONObject) in Spring Controller
I'd like to mock up some JSON (that I'm reading from a file), and return it as a result of some Spring Controller.

File contains of course correct JSON data format inside, like:

```<code>{"country":"","city":""...}
</code>```

My controller looks like:

```<code>@RestController
@RequestMapping("/test")
public class TestController {

    @Value("classpath:/META-INF/json/test.json")
    private Resource testMockup;

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody JSONObject getTest() throws IOException {
        JSONObject jsonObject = new JSONObject(FileUtils.readFileToString(testMockup.getFile(), CharEncoding.UTF_8));
        return jsonObject;
    }
}
</code>```

There is no issue with reading the file itself etc.
jsonObject itself, is correct from debbuging PoV, however I'm getting HTTP Status 406 from the browser.
I've tried also just returning String (by returning jsonObject.toString()), instead of JSONObject.
However it causes encoding issue - so that JSON from the browser, is not the JSON itself (some additional slashes, quotation marks etc.).

Is there any way, to return JSON from file?

答:
I know I have been very late for this but why don't you try the below workaround.</p>

```<code>@RequestMapping(method = RequestMethod.GET)
public @ResponseBody String getTest() throws IOException {
    JSONObject jsonObject = new JSONObject(FileUtils.readFileToString(testMockup.getFile(), CharEncoding.UTF_8));
    return jsonObject.toString();
}
</code>```

Body:
I'd like to mock up some JSON (that I'm reading from a file), and return it as a result of some Spring Controller.

File contains of course correct JSON data format inside, like:

{"country":"","city":""...}

My controller looks like:

@RestController
@RequestMapping("/test")
public class TestController {

    @Value("classpath:/META-INF/json/test.json")
    private Resource testMockup;

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody JSONObject getTest() throws IOException {
        JSONObject jsonObject = new JSONObject(FileUtils.readFileToString(testMockup.getFile(), CharEncoding.UTF_8));
        return jsonObject;
    }
}

There is no issue with reading the file itself etc.
jsonObject itself, is correct from debbuging PoV, however I'm getting HTTP Status 406 from the browser.
I've tried also just returning String (by returning jsonObject.toString()), instead of JSONObject.
However it causes encoding issue - so that JSON from the browser, is not the JSON itself (some additional slashes, quotation marks etc.).

Is there any way, to return JSON from file?

Body:
I know I have been very late for this but why don't you try the below workaround.

@RequestMapping(method = RequestMethod.GET)
public @ResponseBody String getTest() throws IOException {
    JSONObject jsonObject = new JSONObject(FileUtils.readFileToString(testMockup.getFile(), CharEncoding.UTF_8));
    return jsonObject.toString();
}


问:
Xamarin.Forms UWP - InvalidCastException when trying to set TextDecorations for TextBlock
In a Xamarin.Forms project, I'm trying to allow underlined Labels. So I have a custom renderer, and I'm trying to do something simple:

```<code>Control.TextDecorations = TextDecorations.Underline;
</code>```

It compiles just fine, but when the app launches, I'm getting an InvalidCastException on that line which says:

System.InvalidCastException: 'Unable to cast object of type 'Windows.UI.Xaml.Controls.TextBlock' to type 'Windows.UI.Xaml.Controls.ITextBlock5'.'

Here's a screenshot of the exception:

Also, when inspecting the Control, I noticed there are a ton of InvalidCastException exceptions on other properties of the TextBlock control as well - here's a small sample:

Why is it trying to cast to a ITextBlock5 type? Is this a UWP bug? Is there a workaround to get underline to work?

答:
According to the Microsoft documentation, the TextDecorations property wasn't introduced until version 15063. You're probably getting that exception because you're on an earlier version of Windows.

As a workaround, you can create an Underline() object and add a Run() object to the Underline object's Inlines collection, like this:

```<code>// first clear control content
Control.Inlines.Clear();

// next create new Underline object and
// add a new Run to its Inline collection
var underlinedText = new Underline();
underlinedText.Inlines.Add(new Run { Text = "text of xamarin element here" });

// finally add the new Underline object
// to the Control's Inline collection
Control.Inlines.Add(underlinedText);
</code>```

Inside the custom renderer's OnElementChanged() override method, it would look something like this:

```<code>protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
    base.OnElementChanged(e);
    var view = e.NewElement as LabelExt; // LabelExt => name of PCL custom Label class
    var elementExists = (view != null && Control != null);
    if (!elementExists)
    {
        return;
    }

    // add underline to label
    Control.Inlines.Clear();
    var underlinedText = new Underline();
    underlinedText.Inlines.Add(new Run { Text = view.Text });
    Control.Inlines.Add(underlinedText);
}
</code>```

Body:
In a Xamarin.Forms project, I'm trying to allow underlined Labels. So I have a custom renderer, and I'm trying to do something simple:

Control.TextDecorations = TextDecorations.Underline;

It compiles just fine, but when the app launches, I'm getting an InvalidCastException on that line which says:

System.InvalidCastException: 'Unable to cast object of type 'Windows.UI.Xaml.Controls.TextBlock' to type 'Windows.UI.Xaml.Controls.ITextBlock5'.'

Here's a screenshot of the exception:

Also, when inspecting the Control, I noticed there are a ton of InvalidCastException exceptions on other properties of the TextBlock control as well - here's a small sample:

Why is it trying to cast to a ITextBlock5 type? Is this a UWP bug? Is there a workaround to get underline to work?

Body:
According to the Microsoft documentation, the TextDecorations property wasn't introduced until version 15063. You're probably getting that exception because you're on an earlier version of Windows.

As a workaround, you can create an Underline() object and add a Run() object to the Underline object's Inlines collection, like this:

// first clear control content
Control.Inlines.Clear();

// next create new Underline object and
// add a new Run to its Inline collection
var underlinedText = new Underline();
underlinedText.Inlines.Add(new Run { Text = "text of xamarin element here" });

// finally add the new Underline object
// to the Control's Inline collection
Control.Inlines.Add(underlinedText);

Inside the custom renderer's OnElementChanged() override method, it would look something like this:

protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
    base.OnElementChanged(e);
    var view = e.NewElement as LabelExt; // LabelExt => name of PCL custom Label class
    var elementExists = (view != null && Control != null);
    if (!elementExists)
    {
        return;
    }

    // add underline to label
    Control.Inlines.Clear();
    var underlinedText = new Underline();
    underlinedText.Inlines.Add(new Run { Text = view.Text });
    Control.Inlines.Add(underlinedText);
}


问:
SSRS - Search entire Row for a Value - and highlight if found
The Query behind an SSRS report puts the Text "XXX" in fields that should have a value but do not.

When the report runs, I want all Cells that have "XXX" in them to be highlighted a certain color.

I have this Expression in the BackgroundColor Property of one of the fields:

```<code>=IIF(Fields!County.Value = "XXX", "DarkSalmon","Transparent")
</code>```

and it is working fine.

Do I have to put that expression in every field I am checking - or can I use one expression that will look at every field in the row and highlight any that have "XXX" in them?

Thanks!

答:
You need select all cells for putting your expression

Please check this example

Body:
The Query behind an SSRS report puts the Text "XXX" in fields that should have a value but do not.

When the report runs, I want all Cells that have "XXX" in them to be highlighted a certain color.

I have this Expression in the BackgroundColor Property of one of the fields:

=IIF(Fields!County.Value = "XXX", "DarkSalmon","Transparent")

and it is working fine.

Do I have to put that expression in every field I am checking - or can I use one expression that will look at every field in the row and highlight any that have "XXX" in them?

Thanks!


问:
Buttons to replace lists
I'm trying to replace the 2017 events with the 2018 events under each different section when the buttons are clicked, and then vice versa, to only show one list at a time under each event. I know something isn't right, but I can't figure it out. Any advice for how I can make these buttons work please?

$(document).ready(function() {
  var v = false;
  $("button#2018b").click(function() {
    if (v == false) {
      v = true;
    }
  }); //end button
  $("button#2017b").click(function() {
    if (v == true) {
      v = false;
    }
  }); //end button
}); //end document ready

//$("2017".replacewith("
");
//$("2018".replacewith("
");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.panel {
  display: none;
}

ul {
  list-style-type: none;
}

button {
  margin-left: 180px;
}</code>```

Fox Valley Runners Club

 <button id="2018B">Future Events - 2018</button>

 <button id="2017B">Current Events - 2017</button>

5k/10k Events

5k/10 Events

Mini Sprint

Iron Horse

Twilight Trail

5K / 10K Events

Snowball Sprint
 1/14/18
Mosquito Hill
New London

Winter Warrior
2/06/18
Bay Beach
 Green Bay

Big Chill Run
2/24/18
 Mid Valley Golf Course
De Pere

    </button>

Half Marathon Events

Half Marathon Events

Fox River Marathon

N.E.W. Half Marathon

Winnebago Run

Half Marathon Events

Frosty Indoor Marathon
 1/15/18
TryIt Ice Arena
 Neenah

Valentine Run
2/12/18
Green Isle Park
 De Pere

Snowball Marathon
3/03/18
Menominee Park
Oshkosh

Full Marathon Events

Full Marathon Events

Cheesehead Marathon

Chain O'Lakes Marathon

Fox Cities Marathon

Full Marathon Events

Trailbreaker Marathon
 4/02/18
Leach Amphitheatre
 Oshkosh

Jailbreak Marathon
 4/16/18
Menominee Park
Oshkosh

Cellcom Marathon
5/20/18
 Lombardi Atrium
 Green Bay

```

答:
Remark

Set a
 to the corresponding <button>.

```<code><button id="show-event">Event</button>
<div id="event"></div>
</code>```

Hide all divs but only show one. On each button click hide the current div and show the selected one.

Example

var events = document.querySelectorAll("div[id^=events-]");
var btnEvents = document.querySelectorAll("button[id^=show-events-]");
var currBtn = document.querySelector("button[id^=show-events-][class=active]");
var idCurrEvent = currBtn.getAttribute("id").replace("show-", "");
var currEvent = document.getElementById(idCurrEvent);
currEvent.classList.add("show");

btnEvents.forEach(btn => {
  btn.addEventListener("click", function() {
    currBtn.classList.remove("active");
    this.classList.add("active");
    currBtn = this;
    currEvent.classList.remove("show");
    currEvent = document.getElementById(this.id.replace("show-", ""));
    currEvent.classList.add("show");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  outline: none;
}

.active {
  border: 1px solid orange;
}

div[id^=events-] {
  display: none;
}

.show {
  display: block !important;
}</code>```

Events

<button id="show-events-2016">2016</button>
<button id="show-events-2017" class="active">2017</button>
<button id="show-events-2018">2018</button>

Event 1 2016

Event 2 2016

Event 3 2016

Event 1 2017

Event 2 2017

Event 3 2017

Event 1 2018

Event 2 2018

Event 3 2018

```

Title: Buttons to replace lists

Body:
I'm trying to replace the 2017 events with the 2018 events under each different section when the buttons are clicked, and then vice versa, to only show one list at a time under each event. I know something isn't right, but I can't figure it out. Any advice for how I can make these buttons work please?

$(document).ready(function() {
  var v = false;
  $("button#2018b").click(function() {
    if (v == false) {
      v = true;
    }
  }); //end button
  $("button#2017b").click(function() {
    if (v == true) {
      v = false;
    }
  }); //end button
}); //end document ready

//$("2017".replacewith("
");
//$("2018".replacewith("
");

.panel {
  display: none;
}

ul {
  list-style-type: none;
}

button {
  margin-left: 180px;
}

Fox Valley Runners Club

 <button id="2018B">Future Events - 2018</button>

 <button id="2017B">Current Events - 2017</button>

5k/10k Events

5k/10 Events

Mini Sprint

Iron Horse

Twilight Trail

5K / 10K Events

Snowball Sprint
 1/14/18
Mosquito Hill
New London

Winter Warrior
2/06/18
Bay Beach
 Green Bay

Big Chill Run
2/24/18
 Mid Valley Golf Course
De Pere

    </button>

Half Marathon Events

Half Marathon Events

Fox River Marathon

N.E.W. Half Marathon

Winnebago Run

Half Marathon Events

Frosty Indoor Marathon
 1/15/18
TryIt Ice Arena
 Neenah

Valentine Run
2/12/18
Green Isle Park
 De Pere

Snowball Marathon
3/03/18
Menominee Park
Oshkosh

Full Marathon Events

Full Marathon Events

Cheesehead Marathon

Chain O'Lakes Marathon

Fox Cities Marathon

Full Marathon Events

Trailbreaker Marathon
 4/02/18
Leach Amphitheatre
 Oshkosh

Jailbreak Marathon
 4/16/18
Menominee Park
Oshkosh

Cellcom Marathon
5/20/18
 Lombardi Atrium
 Green Bay

Body:
Remark

Set a <div> to the corresponding <button>.

<button id="show-event">Event</button>
<div id="event"></div>

Hide all divs but only show one. On each button click hide the current div and show the selected one.

Example

var events = document.querySelectorAll("div[id^=events-]");
var btnEvents = document.querySelectorAll("button[id^=show-events-]");
var currBtn = document.querySelector("button[id^=show-events-][class=active]");
var idCurrEvent = currBtn.getAttribute("id").replace("show-", "");
var currEvent = document.getElementById(idCurrEvent);
currEvent.classList.add("show");

btnEvents.forEach(btn => {
  btn.addEventListener("click", function() {
    currBtn.classList.remove("active");
    this.classList.add("active");
    currBtn = this;
    currEvent.classList.remove("show");
    currEvent = document.getElementById(this.id.replace("show-", ""));
    currEvent.classList.add("show");
  });
});

button {
  outline: none;
}

.active {
  border: 1px solid orange;
}

div[id^=events-] {
  display: none;
}

.show {
  display: block !important;
}

<h1>Events</h1>

<button id="show-events-2016">2016</button>
<button id="show-events-2017" class="active">2017</button>
<button id="show-events-2018">2018</button>

<div id="events-2016">
  <ul>
    <li>Event 1 2016</li>
    <li>Event 2 2016</li>
    <li>Event 3 2016</li>
  </ul>
</div>

<div id="events-2017">
  <ul>
    <li>Event 1 2017</li>
    <li>Event 2 2017</li>
    <li>Event 3 2017</li>
  </ul>
</div>

<div id="events-2018">
  <ul>
    <li>Event 1 2018</li>
    <li>Event 2 2018</li>
    <li>Event 3 2018</li>
  </ul>
</div>


问:
priority of implicit conversions
I have two classes that are interchangeable. A can be converted to B and B can be converted to A. What I would like is a way to specify that A's conversion to B is preferred, yet still be able to do things like:

```<code>B b = A();
B b; b = A();
</code>```

What I'm trying to avoid is this issue:
    B b = q ? A() : B();

error: conditional expression is ambiguous; 'A' can be converted to 'B' and vice versa

I've tried a range of explicit settings, but I can't quite figure out if this is possible. I prefer to not have to call out static_cast on these.

```<code>struct B;
struct A {
    int a;
    A () {
    }
    A (B b);
    explicit operator B ();
};
struct B {
    int b;
    B () {
    }
    B (A a);
    explicit operator A ();
};
A::A (B b) {
}
A::operator B () {
    B b;
    return b;
}
B::B (A a) {
}
B::operator A () {
    A a;
    return a;
}
int main () {
    int q;
    A a;
    B b;
    A ab = q ? a : b;
    B b2 = a;
}
</code>```

答: The solution is to do this A ab = q ? (A)a : (A)b; this way each of them are being explicitly cast which your code tries to do this implicitly.

Title: priority of implicit conversions

Body:
I have two classes that are interchangeable. A can be converted to B and B can be converted to A. What I would like is a way to specify that A's conversion to B is preferred, yet still be able to do things like:

B b = A();
B b; b = A();

What I'm trying to avoid is this issue:
    B b = q ? A() : B();

error: conditional expression is ambiguous; 'A' can be converted to 'B' and vice versa

I've tried a range of explicit settings, but I can't quite figure out if this is possible. I prefer to not have to call out static_cast on these.

struct B;
struct A {
    int a;
    A () {
    }
    A (B b);
    explicit operator B ();
};
struct B {
    int b;
    B () {
    }
    B (A a);
    explicit operator A ();
};
A::A (B b) {
}
A::operator B () {
    B b;
    return b;
}
B::B (A a) {
}
B::operator A () {
    A a;
    return a;
}
int main () {
    int q;
    A a;
    B b;
    A ab = q ? a : b;
    B b2 = a;
}


问:
How to differentiate between deploying releases vs snapshots
I may be missing something extremely obvious, but I need some clarification regardless. I am about to begin development using maven and archiva. I added both servers + settings to settings.xml, and distributionManagement tags to the maven POM which I want to deploy.

I put references to both my internal snapshot repo, and my internal release repo in the POM. is there a specific maven command or option, which specifies to deploy as a SNAPSHOT, and NOT to both repos? Or if I do deploy, will it automatically push one copy to each repo?

Can someone clarify this?´

答:
You can execute mvn deploy.

If your POM version contains -SNAPSHOT as suffix, it will deploy into the repository configured under distributionManagement.snapshotRepository.

If your POM doesn't contain -SNAPSHOT suffix, it will deploy into the repository configured under distributionManagement.repository.

However, I do recommend you to use maven-release-plugin to manage versioning and deployment. By running mvn -B release:clean release:prepare release:perform, in resume:

the suffix -SNAPSHOT is removed from the version (e.g. 2.1-SNAPSHOT -> 2.1);

the application is built so as to generate JAR files;

the code is committed to your code repository (e.g. git) and tagged (e.g. 2.1);

the JAR is deployed into your release repository (not snapshot repo);

the version is incremented and the suffix -SNAPSHOT is added (e.g. 2.2-SNAPSHOT).


问:
For each record in a table, insert a record in another table and put the key into the first table's record
I am localizing an application and need to convert existing TEXT columns to have multiple translated versions of the text.

The original table looks like this:

person

personId: INT

description: VARCHAR(20)

(other columns)

To store the localized text, I created a new table:

text

textId: INT (auto-incrementing)

languageId: INT

text: TEXT

I want to replace the person.description column with a new person.descTextId column.

For each person that has a value in the description column but descTextId is null:

Insert a new text record with that person's description (English
languageId=1)

Update the person's descTextId to the new textId
value

Then remove the person.description column.

What is the cleanest way to do all of this?  Do I need to create a procedure and cursor or is there a clever MySQL syntax that would help with this? How would you do it?

答:
I figured it out with a temporary procedure and loop.</p>

```<code>DROP PROCEDURE IF EXISTS moveToTextTable;
DELIMITER ;;

CREATE PROCEDURE moveToTextTable()
BEGIN
  DECLARE n INT DEFAULT 0;
  DECLARE i INT DEFAULT 0;
  DECLARE id INT DEFAULT 0;

  SELECT COUNT(*) INTO n FROM person WHERE description IS NOT NULL AND description <> '';
  WHILE i<n DO
    SELECT personId INTO id FROM person WHERE description IS NOT NULL AND description <> '' AND descTextId IS NULL LIMIT 1;
    INSERT INTO text (languageId, text) SELECT 1, description FROM person WHERE personId = id;
    UPDATE person SET descTextId = LAST_INSERT_ID() WHERE personId = id;
    SET i = i + 1;
  END WHILE;
END;
;;

DELIMITER ;
CALL moveToTextTable();
DROP PROCEDURE IF EXISTS moveToTextTable;
</code>```

Body:
I figured it out with a temporary procedure and loop.

DROP PROCEDURE IF EXISTS moveToTextTable;
DELIMITER ;;

CREATE PROCEDURE moveToTextTable()
BEGIN
  DECLARE n INT DEFAULT 0;
  DECLARE i INT DEFAULT 0;
  DECLARE id INT DEFAULT 0;

  SELECT COUNT(*) INTO n FROM person WHERE description IS NOT NULL AND description <> '';
  WHILE i<n DO
    SELECT personId INTO id FROM person WHERE description IS NOT NULL AND description <> '' AND descTextId IS NULL LIMIT 1;
    INSERT INTO text (languageId, text) SELECT 1, description FROM person WHERE personId = id;
    UPDATE person SET descTextId = LAST_INSERT_ID() WHERE personId = id;
    SET i = i + 1;
  END WHILE;
END;
;;

DELIMITER ;
CALL moveToTextTable();
DROP PROCEDURE IF EXISTS moveToTextTable;


问:
How to write bosun alerts which handle low traffic volumes
If you are writing a bosun alert which is based of a percentage error rate for requests handled by your system, how do you write it in such a way that it handles periods of low traffic.

For example:
If I have an alert which looks back over the last 5 minutes and works out the error rate for requests
$errorRate = $numberErr/$numberReq and then triggers an alarm if the errorRate exceeds a predefined threshold crit = $errorRate > 0.05 this can work quite well so long as every 5 minute period had a sufficiently large number of requests ($numberReq).

If the number of requests in a 5 minute period was 10,000 then 501 errors would be required to trigger an alarm. However if the number of requests in a 5 minute period was 100 then only 5 errors would be required to trigger an alarm.

How can I write an alert which handles periods where the number of requests are so low that a small number of errors will equate to a large error rate. I had considered a sliding window of time, rather than a fixed 5 minute period, where the window would increase in size until the number of requests was high enough to give some confidence in the alarm. e.g. increase the time period until the number of requests is 10,000.

I can't find a way to achieve this in bosun, and I don't want to commit to a larger period of time for my alerts because the traffic rate varies so much. A longer period during peak traffic could result in an actual error causing a much larger impact.

答:
I generally pair any percentage and/or historical based alerts with a static threshold.

For example: crit = numberErr > 100 && $errorRate > 0.05. That way the percent part doesn't matter unless the number of errors have also crossed some threshold because the entire statement won't be true.


问:
Inheritance and pointers
I have code like this:

```<code>class Human
{
    protected:
        int age;
        std::string sex;
    public:
        virtual void speak() = 0;
};
class Child:public Human
{
    public:
        void speak(){std::cout << "I am Child\n";}
};
class Man:public Human
{
    public:
        void speak(){std::cout << "I am Man\n";}
};
class Woman:public Human
{
    public:
        void speak(){std::cout << "I am Woman\n";}
};
(don't know, std::shared_ptr<Human> maybe?) operator*(std::shared_ptr<Child> &b, int x)
{
    b->setAge(b->getAge()+x);
    if(b->getAge()>18 && b->getSex()=="Man")
    {
        return (i want b to become std::shared_ptr<Man>)
    }
    if(b->getAge()>18 && b->getSex()=="Woman")
    {
        return (here I want b to become std::shared_ptr<Woman>);
    }
    return;
}
int main(){
    auto x = std::make_shared<Child>;
    x*19;
}
</code>```

I know it seems odd, but it's the simplest case i can think of, without having to write down all code i'm struggling with rn. Could someone explain, what type should overload be and how to change shared_ptr type, knowing they derive from same parent?

答:
You cannot make the type T<Derived> inherit from T<Base> because C++ templates do not support covariance. To do so would be unsafe for certain types, such as mutable references to containers. (Imagine taking a reference to std::vector<Cat> as std::vector<Animal>& and pushing back a dog!)

(I would make this answer a comment, but I don't have comment abilities.)

Update:
You can write a non-template wrapper that handles heap data:

```<code>class Wrapper
{
public:
  Wrapper(Base* b) : raw(b) {}
  ~Wrapper() { delete raw; }
  Base& get() { return *base; }
private:
  Base* raw;
}
</code>```

Of course, in your example, you use std::shared_ptr and not std::unique_ptr. You would have to handle reference counting instead of simply deleting the data in the destructor, but the technique of keeping an internal raw pointer still stands.

Update 2:

The above code could be used as is to provide a level of indirection, such that all classes that inherit from the base class may be held in the same type, without writing your own reference counter:

std::shared_ptr<Wrapper>

This solution may be seen as similar to doing std::shared_ptr<Base*>, except that the latter solution would leak memory.

Title: Inheritance and pointers

Body:
I have code like this:

class Human
{
    protected:
        int age;
        std::string sex;
    public:
        virtual void speak() = 0;
};
class Child:public Human
{
    public:
        void speak(){std::cout << "I am Child\n";}
};
class Man:public Human
{
    public:
        void speak(){std::cout << "I am Man\n";}
};
class Woman:public Human
{
    public:
        void speak(){std::cout << "I am Woman\n";}
};
(don't know, std::shared_ptr<Human> maybe?) operator*(std::shared_ptr<Child> &b, int x)
{
    b->setAge(b->getAge()+x);
    if(b->getAge()>18 && b->getSex()=="Man")
    {
        return (i want b to become std::shared_ptr<Man>)
    }
    if(b->getAge()>18 && b->getSex()=="Woman")
    {
        return (here I want b to become std::shared_ptr<Woman>);
    }
    return;
}
int main(){
    auto x = std::make_shared<Child>;
    x*19;
}

I know it seems odd, but it's the simplest case i can think of, without having to write down all code i'm struggling with rn. Could someone explain, what type should overload be and how to change shared_ptr type, knowing they derive from same parent?

Body:
You cannot make the type T<Derived> inherit from T<Base> because C++ templates do not support covariance. To do so would be unsafe for certain types, such as mutable references to containers. (Imagine taking a reference to std::vector<Cat> as std::vector<Animal>& and pushing back a dog!)

(I would make this answer a comment, but I don't have comment abilities.)

Update:
You can write a non-template wrapper that handles heap data:

class Wrapper
{
public:
  Wrapper(Base* b) : raw(b) {}
  ~Wrapper() { delete raw; }
  Base& get() { return *base; }
private:
  Base* raw;
}

Of course, in your example, you use std::shared_ptr and not std::unique_ptr. You would have to handle reference counting instead of simply deleting the data in the destructor, but the technique of keeping an internal raw pointer still stands.

Update 2:

The above code could be used as is to provide a level of indirection, such that all classes that inherit from the base class may be held in the same type, without writing your own reference counter:

std::shared_ptr<Wrapper>

This solution may be seen as similar to doing std::shared_ptr<Base*>, except that the latter solution would leak memory.


问:
How do I modify the session in the Django test framework
My site allows individuals to contribute content in the absence of being logged in by creating a User based on the current session_key

I would like to setup a test for my view, but it seems that it is not possible to modify the request.session:

I'd like to do this:

```<code>from django.contrib.sessions.models import Session
s = Session()
s.expire_date = '2010-12-05'
s.session_key = 'my_session_key'
s.save()
self.client.session = s
response = self.client.get('/myview/')
</code>```

But I get the error:

```<code>AttributeError: can't set attribute
</code>```

Thoughts on how to modify the client session before making get requests?
I have seen this and it doesn't seem to work

答:
as per the docs you can add values to the session in the test client via eg

```<code>def test_something(self):
    session = self.client.session
    session['somekey'] = 'test'
    session.save()
</code>```

https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.Client.session

This will let you test views that require data in the session to function correctly.

So for this question:

```<code>session = self.client.session
   session['expire_date'] = '2010-12-05'
   .....
   session.save()
</code>```

Body:
My site allows individuals to contribute content in the absence of being logged in by creating a User based on the current session_key

I would like to setup a test for my view, but it seems that it is not possible to modify the request.session:

I'd like to do this:

from django.contrib.sessions.models import Session
s = Session()
s.expire_date = '2010-12-05'
s.session_key = 'my_session_key'
s.save()
self.client.session = s
response = self.client.get('/myview/')

But I get the error:

AttributeError: can't set attribute

Thoughts on how to modify the client session before making get requests?
I have seen this and it doesn't seem to work

Body:
as per the docs you can add values to the session in the test client via eg

def test_something(self):
    session = self.client.session
    session['somekey'] = 'test'
    session.save()

https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.Client.session

This will let you test views that require data in the session to function correctly.

So for this question:

session = self.client.session
   session['expire_date'] = '2010-12-05'
   .....
   session.save()


问:
Get last/next week Wednesday date in C#
How would I get last week Wednesday and next week Wednesday's date in C#:</p>

```<code>public Form1()
{
   InitializeComponent();
   CurrentDate.Text = "Today's Date: " + DateTime.Now.ToString("dd/MM/yyyy");
   CurrentRent.Text = "Current Rent Date: "; // last wednesday
   NextRent.Text = "Next Rent Date: "; // next wednesday
}
</code>```

答:
```<code>    private static DateTime FindPreviousDayOfWeek(DateTime fromDate, DayOfWeek findDay,
        bool skipSame = false)
    {
        if (fromDate.DayOfWeek < findDay)
            fromDate = fromDate.AddDays(-((int)fromDate.DayOfWeek - 1 + (int)findDay));
        else if (fromDate.DayOfWeek > findDay)
            fromDate = fromDate.AddDays(-((int)fromDate.DayOfWeek - (int)findDay));
        else if (fromDate.DayOfWeek == findDay && skipSame == true)
            fromDate = fromDate.AddDays(-7);

        return fromDate;
    }
</code>```

the skipSame variable does not include the current day if it is the saem as the desired day.

Title: Get last/next week Wednesday date in C#

Body:
How would I get last week Wednesday and next week Wednesday's date in C#:

public Form1()
{
   InitializeComponent();
   CurrentDate.Text = "Today's Date: " + DateTime.Now.ToString("dd/MM/yyyy");
   CurrentRent.Text = "Current Rent Date: "; // last wednesday
   NextRent.Text = "Next Rent Date: "; // next wednesday
}

Body:
    private static DateTime FindPreviousDayOfWeek(DateTime fromDate, DayOfWeek findDay,
        bool skipSame = false)
    {
        if (fromDate.DayOfWeek < findDay)
            fromDate = fromDate.AddDays(-((int)fromDate.DayOfWeek - 1 + (int)findDay));
        else if (fromDate.DayOfWeek > findDay)
            fromDate = fromDate.AddDays(-((int)fromDate.DayOfWeek - (int)findDay));
        else if (fromDate.DayOfWeek == findDay && skipSame == true)
            fromDate = fromDate.AddDays(-7);

        return fromDate;
    }

the skipSame variable does not include the current day if it is the saem as the desired day.