问:
Shorten string without cutting words in JavaScript
I'm not very good with string manipulation in JavaScript, and I was wondering how you would go about shortening a string without cutting any word off. I know how to use substring, but not indexOf or anything really well.

Say I had the following string:

```<code>text = "this is a long string I cant display"
</code>```

I want to trim it down to 10 characters, but if it doesn't end with a space, finish the word. I don't want the string variable to look like this:

"this is a long string I cant dis"

I want it to finish the word until a space occurs.

答:
I'm late to the party, but here's a small and easy solution I came up with to return an amount of words.

It's not directly related to your requirement of characters, but it serves the same outcome that I believe you were after.

```<code>function truncateWords(sentence, amount, tail) {
  const words = sentence.split(' ');

  if (amount >= words.length) {
    return sentence;
  }

  const truncated = words.slice(0, amount);
  return `${truncated.join(' ')}${tail}`;
}

const sentence = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.';

console.log(truncateWords(sentence, 10, '...'));
</code>```

See the working example here:
https://jsfiddle.net/bx7rojgL/

Body:
I'm not very good with string manipulation in JavaScript, and I was wondering how you would go about shortening a string without cutting any word off. I know how to use substring, but not indexOf or anything really well.

Say I had the following string:

text = "this is a long string I cant display"

I want to trim it down to 10 characters, but if it doesn't end with a space, finish the word. I don't want the string variable to look like this:

"this is a long string I cant dis"

I want it to finish the word until a space occurs.

Body:
I'm late to the party, but here's a small and easy solution I came up with to return an amount of words.

It's not directly related to your requirement of characters, but it serves the same outcome that I believe you were after.

function truncateWords(sentence, amount, tail) {
  const words = sentence.split(' ');

  if (amount >= words.length) {
    return sentence;
  }

  const truncated = words.slice(0, amount);
  return `${truncated.join(' ')}${tail}`;
}

const sentence = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.';

console.log(truncateWords(sentence, 10, '...'));

See the working example here:
https://jsfiddle.net/bx7rojgL/


来源: stackexchange

问:
Set Cover Reduction
Let's say we have a set U = {x1, x2, x3} and a set S = {{x1},{x1, x2},{x1, x3},{x1,x1,x3}}.
This is purely an example and the problem is for the general problem. This looks just like a regular set cover problem, which is why I figure reducing it to a true set cover problem is feasible. The twist is that the elements in U needs to be 'picked' z amount of times, where z is different for each x1, x2, x3.... and so forth.

Any subset in S can only pick up the elements they have inside them ONCE. Given a number 'k', is it possible to form a collection of subsets in S so that

Every element in U is included.

Every element is included z amount of times, where z is different for all x'es.

If i can formulate the Set Cover problem in such a way that'd be great, but im stuck at this part.

答: The covering problem is NP-complete, because of it, heuristic methods are employed to found good solutions."The algorithm design Manual" from Skiena have a detailed discussion about the subject.</p>

ContentLicense: CC BY-SA 3.0

Title: Set Cover Reduction


问:
Sending and receiving SMSes without a native messaging application
I tried to research around to find the answer to this question, and I have found bits and pieces to different parts of my question, but I still can't decipher whether it's possible (or at least within the confines of our very small, beginner operation). I'll explain what him and I are hoping to acheive, and just a fairly simply response or maybe some links to some literature on the possibilities would be much appreciated.

I'm not looking for someone to have to spill some code or something like that, as I realize my request will be somewhat vague (as I don't want to give away too much of what our application is about, which we will simply call Alpha) but also because my knowledge into the world of program is very minimal (I'm more behind the design and everything else than the programming).

We would like to be able to send and receive SMS text messages within the application we are creating, without having to deal with the native messaging application. We would like to do this because (at least with HTC phones), there is no option to easily "copy" a received, individual text message. On an HTC phone, when you long-press an individual text message, the ability to copy the message is simply not there (but it is on Samsung, and I'm not sure about Motorola, so I assume it's a Sense UI limitation).

Because we need an easy way to move the received text message into our application, and since the easy, intuitive way is not available (again, at least not to HTC owners), we have had to try to come up with other ways of doing so. So, we were wondering if it's possible to create your own small text messaging area within our application so that only the text messages that pertain to our application will show up within the application without first popping up in the native messaging application?

Or, is it possible to add a function to the "Message Options" that pop up after long-pressing an individual text, allowing the user to "Send to Alpha application"?

Again, I know this might be kind of vague, or not the easiest to follow, and I wish I had more programming knowledge to put it into more specific terms.

I'm new to the Android development world, as is a buddy of mine who I'm creating an Android application with.

答:
Yes, it is completely possible - for receiving just implement a Listener and add it to your manifest.xml file like so:

```<code><receiver android:name=".MyListener">
   <intent-filter>
       <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
   </intent-filter>
</receiver>
</code>```

That tells the Android framework that you want to be able to receive and handle all SMS messages.

Here's an article I found that talks about how:
http://www.devx.com/wireless/Article/39495/1954

Body:
Yes, it is completely possible - for receiving just implement a Listener and add it to your manifest.xml file like so:

<receiver android:name=".MyListener">
   <intent-filter>
       <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
   </intent-filter>
</receiver>

That tells the Android framework that you want to be able to receive and handle all SMS messages.

Here's an article I found that talks about how:
http://www.devx.com/wireless/Article/39495/1954

ContentLicense: CC BY-SA 2.5


问:
Convert Column of List to Dataframe
I have a column of lists in a spark dataframe. </p>

<pre class="lang-python prettyprint-override"><code>+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+
</code>```

<p>How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size. </p>

<p>For Example, </p>

<pre class="lang-python prettyprint-override"><code>+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+
</code>```

答:
@desertnaut's answer can also be accomplished with dataframe and udf.

import pyspark.sql.functions as F

dimensionality = 7
column_names = ['c'+str(i+1) for i in range(dimensionality)]
splits = [F.udf(lambda val:val[i],FloatType()) for i in range(dimensionality)]
df = df.select(*[s('features').alias(j) for s,j in zip(splits,column_names)])
```

Title: Convert Column of List to Dataframe

Body:
I have a column of lists in a spark dataframe.

+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+

How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size.

For Example,

+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+


问:
How to print out elements of multiset of pair
```<code>multiset< pair<int,pair<int,int>> >ml;
pair<int,pair<int,int>> p;
p.first=3;
p.second.first=5;
p.second.second=2;
ml.insert(p);
</code>```

That's how I insert in my multiset of pair of pair
But I don't know how to print out all elements in my multiset of pair of pair
I have tried that but it's not working

```<code> multiset< pair<long long,pair<long long,long long> > >::iterator it;
      it=ml.begin();
   p=*it;
cout<<p.first<<" "<<p.second.first<<" "<<p.second.second<<endl;
</code>```

答:
There are two approaches to this. They are almost the same, but the second one is much shorter.

First approach:

```<code>for (multiset< pair<int, pair<int,int> > >::iterator it = ml.begin(); it!=ml.end(); it++) {
    cout<<"First: "<<it->first<<", Second: "<<it->second.first<<", Third: "<<it->second.second<<endl;
}
</code>```

Second approach (only in C++11 and later):

```<code>for (auto it:ml) {
    cout<<"First: "<<it.first<<", Second: "<<it.second.first<<", Third: "<<it.second.second<<endl;
}
</code>```

And the output is the same:

```<code>First: 3, Second: 5, Third: 2
</code>```

Body:
multiset< pair<int,pair<int,int>> >ml;
pair<int,pair<int,int>> p;
p.first=3;
p.second.first=5;
p.second.second=2;
ml.insert(p);

That's how I insert in my multiset of pair of pair
But I don't know how to print out all elements in my multiset of pair of pair
I have tried that but it's not working

 multiset< pair<long long,pair<long long,long long> > >::iterator it;
      it=ml.begin();
   p=*it;
cout<<p.first<<" "<<p.second.first<<" "<<p.second.second<<endl;

Body:
There are two approaches to this. They are almost the same, but the second one is much shorter.

First approach:

for (multiset< pair<int, pair<int,int> > >::iterator it = ml.begin(); it!=ml.end(); it++) {
    cout<<"First: "<<it->first<<", Second: "<<it->second.first<<", Third: "<<it->second.second<<endl;
}

Second approach (only in C++11 and later):

for (auto it:ml) {
    cout<<"First: "<<it.first<<", Second: "<<it.second.first<<", Third: "<<it.second.second<<endl;
}

And the output is the same:

First: 3, Second: 5, Third: 2


问:
rails - Case Insensitive Search Condition
I have the following:

```<code>  @users = User.find( :all,
                      :select => 'users.*',
                      :conditions => ["fname || ' ' || lname LIKE ?", '%'+"#{params[:q]}"+'%']
</code>```

Problem here is that the search input params[:q] is case sensitive. How can I make it case insensitive in my Rails 3 Heroku app?

Thanks

答: For PostgreSQL to get case insensitive LIKE just use ILIKE. It works according to the active locale.

Body:
I have the following:

  @users = User.find( :all,
                      :select => 'users.*',
                      :conditions => ["fname || ' ' || lname LIKE ?", '%'+"#{params[:q]}"+'%']

Problem here is that the search input params[:q] is case sensitive. How can I make it case insensitive in my Rails 3 Heroku app?

Thanks


问:
Caxis auto equivalent in OpenCV Python or Pillow?
MATLAB has the function caxis auto which comes in handy for viewing images if they have a low contrast and are looking almost black.

In Matlab it works like this:

```<code>figure;imshow(I);caxis auto
</code>```

I know  how to adjust the contrast in OpenCV Python, like:

```<code> img = cv2.imread('someimage.jpg',0)
 equ = cv2.equalizeHist(img)

 #Showing image
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

However, this does is not the same implementation as caxis auto which changes the illuminuation adaptively.

答:
OpenCV does not use colormaps for displaying single channel images. In Matlab, caxis sets the colormap limits. In other words, if your image has values between 0.5 and 1.0, you can set the displayed color limits so that 0.5 is rendered as if it were 0.0, and scale that way. OpenCV just displays the image values as they are.

What that means is that if you want a different scaling for the values, you can just change them in the array that gets displayed.

With OpenCV, you can easily accomplish this scaling with cv2.normalize() with the normType=cv2.NORM_MINMAX.

```<code>img = np.random.rand(500, 500, 3)*0.2
cv2.imshow('Low contrast image', img)
cv2.waitKey()
</code>```

```<code>img_scaled = cv2.normalize(img, None, alpha=0.0, beta=1.0, norm_type=cv2.NORM_MINMAX)
cv2.imshow('Scaled colors for display', img_scaled)
cv2.waitKey()
</code>```

Note that this works for both grayscale and color images.

However, if you just have a grayscale image, another option is to display them with Matplotlib. MPL will automatically scale single channel images to the min/max display values.

```<code>from matplotlib import pyplot as plt

img = np.random.rand(500, 500)*0.2
plt.imshow(img, cmap='gray')
plt.show()
</code>```

Note here I included the cmap='gray' argument because the default colormap for a single channel image is Viridis, and not grayscale. You can read more about Matplotlib colormaps here. Generally, if you're looking for similar syntax to Matlab, Matplotlib has you covered---it was initially geared towards people coming to Python from Matlab, so it has similar functionality and syntax.

One last option is to just scale manually in numpy. If your image is an unsigned int type, you can do this simply by shifting the image to have it's lowest value as 0, and then multiply so that it's max value is the maximum of your datatype. Note that when you multiply your image will be converted to a float, so you'll need to recast it. For e.g., if you have a uint16 image, the values range from 0 to 65535, so you could do:

```<code>img_scaled = img.copy() - np.min(img)
img_scaled = np.uint16(img_scaled*(65535/np.max(img)))
</code>```

Or, if you'd like to do this automatically, you can grab the datatype information from the image (including the min and max values possible in a datatype) with np.iinfo() to automatically scale and convert as necessary. Here's a function that will normalize any (signed or unsigned) integer or floating point image:

```<code>def normalize_minmax(img):
    """Scales an image into an interval [min, max] with the same datatype.

    If img.dtype is a float type, img is scaled into [0.0, 1.0].
    If img.dtype is an integer type, img is scaled into [dtype.min, dtype.max].
    If img.dtype is some other type, the original image is returned.
    """
    dtype = img.dtype
    if np.issubdtype(dtype, np.integer): # scale to [dtype.min, dtype.max]
        dtype_info = np.iinfo(img.dtype)
        img_scaled = img - np.min(img)
        scale = (dtype_info.max - dtype_info.min) / np.max(img_scaled)
        img_scaled = img_scaled * scale + dtype_info.min
        return np.round(img_scaled).astype(dtype)
    elif np.issubdtype(dtype, np.float):  # scale to [0, 1]
        img_scaled = img - np.min(img)
        img_scaled = img_scaled / np.max(img_scaled)
        return img_scaled.astype(dtype)
    return img
</code>```

How it works is easy to describe. For the float image case, you simply shift it so that the lowest value is zero, and then divide by the max to get it between 0 and 1. Then just simply cast it back to the original type. For the integer datatypes, it takes a little more effort if you care to include signed integers. In this case the range extends to negative numbers as well. You start off the same by shifting the lowest value to zero. But then you need to scale so that the values span the entire range of the datatype (e.g. (datatype_max - datatype_min) / max(img)). So now your values will span from [0, datatype_max - datatype_min], so you need to add back the datatype_min to get to [datatype_min, datatype_max]. I also rounded the values instead of truncating before converting back to the original datatype.

Body:
MATLAB has the function caxis auto which comes in handy for viewing images if they have a low contrast and are looking almost black.

In Matlab it works like this:

figure;imshow(I);caxis auto

I know  how to adjust the contrast in OpenCV Python, like:

 img = cv2.imread('someimage.jpg',0)
 equ = cv2.equalizeHist(img)

 #Showing image
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

However, this does is not the same implementation as caxis auto which changes the illuminuation adaptively.

Body:
OpenCV does not use colormaps for displaying single channel images. In Matlab, caxis sets the colormap limits. In other words, if your image has values between 0.5 and 1.0, you can set the displayed color limits so that 0.5 is rendered as if it were 0.0, and scale that way. OpenCV just displays the image values as they are.

What that means is that if you want a different scaling for the values, you can just change them in the array that gets displayed.

With OpenCV, you can easily accomplish this scaling with cv2.normalize() with the normType=cv2.NORM_MINMAX.

img = np.random.rand(500, 500, 3)*0.2
cv2.imshow('Low contrast image', img)
cv2.waitKey()

img_scaled = cv2.normalize(img, None, alpha=0.0, beta=1.0, norm_type=cv2.NORM_MINMAX)
cv2.imshow('Scaled colors for display', img_scaled)
cv2.waitKey()

Note that this works for both grayscale and color images.

However, if you just have a grayscale image, another option is to display them with Matplotlib. MPL will automatically scale single channel images to the min/max display values.

from matplotlib import pyplot as plt

img = np.random.rand(500, 500)*0.2
plt.imshow(img, cmap='gray')
plt.show()

Note here I included the cmap='gray' argument because the default colormap for a single channel image is Viridis, and not grayscale. You can read more about Matplotlib colormaps here. Generally, if you're looking for similar syntax to Matlab, Matplotlib has you covered---it was initially geared towards people coming to Python from Matlab, so it has similar functionality and syntax.

One last option is to just scale manually in numpy. If your image is an unsigned int type, you can do this simply by shifting the image to have it's lowest value as 0, and then multiply so that it's max value is the maximum of your datatype. Note that when you multiply your image will be converted to a float, so you'll need to recast it. For e.g., if you have a uint16 image, the values range from 0 to 65535, so you could do:

img_scaled = img.copy() - np.min(img)
img_scaled = np.uint16(img_scaled*(65535/np.max(img)))

Or, if you'd like to do this automatically, you can grab the datatype information from the image (including the min and max values possible in a datatype) with np.iinfo() to automatically scale and convert as necessary. Here's a function that will normalize any (signed or unsigned) integer or floating point image:

def normalize_minmax(img):
    """Scales an image into an interval [min, max] with the same datatype.

    If img.dtype is a float type, img is scaled into [0.0, 1.0].
    If img.dtype is an integer type, img is scaled into [dtype.min, dtype.max].
    If img.dtype is some other type, the original image is returned.
    """
    dtype = img.dtype
    if np.issubdtype(dtype, np.integer): # scale to [dtype.min, dtype.max]
        dtype_info = np.iinfo(img.dtype)
        img_scaled = img - np.min(img)
        scale = (dtype_info.max - dtype_info.min) / np.max(img_scaled)
        img_scaled = img_scaled * scale + dtype_info.min
        return np.round(img_scaled).astype(dtype)
    elif np.issubdtype(dtype, np.float):  # scale to [0, 1]
        img_scaled = img - np.min(img)
        img_scaled = img_scaled / np.max(img_scaled)
        return img_scaled.astype(dtype)
    return img

How it works is easy to describe. For the float image case, you simply shift it so that the lowest value is zero, and then divide by the max to get it between 0 and 1. Then just simply cast it back to the original type. For the integer datatypes, it takes a little more effort if you care to include signed integers. In this case the range extends to negative numbers as well. You start off the same by shifting the lowest value to zero. But then you need to scale so that the values span the entire range of the datatype (e.g. (datatype_max - datatype_min) / max(img)). So now your values will span from [0, datatype_max - datatype_min], so you need to add back the datatype_min to get to [datatype_min, datatype_max]. I also rounded the values instead of truncating before converting back to the original datatype.


问:
Passing 2D-array to VBA/UDF function from sheet
I am on Excel 2010.

When a VBA user-defined function, say make2DArray, outputs a variant representing a 2D-array, this 2D-array can be then used as an input to another VBA function, say someFunction. While calling the functions from within VBA code. It works fine.

However when doing the same, passing make2DArray output as argument to someFunction, from within the sheet (via a formula in a cell), then it seems to work only for 2D-array with **2 or more rows**. Generating 2D-array with 1 row would fail. It seems that the 1-row 2D-array is then transformed automatically into an equivalent 1D-array.

A small example :

```<code>Option Explicit

'returns last (top-most, right-most) element
Function someFunction(v As Variant) As Integer
    On Error Resume Next
        Debug.Print "Dim-1 size", UBound(v, 1) - LBound(v, 1) + 1
        Debug.Print "Dim-2 size", UBound(v, 2) - LBound(v, 2) + 1
    On Error GoTo 0

    someFunction = v(UBound(v, 1), UBound(v, 2))
End Function

Function make2DArray(h As Integer, w As Integer) As Variant
    Dim i As Integer, j  As Integer
    Dim v2d As Variant

    ReDim v2d(1 To h, 1 To w)
    For i = 1 To h
        For j = 1 To w
            v2d(i, j) = i * j
        Next j
    Next i

    make2DArray = v2d
End Function

Sub test()
    'also works when called from sheet
    Debug.Print someFunction(make2DArray(2, 3)) 'returns 6
    'doesn't work when called from sheet
    Debug.Print someFunction(make2DArray(1, 3)) 'returns 3
End Sub
</code>```

The test function will work fine from within VBA. Similarly =someFunction(make2DArray(2, 3)) or any =someFunction(make2DArray(i, j)) cell formula would work well for i>1, however =someFunction(make2DArray(1, 3)) or any =someFunction(make2DArray(1, j)) will only produce a #VALUE! result in the sheet.

My question : Is this behavior documented somewhere? Is there a way to avoid the "casting" from 2D-array to 1D-array for 1-row 2D-arrays?

答:
UDFs should really copy with parameters being either a range, or a vector, or an array, or a scalar constant, or an array/vector output from some other function.
SomeFunction({1,2,3}) gets a 1D vector array
 SomeFunction({1;2;3}) gets a 2D array
 SomeFunction(Range as variant) gets a variant containing a range object whose Value2 property always returns either a scalar or a 2D array.

Body:
I am on Excel 2010.

When a VBA user-defined function, say make2DArray, outputs a variant representing a 2D-array, this 2D-array can be then used as an input to another VBA function, say someFunction. While calling the functions from within VBA code. It works fine.

However when doing the same, passing make2DArray output as argument to someFunction, from within the sheet (via a formula in a cell), then it seems to work only for 2D-array with **2 or more rows**. Generating 2D-array with 1 row would fail. It seems that the 1-row 2D-array is then transformed automatically into an equivalent 1D-array.

A small example :

Option Explicit

'returns last (top-most, right-most) element
Function someFunction(v As Variant) As Integer
    On Error Resume Next
        Debug.Print "Dim-1 size", UBound(v, 1) - LBound(v, 1) + 1
        Debug.Print "Dim-2 size", UBound(v, 2) - LBound(v, 2) + 1
    On Error GoTo 0

    someFunction = v(UBound(v, 1), UBound(v, 2))
End Function

Function make2DArray(h As Integer, w As Integer) As Variant
    Dim i As Integer, j  As Integer
    Dim v2d As Variant

    ReDim v2d(1 To h, 1 To w)
    For i = 1 To h
        For j = 1 To w
            v2d(i, j) = i * j
        Next j
    Next i

    make2DArray = v2d
End Function

Sub test()
    'also works when called from sheet
    Debug.Print someFunction(make2DArray(2, 3)) 'returns 6
    'doesn't work when called from sheet
    Debug.Print someFunction(make2DArray(1, 3)) 'returns 3
End Sub

The test function will work fine from within VBA. Similarly =someFunction(make2DArray(2, 3)) or any =someFunction(make2DArray(i, j)) cell formula would work well for i>1, however =someFunction(make2DArray(1, 3)) or any =someFunction(make2DArray(1, j)) will only produce a #VALUE! result in the sheet.

My question : Is this behavior documented somewhere? Is there a way to avoid the "casting" from 2D-array to 1D-array for 1-row 2D-arrays?


问:
sqlite3.OperationalError. SQLite thinks there is a ? mark but there is not
I am trying to insert a Python dictionary into an SQLite3 database to store financial data from my brokerage. I want to learn Python and SQL to do this.

The dictionary I am trying to insert is:

```<code>data = {u'symbols': [{u'optionType': None, u'dividendDate': u'2017-12-15T00:00:00.000000-05:00', u'eps': 1.564, u'currency': u'CAD', u'prevDayClosePrice': 53.01, u'averageVol3Months': 641554, u'industrySubgroup': u'Gold', u'isTradable': True, u'hasOptions': True, u'optionDurationType': None, u'optionExpiryDate': None, u'symbolId': 6849, u'outstandingShares': 232319000, u'tradeUnit': 1, u'optionStrikePrice': None, u'pe': 33.9, u'lowPrice52': 46.91, u'industrySector': u'BasicMaterials', u'optionRoot': u'', u'description': u'AGNICO-EAGLE MINES', u'symbol': u'AEM.TO', u'securityType': u'Stock', u'dividend': 0.11, u'minTicks': [{u'pivot': 0, u'minTick': 0.005}, {u'pivot': 0.5, u'minTick': 0.01}], u'averageVol20Days': 635497, u'industryGroup': u'MetalsMining', u'optionContractDeliverables': {u'cashInLieu': 0, u'underlyings': []}, u'highPrice52': 68.76, u'yield': 1.06, u'listingExchange': u'TSX', u'isQuotable': True, u'optionExerciseType': None, u'marketCap': 12315230190, u'exDate': u'2017-11-30T00:00:00.000000-05:00'}]}
</code>```

The code looks like:

```<code>data = data['symbols'][0]
        try:
            conn = sqlite3.connect('sql/investment_databse.db')
            c = conn.cursor()
            with conn:
                c.execute('''INSERT INTO daily_sec_data(optionType, dividendDate, eps, currency, prevDayClosePrice,
                         averageVol3Months, industrySubgroup, isTradable, hasOptions, optionDurationType,
                         optionExpiryDate, symbolId, outstandingShares, tradeUnit, optionStrikePrice,
                         pe, lowPrice52, industrySector, optionRoot, description,
                         symbol, securityType, dividend, minTicks, averageVol20Days,
                         industryGroup, optionContractDeliverables, highPrice52, yield, listingExchange,
                         isQuotable, optionExerciseType, marketCap, exDate)
                         VALUES(?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?)''',(data['optionType'], data['dividendDate'], data['eps'], data['currency'], data['prevDayClosePrice'],
                                data['averageVol3Months'], data['industrySubgroup'], data['isTradable'], data['hasOptions'], data['optionDurationType'],
                                data['optionExpiryDate'], data['symbolId'], data['outstandingShares'], data['tradeUnit'], data['optionStrikePrice'],
                                data['pe'], data['lowPrice52'], data['industrySector'], data['optionRoot'], data['description'],
                                data['symbol'], data['securityType'], data['dividend'], data['minTicks'], data['averageVol20Days'],
                                data['industryGroup'], data['optionContractDeliverables'], data['highPrice52'], data['yield'], data['listingExchange'],
                                data['isQuotable'], data['optionExerciseType'], data['marketCap'], data['exDate']))
                conn.commit()
</code>```

I get the following error:

```<code>File "/Users/michael/GoogleDrive/atomProjects/questrade/def_securities.py", line 114, in get_ftse_can_data
    data['isQuotable'], data['optionExerciseType'], data['marketCap'], data['exDate']))
sqlite3.InterfaceError: Error binding parameter 23 - probably unsupported type.
</code>```

Line 114 is the second-to-last line of the above code.

答:
```<code>'minTicks': [{'pivot': 0, 'minTick': 0.005}, {'pivot': 0.5, 'minTick': 0.01}]
</code>```

This is an array (containing two dictionaries). It cannot be stored in one of the storage types.

If minTicks always has four values, you could extract them and store them in four columns. But to store an array of arbitrary size, you would need a separate table with an 1:N relationship to the main table.

Body:
I am trying to insert a Python dictionary into an SQLite3 database to store financial data from my brokerage. I want to learn Python and SQL to do this.

The dictionary I am trying to insert is:

data = {u'symbols': [{u'optionType': None, u'dividendDate': u'2017-12-15T00:00:00.000000-05:00', u'eps': 1.564, u'currency': u'CAD', u'prevDayClosePrice': 53.01, u'averageVol3Months': 641554, u'industrySubgroup': u'Gold', u'isTradable': True, u'hasOptions': True, u'optionDurationType': None, u'optionExpiryDate': None, u'symbolId': 6849, u'outstandingShares': 232319000, u'tradeUnit': 1, u'optionStrikePrice': None, u'pe': 33.9, u'lowPrice52': 46.91, u'industrySector': u'BasicMaterials', u'optionRoot': u'', u'description': u'AGNICO-EAGLE MINES', u'symbol': u'AEM.TO', u'securityType': u'Stock', u'dividend': 0.11, u'minTicks': [{u'pivot': 0, u'minTick': 0.005}, {u'pivot': 0.5, u'minTick': 0.01}], u'averageVol20Days': 635497, u'industryGroup': u'MetalsMining', u'optionContractDeliverables': {u'cashInLieu': 0, u'underlyings': []}, u'highPrice52': 68.76, u'yield': 1.06, u'listingExchange': u'TSX', u'isQuotable': True, u'optionExerciseType': None, u'marketCap': 12315230190, u'exDate': u'2017-11-30T00:00:00.000000-05:00'}]}

The code looks like:

data = data['symbols'][0]
        try:
            conn = sqlite3.connect('sql/investment_databse.db')
            c = conn.cursor()
            with conn:
                c.execute('''INSERT INTO daily_sec_data(optionType, dividendDate, eps, currency, prevDayClosePrice,
                         averageVol3Months, industrySubgroup, isTradable, hasOptions, optionDurationType,
                         optionExpiryDate, symbolId, outstandingShares, tradeUnit, optionStrikePrice,
                         pe, lowPrice52, industrySector, optionRoot, description,
                         symbol, securityType, dividend, minTicks, averageVol20Days,
                         industryGroup, optionContractDeliverables, highPrice52, yield, listingExchange,
                         isQuotable, optionExerciseType, marketCap, exDate)
                         VALUES(?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?)''',(data['optionType'], data['dividendDate'], data['eps'], data['currency'], data['prevDayClosePrice'],
                                data['averageVol3Months'], data['industrySubgroup'], data['isTradable'], data['hasOptions'], data['optionDurationType'],
                                data['optionExpiryDate'], data['symbolId'], data['outstandingShares'], data['tradeUnit'], data['optionStrikePrice'],
                                data['pe'], data['lowPrice52'], data['industrySector'], data['optionRoot'], data['description'],
                                data['symbol'], data['securityType'], data['dividend'], data['minTicks'], data['averageVol20Days'],
                                data['industryGroup'], data['optionContractDeliverables'], data['highPrice52'], data['yield'], data['listingExchange'],
                                data['isQuotable'], data['optionExerciseType'], data['marketCap'], data['exDate']))
                conn.commit()

I get the following error:

File "/Users/michael/GoogleDrive/atomProjects/questrade/def_securities.py", line 114, in get_ftse_can_data
    data['isQuotable'], data['optionExerciseType'], data['marketCap'], data['exDate']))
sqlite3.InterfaceError: Error binding parameter 23 - probably unsupported type.

Line 114 is the second-to-last line of the above code.

Body:
'minTicks': [{'pivot': 0, 'minTick': 0.005}, {'pivot': 0.5, 'minTick': 0.01}]

This is an array (containing two dictionaries). It cannot be stored in one of the storage types.

If minTicks always has four values, you could extract them and store them in four columns. But to store an array of arbitrary size, you would need a separate table with an 1:N relationship to the main table.


问:
Child theme is not getting parent theme's jQuery code in wordpress.
Hey I have created tabbed menu in my wordpress blog. I have done it in parent theme. Now I have created a child theme of that parent theme. Everything seems fine expect tabbed menu. I have used jQuery for tabbed menu.
Here is my function.php file's specific part to include jQuery and css code from parent theme.

```<code>// enqueue tabs script
function my_scripts_tabs() {
if ( !is_admin() ) {
wp_enqueue_script('jquery-ui-tabs');
wp_enqueue_script( 'custom-tabs', get_stylesheet_directory_uri() .
'/js/tabs.js', array('jquery'));
}
}
add_action('wp_enqueue_scripts', 'my_scripts_tabs');

//add tabs stylesheet
wp_register_style('jquery-custom-style',
get_stylesheet_directory_uri().'/css/jquery-ui-1.12.1.custom/jquery-ui.css',
array(), '1', 'screen');
wp_enqueue_style('jquery-custom-style');
</code>```

Here is my function.php file for child theme.

```<code><?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
// BEGIN ENQUEUE PARENT ACTION
// AUTO GENERATED - Do not modify or remove comment markers above or below:

if ( !function_exists( 'chld_thm_cfg_parent_css' ) ):
function chld_thm_cfg_parent_css() {
    wp_enqueue_style( 'chld_thm_cfg_parent', trailingslashit(
get_template_directory_uri() ) . 'style.css', array( 'genericons' ) );
}
endif;
add_action( 'wp_enqueue_scripts', 'chld_thm_cfg_parent_css', 10 );

// END ENQUEUE PARENT ACTION
</code>```

Anyone please help. TIA

答:
You need to edit

```<code>get_stylesheet_directory_uri().'/css/jquery-ui-1.12.1.custom/jquery-ui.css'
</code>```

to

```<code>get_template_directory_uri().'/css/jquery-ui-1.12.1.custom/jquery-ui.css'
</code>```

at parent theme.
Because when it is run by child theme get_stylesheet_directory_uri() returns child theme path, although the code is in parent theme.

Body:
Hey I have created tabbed menu in my wordpress blog. I have done it in parent theme. Now I have created a child theme of that parent theme. Everything seems fine expect tabbed menu. I have used jQuery for tabbed menu.
Here is my function.php file's specific part to include jQuery and css code from parent theme.

// enqueue tabs script
function my_scripts_tabs() {
if ( !is_admin() ) {
wp_enqueue_script('jquery-ui-tabs');
wp_enqueue_script( 'custom-tabs', get_stylesheet_directory_uri() .
'/js/tabs.js', array('jquery'));
}
}
add_action('wp_enqueue_scripts', 'my_scripts_tabs');

//add tabs stylesheet
wp_register_style('jquery-custom-style',
get_stylesheet_directory_uri().'/css/jquery-ui-1.12.1.custom/jquery-ui.css',
array(), '1', 'screen');
wp_enqueue_style('jquery-custom-style');

Here is my function.php file for child theme.

<?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
// BEGIN ENQUEUE PARENT ACTION
// AUTO GENERATED - Do not modify or remove comment markers above or below:

if ( !function_exists( 'chld_thm_cfg_parent_css' ) ):
function chld_thm_cfg_parent_css() {
    wp_enqueue_style( 'chld_thm_cfg_parent', trailingslashit(
get_template_directory_uri() ) . 'style.css', array( 'genericons' ) );
}
endif;
add_action( 'wp_enqueue_scripts', 'chld_thm_cfg_parent_css', 10 );

// END ENQUEUE PARENT ACTION

Anyone please help. TIA

Body:
You need to edit

get_stylesheet_directory_uri().'/css/jquery-ui-1.12.1.custom/jquery-ui.css'

to

get_template_directory_uri().'/css/jquery-ui-1.12.1.custom/jquery-ui.css'

at parent theme.
Because when it is run by child theme get_stylesheet_directory_uri() returns child theme path, although the code is in parent theme.


问:
Hide specific part of passed parameters in URL
I am passing multiple parameters in select form with GET method. I want to hide 3 from 4 parameters in URL after form submit. I have an options with 4 values and the I explode them and get each like that:

```<code><select name="hardware">
<option value="Bitmain AntMiner S9|1-btc-sha-256|14000|1375">BITMAIN AntMiner S9</option>
<option value="Bitmain AntMiner D3|34-dash-x11|15000|1200">BITMAIN AntMiner D3</option>
</select>

<?php
$hardware = $_GET["hardware"];
$hardware_explode = explode('|', $hardware);
echo $hardware_explode[0];
echo $hardware_explode[1];
echo $hardware_explode[2];
echo $hardware_explode[3];
?>
</code>```

in URL it is like that: example.com/calculate.php?hardware=Bitmain+AntMiner+S9%7C1-btc-sha-256%7C13000%7C1375

and I want it to be example.com/calculate.php?hardware=Bitmain+AntMiner+S9

How can I hide this last 3 parameters in JS or PHP?

答:
If you don't want them to be submitted, don't put them in the form in the first place.</p>

```<code><option value="Bitmain AntMiner S9">
</code>```

Body:
I am passing multiple parameters in select form with GET method. I want to hide 3 from 4 parameters in URL after form submit. I have an options with 4 values and the I explode them and get each like that:

<select name="hardware">
<option value="Bitmain AntMiner S9|1-btc-sha-256|14000|1375">BITMAIN AntMiner S9</option>
<option value="Bitmain AntMiner D3|34-dash-x11|15000|1200">BITMAIN AntMiner D3</option>
</select>

<?php
$hardware = $_GET["hardware"];
$hardware_explode = explode('|', $hardware);
echo $hardware_explode[0];
echo $hardware_explode[1];
echo $hardware_explode[2];
echo $hardware_explode[3];
?>

in URL it is like that: example.com/calculate.php?hardware=Bitmain+AntMiner+S9%7C1-btc-sha-256%7C13000%7C1375

and I want it to be example.com/calculate.php?hardware=Bitmain+AntMiner+S9

How can I hide this last 3 parameters in JS or PHP?

Body:
If you don't want them to be submitted, don't put them in the form in the first place.

<option value="Bitmain AntMiner S9">


问:
Setting up a display environment variable for a remote unix system
Trying to get some graphical network simulator (ns2) code to display from my university's unix system. My local OS is Ubuntu 10 and I am accessing the unix system through PuTTY SSH client. When some prewritten code is executed, the following error prompt occurs:

```<code>no display name and no $DISPLAY environment variable</code>```

What can be done to get remotely executed code to display on my system? I am a total novice with unix and my attempts at redefining the $DISPLAY env var were spectacular failures. Thanks. Appreciated.

答:
Just do:

```<code>$ ssh -X username@cornell.unix.edu
</code>```

This should launch ssh with X forwarding enabled, when run from a terminal emulator like Xterm, gnome-terminal and the like. username should be your account name on the remote computer, of course.

Body:
Trying to get some graphical network simulator (ns2) code to display from my university's unix system. My local OS is Ubuntu 10 and I am accessing the unix system through PuTTY SSH client. When some prewritten code is executed, the following error prompt occurs:

no display name and no $DISPLAY environment variable

What can be done to get remotely executed code to display on my system? I am a total novice with unix and my attempts at redefining the $DISPLAY env var were spectacular failures. Thanks. Appreciated.

Body:
Just do:

$ ssh -X username@cornell.unix.edu

This should launch ssh with X forwarding enabled, when run from a terminal emulator like Xterm, gnome-terminal and the like. username should be your account name on the remote computer, of course.


问:
Multiple short tasks
What is the best approach to handle multiple short-time tasks?

I have a case where I need to work off a lot of short-time/cheap Actions. The number can vary from let's say 8 to 100 and the time each action needs is between 0.00x ms and 1 ms. Because it's for UI the work should done in 60fps. But I will also run the code on Xamarin and low-end mobiles, so that goal cannot be reached always, that's why I'm using Tasks.
Actually I'm using a custom TaskScheduler from here.

Now, the question is, how to handle all these actions:

How expensive is Task.Run/Task.Factory.StartNew?

Would it be better to collect the multiple actions in a ConcurrentQueue and starting just max. 4 tasks (on a 4 core CPU) that will work off all the actions in while loop until queue is empty?

Are multiple tasks managed by TaskScheduler much more expensive than multiple actions in a single (or some few) task(s)?

I would like to take advantage of the existing async/await TPL structure, but is it also good for many and very small/short/cheap Actions?

答:
Best approach would be to use Parallel.Invoke().  This has lower overhead than creating Tasks.  It will also automatically determine how many actions to run simultaneously, depending on the current hardware.

See the documentation for more details.

I have tried this with thousands of Tasks and Parallel.Invoke is faster.

Title: Multiple short tasks


问:
Need to match mid part of id using JQuery
I want to match mid part of id
my code is

```<code><asp:Label runat="server" ID="lbl_OrderDate_DateTime_M"  Text="Order Date:">
</asp:Label>
</code>```

I need to match _DateTime from ID how can I do this using jQuery?

答:
You can use the attribute contains selector to select based on a substring of an attribute:

```<code>$("[id*='_DateTime']")
</code>```

It's of course worth noting that what you're showing is a server-side ASP.NET control, not an HTML element.  You'll want to double-check the actual HTML that you're trying to operate on with JavaScript to make sure it's what you expect it to be.

Body:
I want to match mid part of id
my code is

<asp:Label runat="server" ID="lbl_OrderDate_DateTime_M"  Text="Order Date:">
</asp:Label>

I need to match _DateTime from ID how can I do this using jQuery?

Body:
You can use the attribute contains selector to select based on a substring of an attribute:

$("[id*='_DateTime']")

It's of course worth noting that what you're showing is a server-side ASP.NET control, not an HTML element.  You'll want to double-check the actual HTML that you're trying to operate on with JavaScript to make sure it's what you expect it to be.


问:
Volatile or synchronized for primitive type?
In Java, assignment is atomic if the size of the variable is less than or equal to 32 bits but is not if more than 32 bits.

What (volatile/synchronized) would be more efficient to use in case of double or long assignment?

Like,

```<code>  volatile double x = y;
</code>```

synchronized is not applicable with primitive argument. How do I use synchronized in this case? Of course I don't want to lock my class, so this should not be used.

答:
According to the oracle documentation, you can use volatile to refer to Double object:

```<code>volatile Double x = y;
</code>```

"Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values."

Body:
In Java, assignment is atomic if the size of the variable is less than or equal to 32 bits but is not if more than 32 bits.

What (volatile/synchronized) would be more efficient to use in case of double or long assignment?

Like,

  volatile double x = y;

synchronized is not applicable with primitive argument. How do I use synchronized in this case? Of course I don't want to lock my class, so this should not be used.

Body:
According to the oracle documentation, you can use volatile to refer to Double object:

volatile Double x = y;

"Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values."


问:
Django / Cassandra: can not createsuperuser
I am running Debian server with Django and Cassandra. I am not able to create the admin user via command:

```<code>python manage.py createsuperuser
</code>```

Running the command causes an error:

```<code>cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:260 no viable           alternative at input '.' (...auth_user.date_joined FROM auth_user WHERE [auth_user]....)">
</code>```

The synchronization works fine - the keyspace and tables were created according to model.

Question

How can I get rid of this error and make the command work?

Version information

Debian GNU/Linux 8.6 (jessie)

Python 2.7.9

Django 1.10.5

Cassandra 3.0.9

Django: settings.py

```<code># Application definition

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django_cassandra_engine',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django_cassandra_engine',
        'NAME': 'mydb',
        'TEST_NAME': 'test_db',
        'HOST': 'xx.xx.xx.xx',
        'OPTIONS': {
            'replication': {
                'strategy_class': 'SimpleStrategy',
                'replication_factor': 1
            }
        }
    }
}
</code>```

Full traceback

```<code>Not checking migrations as it is not possible to access/create the django_migrations table.
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 96, in handle
    default_username = get_default_username()
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/__init__.py", line 148, in get_default_username
    auth_app.User._default_manager.get(username=default_username)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 379, in get
    num = len(clone)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 238, in __len__
    self._fetch_all()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 54, in __iter__
    results = compiler.execute_sql()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django_cassandra_engine/utils.py", line 47, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django_cassandra_engine/connection.py", line 13, in execute
    return self.connection.execute(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django_cassandra_engine/connection.py", line 88, in execute
    return self.session.execute(qs, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 1998, in execute
    return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 3781, in result
    raise self._final_exception
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:260 no viable           alternative at input '.' (...auth_user.date_joined FROM auth_user WHERE [auth_user]....)">
</code>```

答:
We can not use:

```<code>python manage.py createsuperuser using cassandra
</code>```

It does not work with the default django model.

You need to use an external library for the same.

Please read document on data-stax or at this link:
https://pypi.python.org/pypi/django-cassandra-engine/

Body:
I am running Debian server with Django and Cassandra. I am not able to create the admin user via command:

python manage.py createsuperuser

Running the command causes an error:

cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:260 no viable           alternative at input '.' (...auth_user.date_joined FROM auth_user WHERE [auth_user]....)">

The synchronization works fine - the keyspace and tables were created according to model.

Question

How can I get rid of this error and make the command work?

Version information

Debian GNU/Linux 8.6 (jessie)

Python 2.7.9

Django 1.10.5

Cassandra 3.0.9

Django: settings.py

# Application definition

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django_cassandra_engine',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django_cassandra_engine',
        'NAME': 'mydb',
        'TEST_NAME': 'test_db',
        'HOST': 'xx.xx.xx.xx',
        'OPTIONS': {
            'replication': {
                'strategy_class': 'SimpleStrategy',
                'replication_factor': 1
            }
        }
    }
}

Full traceback

Not checking migrations as it is not possible to access/create the django_migrations table.
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 96, in handle
    default_username = get_default_username()
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/__init__.py", line 148, in get_default_username
    auth_app.User._default_manager.get(username=default_username)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 379, in get
    num = len(clone)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 238, in __len__
    self._fetch_all()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 54, in __iter__
    results = compiler.execute_sql()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django_cassandra_engine/utils.py", line 47, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django_cassandra_engine/connection.py", line 13, in execute
    return self.connection.execute(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django_cassandra_engine/connection.py", line 88, in execute
    return self.session.execute(qs, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 1998, in execute
    return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
  File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 3781, in result
    raise self._final_exception
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:260 no viable           alternative at input '.' (...auth_user.date_joined FROM auth_user WHERE [auth_user]....)">

Body:
We can not use:

python manage.py createsuperuser using cassandra

It does not work with the default django model.

You need to use an external library for the same.

Please read document on data-stax or at this link:
https://pypi.python.org/pypi/django-cassandra-engine/


问:
UIImagePickerController in an existing UIPopoverController
Is there a way to push the UIImagePickerController in an existing UIPopoverController's navigation controller?

What I know is that you have to create a new popover and add the UIImagePickerController in it. But I have an existing popover with its navigation controller that should present the image picker.

答: Use setContentViewController:animated: on UIPopoverController


问:
(Oracle) SQL: Column must contain a list of values
I'm trying to figure out an efficient (Oracle) SQL statement that verifies whether a column contains a specific list of values at least once.

One option would be to filter for that list, output all distinct values and then count them. So, something like this:

```<code>SELECT count(*)
FROM (
      SELECT DISTINCT columnname
      FROM table
      WHERE columnname in ('a', 'b', 'c')
     )
;
</code>```

(And then check whether count(*) returns the number 3)

The problem with this is that the DISTINCT statement looks at the whole table, which is very bad performance-wise. All three values of my list could be at the very beginning, so i don't need to look at the millions of other rows. I only want to know that the column contains 'a', 'b' and 'c'.

Does anyone has an idea to solve this efficiently?

Thanks in advance!

答:
If you wish to get rid of distinct, then try the below, Group by has better performance than distinct, See here.

```<code>SELECT count(*)
FROM (
      SELECT columnname
      FROM table
      WHERE columnname in ('a', 'b', 'c')
      GROUP BY columnname
     )
;
</code>```

Or you can avoid the usage of subquery by

```<code>SELECT count(DISTINCT columnname)
      FROM table
      WHERE columnname in ('a', 'b', 'c');
</code>```

Body:
I'm trying to figure out an efficient (Oracle) SQL statement that verifies whether a column contains a specific list of values at least once.

One option would be to filter for that list, output all distinct values and then count them. So, something like this:

SELECT count(*)
FROM (
      SELECT DISTINCT columnname
      FROM table
      WHERE columnname in ('a', 'b', 'c')
     )
;

(And then check whether count(*) returns the number 3)

The problem with this is that the DISTINCT statement looks at the whole table, which is very bad performance-wise. All three values of my list could be at the very beginning, so i don't need to look at the millions of other rows. I only want to know that the column contains 'a', 'b' and 'c'.

Does anyone has an idea to solve this efficiently?

Thanks in advance!

Body:
If you wish to get rid of distinct, then try the below, Group by has better performance than distinct, See here.

SELECT count(*)
FROM (
      SELECT columnname
      FROM table
      WHERE columnname in ('a', 'b', 'c')
      GROUP BY columnname
     )
;

Or you can avoid the usage of subquery by

SELECT count(DISTINCT columnname)
      FROM table
      WHERE columnname in ('a', 'b', 'c');


问:
Reading XML file via VBA
I am trying to read a XML file (this is not in a correct format). Below is the actual XML file that I have.

<?xml version="1.0" encoding="UTF-8"?><Report time="8/18/2017 12:54:42">
TABLE
<Application>Fruits</Application><Environment>AMAZON</Environment><Group>FOREST</Group><SubGroup>RAINFOREST</SubGroup><Row>3</Row><Release>SEPT</Release><Result>Pass</Result><Testname>HEALTHCHECK</Testname><Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath></Report>
```

<p>Now I am trying to read this and save the XML format, but unable to get any further.</p>

<p>Format that I want and save it:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Report time="8/18/2017 12:54:42">
<Table>TABLE</Table>
<Application>Fruits</Application>
<Environment>AMAZON</Environment>
<Group>FOREST</Group>
<SubGroup>RAINFOREST</SubGroup>
<Row>3</Row>
<Release>SEPT</Release>
<Result>Pass</Result>
<Testname>HEALTHCHECK</Testname>
<Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath>
</Report>
</code>```

I am able to check the format but not able to save it. Below is the code that I have tried.

```<code>Public Sub Create_Report()
myFile = "C:\Prac_Session\OLB.xml"
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(myFile, ForReading, False)
Do While Not txtStream.AtEndOfStream
    Debug.Print txtStream.ReadLine
    Tempstr = ">" & vbNewLine & "<"
    a = Replace(txtStream.ReadLine, "><", Tempstr)
    Debug.Print a
    ''Now to save.??''
Loop
txtStream.Close

End Sub
</code>```

答:
I believe this would do it:</p>

```<code>Sub foo()
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Prac_Session\OLB.xml" 'change the path to whatever yours ought to be
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)

strContents = objTS.ReadAll 'would use read all to read the whole file into memory

'Do While Not objTS.AtEndOfStream
'    strContents = strContents & " " & objTS.ReadLine 'Read line by line and store all lines in strContents
'Loop
Tempstr = ">" & vbCrLf & "<" 'instead of vbNewLine
strContents = Replace(strContents, "><", Tempstr)
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
End Sub
</code>```

Title: Reading XML file via VBA

Body:
I am trying to read a XML file (this is not in a correct format). Below is the actual XML file that I have.

<?xml version="1.0" encoding="UTF-8"?><Report time="8/18/2017 12:54:42">
TABLE
<Application>Fruits</Application><Environment>AMAZON</Environment><Group>FOREST</Group><SubGroup>RAINFOREST</SubGroup><Row>3</Row><Release>SEPT</Release><Result>Pass</Result><Testname>HEALTHCHECK</Testname><Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath></Report>

Now I am trying to read this and save the XML format, but unable to get any further.

Format that I want and save it:

<?xml version="1.0" encoding="UTF-8"?>
<Report time="8/18/2017 12:54:42">

TABLE

<Application>Fruits</Application>
<Environment>AMAZON</Environment>
<Group>FOREST</Group>
<SubGroup>RAINFOREST</SubGroup>
<Row>3</Row>
<Release>SEPT</Release>
<Result>Pass</Result>
<Testname>HEALTHCHECK</Testname>
<Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath>
</Report>

I am able to check the format but not able to save it. Below is the code that I have tried.

Public Sub Create_Report()
myFile = "C:\Prac_Session\OLB.xml"
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(myFile, ForReading, False)
Do While Not txtStream.AtEndOfStream
    Debug.Print txtStream.ReadLine
    Tempstr = ">" & vbNewLine & "<"
    a = Replace(txtStream.ReadLine, "><", Tempstr)
    Debug.Print a
    ''Now to save.??''
Loop
txtStream.Close

End Sub

Body:
I believe this would do it:

Sub foo()
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Prac_Session\OLB.xml" 'change the path to whatever yours ought to be
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)

strContents = objTS.ReadAll 'would use read all to read the whole file into memory

'Do While Not objTS.AtEndOfStream
'    strContents = strContents & " " & objTS.ReadLine 'Read line by line and store all lines in strContents
'Loop
Tempstr = ">" & vbCrLf & "<" 'instead of vbNewLine
strContents = Replace(strContents, "><", Tempstr)
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
End Sub


问:
Single line break in body of powershell MailMessage not working
For some reason when attempting to populate the body of an email in powershell, a single line break using the `n escape sequence is not working, however a double is.

This is my code...

```<code>param([string]$BuildId, [string]$BuildName)

$EmailTo = "[email]"
$EmailFrom = "sepaautomation@gmail.com"
$Subject = "$BuildName $BuildId SpecFlow Reports"
$Body = "The following SpecFlow reports are attached: `n`n"
$SMTPServer = "smtp.sendgrid.net"

$date = Get-Date -Format yyyy-MM-dd

$files = Get-ChildItem "C:\Build\SA.SEPA.Web.UI.Selenium" -Recurse | Where-Object { $_.Name -match "^.*$date.*\.html$" } | % { $_.FullName }

foreach($item in $files)
{
    $Body += "$item `n"
}

$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)

foreach($item in $files)
{
    $attachment = New-Object System.Net.Mail.Attachment($item)
    $SMTPMessage.Attachments.Add($attachment)
}

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("apikey", "[apiKey]");
$SMTPClient.Send($SMTPMessage)
</code>```

This is the section that is failing to add a line break

```<code>foreach($item in $files)
{
    $Body += "$item `n"
}
</code>```

My email in outlook looks like the following....

You can see that the `n `n double line break has been applied but not the `n. Incidentally if I change to...

```<code>foreach($item in $files)
{
    $Body += "$item `n`n"
}
</code>```

I do see a double line break.

How do I get just a single line break?

答:
Just go with [Environment]::NewLine to resolve this one. It will take away most headaches relating to this issue.

Usage:

```<code>foreach($item in $files)
{
    $Body += "$item " + [Environment]::NewLine
}
</code>```

Body:
For some reason when attempting to populate the body of an email in powershell, a single line break using the `n escape sequence is not working, however a double is.

This is my code...

param([string]$BuildId, [string]$BuildName)

$EmailTo = "[email]"
$EmailFrom = "sepaautomation@gmail.com"
$Subject = "$BuildName $BuildId SpecFlow Reports"
$Body = "The following SpecFlow reports are attached: `n`n"
$SMTPServer = "smtp.sendgrid.net"

$date = Get-Date -Format yyyy-MM-dd

$files = Get-ChildItem "C:\Build\SA.SEPA.Web.UI.Selenium" -Recurse | Where-Object { $_.Name -match "^.*$date.*\.html$" } | % { $_.FullName }

foreach($item in $files)
{
    $Body += "$item `n"
}

$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)

foreach($item in $files)
{
    $attachment = New-Object System.Net.Mail.Attachment($item)
    $SMTPMessage.Attachments.Add($attachment)
}

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("apikey", "[apiKey]");
$SMTPClient.Send($SMTPMessage)

This is the section that is failing to add a line break

foreach($item in $files)
{
    $Body += "$item `n"
}

My email in outlook looks like the following....

You can see that the `n `n double line break has been applied but not the `n. Incidentally if I change to...

foreach($item in $files)
{
    $Body += "$item `n`n"
}

I do see a double line break.

How do I get just a single line break?

Body:
Just go with [Environment]::NewLine to resolve this one. It will take away most headaches relating to this issue.

Usage:

foreach($item in $files)
{
    $Body += "$item " + [Environment]::NewLine
}


问:
Webview showing blank screen when clicking a link within the webview
On Android 7.1.1 i have a page on my app that creates a webview and allows some navigation around my site. the first page loads fine, but when i click a link within the webview it shows a white blank page. this all works fine on previous versions of android.

I understand the changes google have made with the webview and chrome is updated and i have been through various resetting and installing of the new webview system app, so i am unsure if the problem is related. I am thinking its not otherwise the first page wouldnt load.

Here is my webview code

```<code> public class WebViewActivity extends Activity
{
Service details;
String URL;
WebView webView;
private DataManager mDataManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);
    Intent intent = this.getIntent();
    Bundle bundle = intent.getExtras();

    URL = (String)bundle.getString("url");
    webView = (WebView) findViewById(R.id.wv);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.setWebViewClient(new GeoWebViewClient());
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setGeolocationEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.setWebChromeClient(new GeoWebChromeClient());
    webView.clearCache(true);
    webView.loadUrl(URL);

    //webView.setWebViewClient(new Client());
    //webView.setWebChromeClient(new ChromeClient());
    if (Build.VERSION.SDK_INT >= 19) {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }
    else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

    /**
     * WebChromeClient subclass handles UI-related calls
     * Note: think chrome as in decoration, not the Chrome browser
     */
    public class GeoWebChromeClient extends WebChromeClient
    {
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback)
        {
            // Always grant permission since the app itself requires location
            // permission and the user has therefore already granted it
            callback.invoke(origin, true, false);
        }
    }

    public class GeoWebViewClient extends WebViewClient
    {

        @Override
        public void onPageFinished(WebView view, String url)
        {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

        }
        /*@deprecated
        public boolean shouldoverrideurlloading(webview view, string url) {
            return false;
        }*/

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
        {
            view.loadUrl(request.toString());
            return true;
        }
    }

}
</code>```

I think it may have something to do with shouldOverrideUrlLoading

答:
You need to set a WebClient to webView. If you want to open link in webview.
Then do like this.

```<code>webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return false;
}
});
</code>```

for Android N above Use Overridden method :

```<code> @TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

    return false;
}
</code>```

Body:
On Android 7.1.1 i have a page on my app that creates a webview and allows some navigation around my site. the first page loads fine, but when i click a link within the webview it shows a white blank page. this all works fine on previous versions of android.

I understand the changes google have made with the webview and chrome is updated and i have been through various resetting and installing of the new webview system app, so i am unsure if the problem is related. I am thinking its not otherwise the first page wouldnt load.

Here is my webview code

 public class WebViewActivity extends Activity
{
Service details;
String URL;
WebView webView;
private DataManager mDataManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);
    Intent intent = this.getIntent();
    Bundle bundle = intent.getExtras();

    URL = (String)bundle.getString("url");
    webView = (WebView) findViewById(R.id.wv);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.setWebViewClient(new GeoWebViewClient());
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setGeolocationEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.setWebChromeClient(new GeoWebChromeClient());
    webView.clearCache(true);
    webView.loadUrl(URL);

    //webView.setWebViewClient(new Client());
    //webView.setWebChromeClient(new ChromeClient());
    if (Build.VERSION.SDK_INT >= 19) {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }
    else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

    /**
     * WebChromeClient subclass handles UI-related calls
     * Note: think chrome as in decoration, not the Chrome browser
     */
    public class GeoWebChromeClient extends WebChromeClient
    {
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback)
        {
            // Always grant permission since the app itself requires location
            // permission and the user has therefore already granted it
            callback.invoke(origin, true, false);
        }
    }

    public class GeoWebViewClient extends WebViewClient
    {

        @Override
        public void onPageFinished(WebView view, String url)
        {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

        }
        /*@deprecated
        public boolean shouldoverrideurlloading(webview view, string url) {
            return false;
        }*/

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
        {
            view.loadUrl(request.toString());
            return true;
        }
    }

}

I think it may have something to do with shouldOverrideUrlLoading

Body:
You need to set a WebClient to webView. If you want to open link in webview.
Then do like this.

webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return false;
}
});

for Android N above Use Overridden method :

 @TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

    return false;
}


问:
Change default MSSQL datasource for connection string
When executing integration tests, I'm using a connection string to connect to the database. I know there is a default notation for connecting to the default server instance in a connection string:

data source=.;initial catalog=[database name];integrated security=SSPI;

Unfortunately the database is currently not installed on the default server and due to compatibility issues I am unable to change to the default server. Now for all my tests, I will have to assign the sever name like so:

data source=[My Server name] ;initial catalog=[database name];integrated security=SSPI;

Since the solution is shared, I can't check this configuration in, and I'll have to do a lot of manual maintenance for this.

Is there any way I can change the default SQL Server for my PC, so that I can use the connection string as shown in the first example?

EDIT:

I was able to successfully use the following connection string:

data source=.\SQLEXPRESS;initial catalog=[database name];integrated security=SSPI;

EDIT 2:

I was able to resolve my issue by this awnser

答:
To change the default server, do:</p>

```<code>sp_dropserver <old_name>;
GO
sp_addserver <new_name>, local;
GO
</code>```

Body:
To change the default server, do:

sp_dropserver <old_name>;
GO
sp_addserver <new_name>, local;
GO


问:
segmentaion fault (core dumped)
Hi I'm kind of new to C++ and i had to fill a code. The code should read as many values as given in the first input, afterwards it should compute the triple of the sum of these values.

I tried it like this:

```<code>#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2) {
        return 1;
    }
    int n = atoi(argv[1]);
    vector<double> x;
    for (int i = 0; i < n; i++)
        cin >> x[i];
    double v = 0;
    for (int i = 0; i < n; i++)
        v = 3 * x[i];
    cout << v << endl;
    return 0;
}
</code>```

Unfortunately I end up in a segmentation fault...
Here is the unfinished code

答:
Because in line vector <double> x;, you have created a vector with 0 size. So there is no space in vector x to hold elements.

To correct your code do either of the following:

Change line vector <double> x; to vector <double> x(n); OR

Change line for (int i =0; i <n ; i++) cin >> x[i] ; to double temp; for (int i =0; i <n ; i++) {cin >> temp; x.push_back(dummy);}

Title: segmentaion fault (core dumped)

Body:
Hi I'm kind of new to C++ and i had to fill a code. The code should read as many values as given in the first input, afterwards it should compute the triple of the sum of these values.

I tried it like this:

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2) {
        return 1;
    }
    int n = atoi(argv[1]);
    vector<double> x;
    for (int i = 0; i < n; i++)
        cin >> x[i];
    double v = 0;
    for (int i = 0; i < n; i++)
        v = 3 * x[i];
    cout << v << endl;
    return 0;
}

Unfortunately I end up in a segmentation fault...
Here is the unfinished code


问:
Why do try!() and ? not compile when used in a function that doesn't return Option or Result?
Why does this code not compile?

```<code>use std::{fs, path::Path};

fn main() {
    let dir = Path::new("../FileSystem");

    if !dir.is_dir() {
        println!("Is not a directory");
        return;
    }

    for item in try!(fs::read_dir(dir)) {
        let file = match item {
            Err(e) => {
                println!("Error: {}", e);
                return;
            }
            Ok(f) => f,
        };

        println!("");
    }

    println!("Done");
}
</code>```

This is the error I get

error[E0308]: mismatched types
  --> src/main.rs:11:17
   |
11 |     for item in try!(fs::read_dir(dir)) {
   |                 ^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
   |
   = note: expected type `()`
              found type `std::result::Result<_, _>`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
```

<p>I also tried the question mark operator:</p>

```for item in fs::read_dir(dir)? {
```

<p>Which had a different error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:11:17
   |
11 |     for item in fs::read_dir(dir)? {
   |                 ^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`
</code>```

Previous versions of Rust had a similar error about std::ops::Carrier

Should I avoid try!() and ?? What is the best way to handle errors? Mostly I do it like this:

```<code>match error_prone {
    Err(e) => {
        println!("Error: {}", e);
        return;
    },
    Ok(f) => f,
};
</code>```

But if I have to use that in a for loop, it's a complete mess

```<code>for i in match error_prone {
    // match code
} {
    // loop code
}
</code>```

答:
Veedrac's answer helped me too, although the OP's question is slightly different. While reading the Rust documentation, I saw this snippet:

```<code>use std::fs::File;
use std::io::prelude::*;

let mut file = File::open("foo.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
assert_eq!(contents, "Hello, world!");
</code>```

Though in the Rust Book they point out the centrality of the main function, if you run this inside it you'll get a similar error. If you wrap the code inside a function handling the errors the aforementioned snippet works:

```<code>use std::error::Error;
use std::io::prelude::*;
use std::fs::File;

fn print_file_content() -> Result<String, Box<Error>> {
    let mut f = File::open("foo.txt")?;
    let mut contents = String::new();

    f.read_to_string(&mut contents)?;

    println!("The content: {:?}", contents);

    Ok("Done".into())
}

fn main() {
    match print_file_content() {
        Ok(s) => println!("{}", s),
        Err(e) => println!("Error: {}", e.to_string()),
    }
}
</code>```

P.S. I'm learning Rust so these snippets are not intended as good Rust coding :)

ContentLicense: CC BY-SA 4.0

Body:
Why does this code not compile?

use std::{fs, path::Path};

fn main() {
    let dir = Path::new("../FileSystem");

    if !dir.is_dir() {
        println!("Is not a directory");
        return;
    }

    for item in try!(fs::read_dir(dir)) {
        let file = match item {
            Err(e) => {
                println!("Error: {}", e);
                return;
            }
            Ok(f) => f,
        };

        println!("");
    }

    println!("Done");
}

This is the error I get

error[E0308]: mismatched types
  --> src/main.rs:11:17
   |
11 |     for item in try!(fs::read_dir(dir)) {
   |                 ^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
   |
   = note: expected type `()`
              found type `std::result::Result<_, _>`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

I also tried the question mark operator:

for item in fs::read_dir(dir)? {

Which had a different error:

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/main.rs:11:17
   |
11 |     for item in fs::read_dir(dir)? {
   |                 ^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
   |
   = help: the trait `std::ops::Try` is not implemented for `()`
   = note: required by `std::ops::Try::from_error`

Previous versions of Rust had a similar error about std::ops::Carrier

Should I avoid try!() and ?? What is the best way to handle errors? Mostly I do it like this:

match error_prone {
    Err(e) => {
        println!("Error: {}", e);
        return;
    },
    Ok(f) => f,
};

But if I have to use that in a for loop, it's a complete mess

for i in match error_prone {
    // match code
} {
    // loop code
}

Body:
Veedrac's answer helped me too, although the OP's question is slightly different. While reading the Rust documentation, I saw this snippet:

use std::fs::File;
use std::io::prelude::*;

let mut file = File::open("foo.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
assert_eq!(contents, "Hello, world!");

Though in the Rust Book they point out the centrality of the main function, if you run this inside it you'll get a similar error. If you wrap the code inside a function handling the errors the aforementioned snippet works:

use std::error::Error;
use std::io::prelude::*;
use std::fs::File;

fn print_file_content() -> Result<String, Box<Error>> {
    let mut f = File::open("foo.txt")?;
    let mut contents = String::new();

    f.read_to_string(&mut contents)?;

    println!("The content: {:?}", contents);

    Ok("Done".into())
}

fn main() {
    match print_file_content() {
        Ok(s) => println!("{}", s),
        Err(e) => println!("Error: {}", e.to_string()),
    }
}

P.S. I'm learning Rust so these snippets are not intended as good Rust coding :)


问:
coredata - move to app group target
I am new to the Today extension and using an embedded framework.

Our app currently uses core data backed by sqlite.  If I want to share this between the app and the today extension, should I move this to a framework to be shared by both?

How can I migrate our current version in the app store to be able to upgrade to a new structure?

答:
For Migration in swift 3.0 and above just replace below persistentStoreCoordinator method with yours</p>

```<code>lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {

    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let options = [
        NSMigratePersistentStoresAutomaticallyOption: true,
        NSInferMappingModelAutomaticallyOption: true
    ]

    let oldStoreUrl = self.applicationDocumentsDirectory.appendingPathComponent("TaskTowerStorage.sqlite")
    let directory: NSURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppGroupID)! as NSURL
    let newStoreUrl = directory.appendingPathComponent("YourDatabaseName.sqlite")!

    var targetUrl : URL? = nil
    var needMigrate = false
    var needDeleteOld = false

    if FileManager.default.fileExists(atPath: oldStoreUrl.path){
        needMigrate = true
        targetUrl = oldStoreUrl
    }
    if FileManager.default.fileExists(atPath: newStoreUrl.path){
        needMigrate = false
        targetUrl = newStoreUrl

        if FileManager.default.fileExists(atPath: oldStoreUrl.path){
            needDeleteOld = true
        }
    }
    if targetUrl == nil {
        targetUrl = newStoreUrl
    }

    if needMigrate {
        do {
            try coordinator?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: targetUrl!, options: options)
            if let store = coordinator?.persistentStore(for: targetUrl!)
            {
                do {
                    try coordinator?.migratePersistentStore(store, to: newStoreUrl, options: options, withType: NSSQLiteStoreType)

                } catch let error {
                    print("migrate failed with error : \(error)")
                }
            }
        } catch let error {
            //CrashlyticsHelper.reportCrash(err: error as NSError, strMethodName: "migrateStore")
            print(error)
        }
    }

    if needDeleteOld {
        self.deleteDocumentAtUrl(url: oldStoreUrl)
        self.deleteDocumentAtUrl(url: self.applicationDocumentsDirectory.appendingPathComponent("YourDatabaseName.sqlite-shm"))
        self.deleteDocumentAtUrl(url: self.applicationDocumentsDirectory.appendingPathComponent("YourDatabaseName.sqlite-wal"))
    }

    do {
        try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: targetUrl, options: options)
    } catch var error as NSError {
        coordinator = nil
        NSLog("Unresolved error \(error), \(error.userInfo)")
        abort()
    } catch {
        fatalError()
    }
    return coordinator

}()
     lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named 'Bundle identifier' in the application's documents Application Support directory.
    let urls = Foundation.FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "StorageName", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
</code>```

Title: coredata - move to app group target

Body:
For Migration in swift 3.0 and above just replace below persistentStoreCoordinator method with yours

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {

    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let options = [
        NSMigratePersistentStoresAutomaticallyOption: true,
        NSInferMappingModelAutomaticallyOption: true
    ]

    let oldStoreUrl = self.applicationDocumentsDirectory.appendingPathComponent("TaskTowerStorage.sqlite")
    let directory: NSURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppGroupID)! as NSURL
    let newStoreUrl = directory.appendingPathComponent("YourDatabaseName.sqlite")!

    var targetUrl : URL? = nil
    var needMigrate = false
    var needDeleteOld = false

    if FileManager.default.fileExists(atPath: oldStoreUrl.path){
        needMigrate = true
        targetUrl = oldStoreUrl
    }
    if FileManager.default.fileExists(atPath: newStoreUrl.path){
        needMigrate = false
        targetUrl = newStoreUrl

        if FileManager.default.fileExists(atPath: oldStoreUrl.path){
            needDeleteOld = true
        }
    }
    if targetUrl == nil {
        targetUrl = newStoreUrl
    }

    if needMigrate {
        do {
            try coordinator?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: targetUrl!, options: options)
            if let store = coordinator?.persistentStore(for: targetUrl!)
            {
                do {
                    try coordinator?.migratePersistentStore(store, to: newStoreUrl, options: options, withType: NSSQLiteStoreType)

                } catch let error {
                    print("migrate failed with error : \(error)")
                }
            }
        } catch let error {
            //CrashlyticsHelper.reportCrash(err: error as NSError, strMethodName: "migrateStore")
            print(error)
        }
    }

    if needDeleteOld {
        self.deleteDocumentAtUrl(url: oldStoreUrl)
        self.deleteDocumentAtUrl(url: self.applicationDocumentsDirectory.appendingPathComponent("YourDatabaseName.sqlite-shm"))
        self.deleteDocumentAtUrl(url: self.applicationDocumentsDirectory.appendingPathComponent("YourDatabaseName.sqlite-wal"))
    }

    do {
        try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: targetUrl, options: options)
    } catch var error as NSError {
        coordinator = nil
        NSLog("Unresolved error \(error), \(error.userInfo)")
        abort()
    } catch {
        fatalError()
    }
    return coordinator

}()
     lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named 'Bundle identifier' in the application's documents Application Support directory.
    let urls = Foundation.FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "StorageName", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()