问:
Gurobi in Python: best way to read csv file
I'm learning how to solve combinatorial optimization problems in Gurobi using Python. I would like to know what is the best option to read a csv file to use the data as model parameters. I'm using 'genfromtxt' to read the csv file, but I'm having difficulties in using it for constraint construction (Gurobi doesn't support this type - see error).

Here my code and error message, my_data is composed by 4 columns: node index, x coordinate, y coordinate and maximum degree.

```<code>from gurobipy import *
from numpy import genfromtxt
import math

# Read data from csv file
my_data = genfromtxt('prob25.csv', delimiter=',')

# Number of vertices
n = len(my_data)

# Function to calculate euclidean distancces
dist = {(i,j) :
    math.sqrt(sum((my_data[i][k]-my_data[j][k])**2 for k in [1,2]))
    for i in range(n) for j in range(i)}

# Create a new model
m = Model("dcstNarula")

# Create variables

vars = m.addVars(dist.keys(), obj=dist, vtype=GRB.BINARY, name='e')
for i,j in vars.keys():
    vars[j,i] = vars[i,j] # edge in opposite direction

m.update()

# Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
             for i in range(n)), name='degree')

GurobiError: Unsupported type (<type 'numpy.ndarray'>) for LinExpr addition argument
</code>```

First two lines of data

```<code>1,19.007,35.75,1
2,4.4447,6.0735,2
</code>```

答:
Even though this question is answered, for future visitors who are looking for good ways to read a csv file, pandas must be mentioned:</p>

```<code>import pandas as pd
df = pd.read_csv('prob25.csv', header=None, index_col=0, names=['x', 'y', 'idx'])
df
         x        y  idx
1  19.0070  35.7500    1
2   4.4447   6.0735    2
</code>```

Body:
I'm learning how to solve combinatorial optimization problems in Gurobi using Python. I would like to know what is the best option to read a csv file to use the data as model parameters. I'm using 'genfromtxt' to read the csv file, but I'm having difficulties in using it for constraint construction (Gurobi doesn't support this type - see error).

Here my code and error message, my_data is composed by 4 columns: node index, x coordinate, y coordinate and maximum degree.

from gurobipy import *
from numpy import genfromtxt
import math

# Read data from csv file
my_data = genfromtxt('prob25.csv', delimiter=',')

# Number of vertices
n = len(my_data)

# Function to calculate euclidean distancces
dist = {(i,j) :
    math.sqrt(sum((my_data[i][k]-my_data[j][k])**2 for k in [1,2]))
    for i in range(n) for j in range(i)}

# Create a new model
m = Model("dcstNarula")

# Create variables

vars = m.addVars(dist.keys(), obj=dist, vtype=GRB.BINARY, name='e')
for i,j in vars.keys():
    vars[j,i] = vars[i,j] # edge in opposite direction

m.update()

# Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
             for i in range(n)), name='degree')

GurobiError: Unsupported type (<type 'numpy.ndarray'>) for LinExpr addition argument

First two lines of data

1,19.007,35.75,1
2,4.4447,6.0735,2

Body:
Even though this question is answered, for future visitors who are looking for good ways to read a csv file, pandas must be mentioned:

import pandas as pd
df = pd.read_csv('prob25.csv', header=None, index_col=0, names=['x', 'y', 'idx'])
df
         x        y  idx
1  19.0070  35.7500    1
2   4.4447   6.0735    2


来源: stackexchange

问:
Replicating Tutorial but received error with Pandas. Code out of date possible?
I'm currently replicating this tutorial here trying to do some measurements on a convention that recently occurred. However, on trying to replicate the data visualization aspects of the tutorial I am getting an error that I cannot find a solution to.

Here is my code:

```<code>import pandas as pd
from pandas import TimeGrouper
from pandas.tseries.offsets import DateOffset
anthrocon = pd.read_csv(r'E:\Anthrocon\tweets.csv')
anthrocon['createdat'] = pd.todatetime(pd.Series(anthrocon['createdat']))
anthrocon.setindex('createdat', drop=False, inplace=True)
anthrocon.index = anthrocon.index.tzlocalize9('GMT').txconvert('EST')
anthrocon.index = anthrocon.index - DateOffSet(hours = 12)
anthrocon.index
</code>```

There are two big errors I am getting right now. One is that Python returns that there is no module for the pandas.tseries.offsets import DateOffSet. It returns:

```<code>Traceback (most recent call last):
File "D:\database.py", line 2, in <module>
from pandas.tseries.resample import DatetimeIndex, TimeGrouper
ModuleNotFoundError: No module named 'pandas.tseries.resample'
</code>```

I've looked up the same error but I have not found anything too helpful, and I've reinstalled pandas several times to see if that rectifys the issue. Is my code out of date here?

Now if I attempt to remove the code for the sake of just moving forward with the project I return an error that seems to be related to the code above. Python is unable to locate todatetime

The error:

```<code>Warning (from warnings module):
File "D:\database.py", line 1
import pandas as pd
DtypeWarning: Columns (10,11,12,13,14,15,16,17,22,30,31) have mixed types.
Specify dtype option on import or set low_memory=False.
Traceback (most recent call last):
File "D:\database.py", line 4, in <module>
anthrocon['createdat'] = pd.todatetime(pd.Series(anthrocon['createdat']))
AttributeError: module 'pandas' has no attribute 'todatetime'code here
</code>```

I would greatly appreciate any input or point in the right direction.

答: SOLVED. I figured out the tutorial did not have a proper to_datetime it forgot the underscore. Sorry about that!</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm currently replicating this tutorial here trying to do some measurements on a convention that recently occurred. However, on trying to replicate the data visualization aspects of the tutorial I am getting an error that I cannot find a solution to.

Here is my code:

import pandas as pd
from pandas import TimeGrouper
from pandas.tseries.offsets import DateOffset
anthrocon = pd.read_csv(r'E:\Anthrocon\tweets.csv')
anthrocon['createdat'] = pd.todatetime(pd.Series(anthrocon['createdat']))
anthrocon.setindex('createdat', drop=False, inplace=True)
anthrocon.index = anthrocon.index.tzlocalize9('GMT').txconvert('EST')
anthrocon.index = anthrocon.index - DateOffSet(hours = 12)
anthrocon.index

There are two big errors I am getting right now. One is that Python returns that there is no module for the pandas.tseries.offsets import DateOffSet. It returns:

Traceback (most recent call last):
File "D:\database.py", line 2, in <module>
from pandas.tseries.resample import DatetimeIndex, TimeGrouper
ModuleNotFoundError: No module named 'pandas.tseries.resample'

I've looked up the same error but I have not found anything too helpful, and I've reinstalled pandas several times to see if that rectifys the issue. Is my code out of date here?

Now if I attempt to remove the code for the sake of just moving forward with the project I return an error that seems to be related to the code above. Python is unable to locate todatetime

The error:

Warning (from warnings module):
File "D:\database.py", line 1
import pandas as pd
DtypeWarning: Columns (10,11,12,13,14,15,16,17,22,30,31) have mixed types.
Specify dtype option on import or set low_memory=False.
Traceback (most recent call last):
File "D:\database.py", line 4, in <module>
anthrocon['createdat'] = pd.todatetime(pd.Series(anthrocon['createdat']))
AttributeError: module 'pandas' has no attribute 'todatetime'code here

I would greatly appreciate any input or point in the right direction.


问:
How do you log an int on Android?
I'm logging this:

```<code>Log.d(getClass().getName(), "BLA BLA BLA");
</code>```

How can I show an int value? What is the equivalent of C's %d?

答: Android's logging does not support formatted printf style string natively. Usually you just use valueOf or toString and use string concats, though if you must you can always use the Formatter. </p>

ContentLicense: CC BY-SA 4.0

Title: How do you log an int on Android?

Body:
I'm logging this:

Log.d(getClass().getName(), "BLA BLA BLA");

How can I show an int value? What is the equivalent of C's %d?

ContentLicense: CC BY-SA 2.5


问:
Split string to maximum length and append the rest to the last array item
Is there a way for me to split a string into an array and limit to x and if there are more parts than the limit append to the last array item?

So, for example I have

```<code>'Billy Bob Joe'.split(' ', 2) // Outputs ["Billy", "Bob"]
</code>```

I would like to output

```<code>["Billy", "Bob Joe"]
</code>```

Is there a way for this to be easily done in JavaScript?

答:
I think you can't do that using split function
you can use

```<code>var str = "Billy Bob Joe";
var res = str.split(" ",1);
str=str.replace(res,'');
</code>```

Now str have Bob Joe

Body:
Is there a way for me to split a string into an array and limit to x and if there are more parts than the limit append to the last array item?

So, for example I have

'Billy Bob Joe'.split(' ', 2) // Outputs ["Billy", "Bob"]

I would like to output

["Billy", "Bob Joe"]

Is there a way for this to be easily done in JavaScript?

Body:
I think you can't do that using split function
you can use

var str = "Billy Bob Joe";
var res = str.split(" ",1);
str=str.replace(res,'');

Now str have Bob Joe


问:
Print n choose k combination algorithm using recursion
This must be a classic interview question, however, I'm having a problem understanding it.

Below is my implementation in Python and if you run it, it's only printing ab, ac, ad. It doesn't go to the 'b' (bc, bd) level.

```<code>def Print_nCk (the_list, k, str_builder, used):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(len(the_list)):
            if used[i] !=True:
                str_builder+=the_list[i]
                used[i] = True
                Print_nCk(the_list, k, str_builder, used)
                str_builder = str_builder[:-1]

Print_nCk(['a','b','c','d'], 2, "",[False,False,False,False])
</code>```

The right answer is ab,ac,ad,bc,bd,cd when above line is passed.

I know the right implementation from here without using used param (http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/) but
my question is what is wrong is my implementation?

Can you shed some light on it?

To debug, I printed out "used" every time. The used param becomes (True, True, True, True) after printing "ad" then it doesn't go deeper than that. What's the smart way to fix the used, if I insist on using used?

答:
You forgot to unset used[i] when you backtrack:

```<code>def Print_nCk (the_list, k, str_builder, used):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(len(the_list)):
            if used[i] != True:
                str_builder += the_list[i]
                used[i] = True
                Print_nCk(the_list, k, str_builder, used)
                str_builder = str_builder[:-1]
                <b>used[i] = False</b>

Print_nCk(['a','b','c','d'], 2, "",[False,False,False,False])</code>```

In your current implementation, you set used[i] to True from the moment you pick the i as value. If however later, you decide to pick another branch, you should do the bookkeeping correctly and thus unset the used[i].

Note that now "ab" and "ba" will be generated. You thus generate combinations with symmetry. If you do not want that, you can use an additional parameter. That makes sure that you do not use an index lower than the previously picked one:

```<code>def Print_nCk (the_list, k, str_builder, used<b>, prev = 0</b>):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(<b>prev,</b>len(the_list)):
            if used[i] != True:
                str_builder += the_list[i]
                used[i] = True
                Print_nCk(the_list, k, str_builder, used, <b>i+1</b>)
                str_builder = str_builder[:-1]
                used[i] = False

Print_nCk(['a','b','c','d'], 2, "",[False,False,False,False])</code>```

Nevertheless, this more or less defeats the purpose of using a "used" array. You can simply use the prev:

```<code>def Print_nCk (the_list, k, str_builder, prev = 0):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(<b>prev,</b>len(the_list)):
            str_builder += the_list[i]
            Print_nCk(the_list, k, str_builder, i+1)
            str_builder = str_builder[:-1]

Print_nCk(['a','b','c','d'], 2, "")</code>```

This then prints:

```<code>>>> Print_nCk(['a','b','c','d'], 2, "")
ab
ac
ad
bc
bd
cd
</code>```

Body:
This must be a classic interview question, however, I'm having a problem understanding it.

Below is my implementation in Python and if you run it, it's only printing ab, ac, ad. It doesn't go to the 'b' (bc, bd) level.

def Print_nCk (the_list, k, str_builder, used):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(len(the_list)):
            if used[i] !=True:
                str_builder+=the_list[i]
                used[i] = True
                Print_nCk(the_list, k, str_builder, used)
                str_builder = str_builder[:-1]

Print_nCk(['a','b','c','d'], 2, "",[False,False,False,False])

The right answer is ab,ac,ad,bc,bd,cd when above line is passed.

I know the right implementation from here without using used param (http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/) but
my question is what is wrong is my implementation?

Can you shed some light on it?

To debug, I printed out "used" every time. The used param becomes (True, True, True, True) after printing "ad" then it doesn't go deeper than that. What's the smart way to fix the used, if I insist on using used?

Body:
You forgot to unset used[i] when you backtrack:

def Print_nCk (the_list, k, str_builder, used):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(len(the_list)):
            if used[i] != True:
                str_builder += the_list[i]
                used[i] = True
                Print_nCk(the_list, k, str_builder, used)
                str_builder = str_builder[:-1]
                used[i] = False

Print_nCk(['a','b','c','d'], 2, "",[False,False,False,False])

In your current implementation, you set used[i] to True from the moment you pick the i as value. If however later, you decide to pick another branch, you should do the bookkeeping correctly and thus unset the used[i].

Note that now "ab" and "ba" will be generated. You thus generate combinations with symmetry. If you do not want that, you can use an additional parameter. That makes sure that you do not use an index lower than the previously picked one:

def Print_nCk (the_list, k, str_builder, used, prev = 0):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(prev,len(the_list)):
            if used[i] != True:
                str_builder += the_list[i]
                used[i] = True
                Print_nCk(the_list, k, str_builder, used, i+1)
                str_builder = str_builder[:-1]
                used[i] = False

Print_nCk(['a','b','c','d'], 2, "",[False,False,False,False])

Nevertheless, this more or less defeats the purpose of using a "used" array. You can simply use the prev:

def Print_nCk (the_list, k, str_builder, prev = 0):
    if len(str_builder) == k:
        print str_builder
        return
    else:
        for i in xrange(prev,len(the_list)):
            str_builder += the_list[i]
            Print_nCk(the_list, k, str_builder, i+1)
            str_builder = str_builder[:-1]

Print_nCk(['a','b','c','d'], 2, "")

This then prints:

>>> Print_nCk(['a','b','c','d'], 2, "")
ab
ac
ad
bc
bd
cd


问:
Extract URL String from Email Getting Rid of All Other Text
I have a vba script that extracts the text of an email.  I am able to select the specific email no problem and debug print that to a file.  I can't figure out how to extract or trim down in the same script the exact line that I need:

```<code>Public Function GetEmailString()
Dim olApp As Outlook.Application
Dim olNamespace As Outlook.Namespace
Dim olFolder  As Outlook.MAPIFolder
Dim olItem As Outlook.Items
Dim olMail As Variant
Dim i As Long
Dim s As String
Dim n As Integer

n = FreeFile()

Set olApp = New Outlook.Application
Set olNamespace = olApp.GetNamespace("MAPI")
Set olFolder = olNamespace.GetDefaultFolder(olFolderInbox).Folders("Test")
Set olItem = olFolder.Items

olItem.Sort “Subject”

i = 1

For Each olMail In olItem
    If InStr(olMail.Subject, "UPS Report Available") > 0 Then
    Open "D:\test.txt" For Output As #n
        s = olMail.body
        Debug.Print s ' write to immediate
        Print #n, s ' write to file
        Close #n
        i = i + 1
    End If
Next olMail
End Function

The contents of the email are this:

At the request of whoever of Test Company, this notification provides access to reports regarding shipper shipment information. The reports are available for download by accessing the link provided below.

Do not reply to this e-mail. Shipper Company and Whoever of Test Company will not receive your reply.

Message from Whoever of Test Company:
Daily Quantum View Report for 1V0650

Reports Available for Download:
https://www.ups.com/email-qvm/downloadCVRpt?id=Ym)Wm4K1t4EyTVWj3Bcm3BZNlhj2Io(86B3YZ0rzJQ6dxEL4O6S(BTNtF08IcdWvoPiJ9JGgw7(SrxzFI6(4yItUToowZLPI)rkb2o7HRxtHUFPz6GMiNnjsI6G)j(iKEWkTDKnH7YnwNeBEDUAPw__&loc=en_US

This e-mail was automatically generated by Shipper Company e-mail services at the request of Whoever of Test Company. Shipping Company and Whoever of Test Company will not receive any reply to this email. Please contact Whoever of Test Company directly if you have questions regarding the referenced shipment or wish to discontinue this notification service.
</code>```

I am able to print that to a text file the contents that I need it trimmed down to are this:

```<code>https://www.ups.com/email-qvm/downloadCVRpt?id=Ym)Wm4K1t4EyTVWj3Bcm3BZNlhj2Io(86B3YZ0rzJQ6dxEL4O6S(BTNtF08IcdWvoPiJ9JGgw7(SrxzFI6(4yItUToowZLPI)rkb2o7HRxtHUFPz6GMiNnjsI6G)j(iKEWkTDKnH7YnwNeBEDUAPw__&loc=en_US
</code>```

Does anyone have any ideas? I am ultimatly trying to get that one string in a text file so I can later read it and use the xttp to download the csv file that this link generates automatically into an access database table.

答:
I figured out a simple method to return what I need.  I am then going to write this to another file and scoop that up to be read by a database:</p>

```<code>Public Function ReadFiles()
Dim fso As New Scripting.FileSystemObject
Dim fsoFolder As Scripting.Folder
Dim fsoFile As File
Dim FileText As TextStream
Dim TextLine As String
Dim key As String ' Part before ":"

Dim strPath As String
Dim strFile As String
Dim strPandF As String
Dim strLine As String

strPath = "D:\"
strFile = "Test.txt"
strPandF = "D:\Test.txt"

Set fso = CreateObject("Scripting.FileSystemObject") 'New FileSystemObject
Set fsoFolder = fso.GetFolder(strPath)
Set fsoFile = fso.GetFile(strPandF)
Set FileText = fsoFile.OpenAsTextStream(ForReading)
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine 'read line
key = "https://www.ups.com/email-qvm"
If Left(TextLine, 29) = key Then

MsgBox TextLine
End If
Loop

FileText.Close

End Function
</code>```

Body:
I have a vba script that extracts the text of an email.  I am able to select the specific email no problem and debug print that to a file.  I can't figure out how to extract or trim down in the same script the exact line that I need:

Public Function GetEmailString()
Dim olApp As Outlook.Application
Dim olNamespace As Outlook.Namespace
Dim olFolder  As Outlook.MAPIFolder
Dim olItem As Outlook.Items
Dim olMail As Variant
Dim i As Long
Dim s As String
Dim n As Integer

n = FreeFile()

Set olApp = New Outlook.Application
Set olNamespace = olApp.GetNamespace("MAPI")
Set olFolder = olNamespace.GetDefaultFolder(olFolderInbox).Folders("Test")
Set olItem = olFolder.Items

olItem.Sort “Subject”

i = 1

For Each olMail In olItem
    If InStr(olMail.Subject, "UPS Report Available") > 0 Then
    Open "D:\test.txt" For Output As #n
        s = olMail.body
        Debug.Print s ' write to immediate
        Print #n, s ' write to file
        Close #n
        i = i + 1
    End If
Next olMail
End Function

The contents of the email are this:

At the request of whoever of Test Company, this notification provides access to reports regarding shipper shipment information. The reports are available for download by accessing the link provided below.

Do not reply to this e-mail. Shipper Company and Whoever of Test Company will not receive your reply.

Message from Whoever of Test Company:
Daily Quantum View Report for 1V0650

Reports Available for Download:
https://www.ups.com/email-qvm/downloadCVRpt?id=Ym)Wm4K1t4EyTVWj3Bcm3BZNlhj2Io(86B3YZ0rzJQ6dxEL4O6S(BTNtF08IcdWvoPiJ9JGgw7(SrxzFI6(4yItUToowZLPI)rkb2o7HRxtHUFPz6GMiNnjsI6G)j(iKEWkTDKnH7YnwNeBEDUAPw__&loc=en_US

This e-mail was automatically generated by Shipper Company e-mail services at the request of Whoever of Test Company. Shipping Company and Whoever of Test Company will not receive any reply to this email. Please contact Whoever of Test Company directly if you have questions regarding the referenced shipment or wish to discontinue this notification service.

I am able to print that to a text file the contents that I need it trimmed down to are this:

https://www.ups.com/email-qvm/downloadCVRpt?id=Ym)Wm4K1t4EyTVWj3Bcm3BZNlhj2Io(86B3YZ0rzJQ6dxEL4O6S(BTNtF08IcdWvoPiJ9JGgw7(SrxzFI6(4yItUToowZLPI)rkb2o7HRxtHUFPz6GMiNnjsI6G)j(iKEWkTDKnH7YnwNeBEDUAPw__&loc=en_US

Does anyone have any ideas? I am ultimatly trying to get that one string in a text file so I can later read it and use the xttp to download the csv file that this link generates automatically into an access database table.

Body:
I figured out a simple method to return what I need.  I am then going to write this to another file and scoop that up to be read by a database:

Public Function ReadFiles()
Dim fso As New Scripting.FileSystemObject
Dim fsoFolder As Scripting.Folder
Dim fsoFile As File
Dim FileText As TextStream
Dim TextLine As String
Dim key As String ' Part before ":"

Dim strPath As String
Dim strFile As String
Dim strPandF As String
Dim strLine As String

strPath = "D:\"
strFile = "Test.txt"
strPandF = "D:\Test.txt"

Set fso = CreateObject("Scripting.FileSystemObject") 'New FileSystemObject
Set fsoFolder = fso.GetFolder(strPath)
Set fsoFile = fso.GetFile(strPandF)
Set FileText = fsoFile.OpenAsTextStream(ForReading)
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine 'read line
key = "https://www.ups.com/email-qvm"
If Left(TextLine, 29) = key Then

MsgBox TextLine
End If
Loop

FileText.Close

End Function


问:
How to centralize and resize digits using opencv?
I want to OCR some scanned forms (filled by hand). It is the first time I do something serious using computer vision. So far I'm able to locate the squares containing digits for a date field:

Looking at the example handwritten digit dataset that comes with OpenCV, I see digits are centralized and resized to (20, 20):

Since this may be a fairly common problem, I'm wondering if the algorithm is already implemented in OpenCV (or numpy, scipy, etc) so I don't have to reinvent the wheel.

The question is: is there a built-in pipeline in Python in order to normalize the samples?

答:
A built in pipeline not sure, but you could implement your own, given you already have the contours, by doing the following (based on my comment):

Obtain Bounding rectangle of contour (therefore centering on it) and crop that part :

```<code>x,y,w,h = cv2.boundingRect(cnt)
imgCrop = img[x:(x+w), y:(y+h)]
</code>```

Resize image to desired size (say 20 x 20):

```<code>imgResized = cv2.resize(imgCrop, (20,20))
</code>```

You can also resize axes by a specific ratio like:

```<code>imgResized = cv2.resize(imgCrop, (0,0), fx=0.5, fy=0.5)
</code>```

or with scipy (as suggested in this question):

```<code>imgResized = scipy.misc.imresize(imgCrop, 0.5)
</code>```

Bonus: Check this great tutorial on basic image manipulation with Python and OpenCV, where they show other way to resize taking into account aspect ratio and interpolations for better results, extracting from it:

```<code>imgResized = cv2.resize(imgCrop, (20,20), interpolation = cv2.INTER_AREA)
</code>```

Body:
A built in pipeline not sure, but you could implement your own, given you already have the contours, by doing the following (based on my comment):

Obtain Bounding rectangle of contour (therefore centering on it) and crop that part :

x,y,w,h = cv2.boundingRect(cnt)
imgCrop = img[x:(x+w), y:(y+h)]

Resize image to desired size (say 20 x 20):

imgResized = cv2.resize(imgCrop, (20,20))

You can also resize axes by a specific ratio like:

imgResized = cv2.resize(imgCrop, (0,0), fx=0.5, fy=0.5)

or with scipy (as suggested in this question):

imgResized = scipy.misc.imresize(imgCrop, 0.5)

Bonus: Check this great tutorial on basic image manipulation with Python and OpenCV, where they show other way to resize taking into account aspect ratio and interpolations for better results, extracting from it:

imgResized = cv2.resize(imgCrop, (20,20), interpolation = cv2.INTER_AREA)


问:
pascal-like string literal regular expression
I'm trying to match pascal string literal input to the following pattern: @"^'([^']|(''))*'$", but that's not working. What is wrong with the pattern?

```<code>public void Run()
{
    using(StreamReader reader = new StreamReader(String.Empty))
    {
        var LineNumber = 0;
        var LineContent = String.Empty;

        while(null != (LineContent = reader.ReadLine()))
        {
            LineNumber++;

            String[] InputWords = new Regex(@"\(\*(?:\w|\d)*\*\)").Replace(LineContent.TrimStart(' '), @" ").Split(' ');

            foreach(String word in InputWords)
            {
                Scanner.Scan(word);
            }

        }
    }
}
</code>```

I search input string for any pascal-comment entry, replace it with whitespace, then I split input into substrings to match them to the following:

```<code>private void Initialize()
{
    MatchingTable = new Dictionary<TokenUnit.TokenType, Regex>();

    MatchingTable[TokenUnit.TokenType.Identifier] = new Regex
    (
        @"^[_a-zA-Z]\w*$",
        RegexOptions.Compiled | RegexOptions.Singleline
    );
    MatchingTable[TokenUnit.TokenType.NumberLiteral] = new Regex
    (
        @"(?:^\d+$)|(?:^\d+\.\d*$)|(?:^\d*\.\d+$)",
         RegexOptions.Compiled | RegexOptions.Singleline
    );
}
// ... Here it all comes together
public TokenUnit Scan(String input)
{
    foreach(KeyValuePair<TokenUnit.TokenType, Regex> node in this.MatchingTable)
    {
        if(node.Value.IsMatch(input))
        {
            return new TokenUnit
            {
                Type = node.Key
            };
        }
    }
    return new TokenUnit
    {
        Type = TokenUnit.TokenType.Unsupported
    };
}
</code>```

答:
The pattern appears to be correct, although it could be simplified:

```<code>^'(?:[^']+|'')*'$
</code>```

Explanation:

```<code>^      # Match start of string
'      # Match the opening quote
(?:    # Match either...
 [^']+ # one or more characters except the quote character
 |     # or
 ''    # two quote characters (= escaped quote)
)*     # any number of times
'      # Then match the closing quote
$      # Match end of string
</code>```

This regex will fail if the input you're checking it against contains anything besides a Pascal string (say, surrounding whitespace).

So if you want to use the regex to find Pascal strings within a larger text corpus, then you need to remove the ^ and $ anchors.

And if you want to allow double quotes, too, then you need to augment the regex:

```<code>^(?:'(?:[^']+|'')*'|"(?:[^"]+|"")*")$
</code>```

In C#:

```<code>foundMatch = Regex.IsMatch(subjectString, "^(?:'(?:[^']+|'')*'|\"(?:[^\"]+|\"\")*\")$");
</code>```

This regex will match strings like

```<code>'This matches.'
'This too, even though it ''contains quotes''.'
"Mixed quotes aren't a problem."
''
</code>```

It won't match strings like

```<code>'The quotes aren't balanced or escaped.'
There is something 'before or after' the quotes.
    "Even whitespace is a problem."
</code>```

Body:
I'm trying to match pascal string literal input to the following pattern: @"^'([^']|(''))*'$", but that's not working. What is wrong with the pattern?

public void Run()
{
    using(StreamReader reader = new StreamReader(String.Empty))
    {
        var LineNumber = 0;
        var LineContent = String.Empty;

        while(null != (LineContent = reader.ReadLine()))
        {
            LineNumber++;

            String[] InputWords = new Regex(@"\(\*(?:\w|\d)*\*\)").Replace(LineContent.TrimStart(' '), @" ").Split(' ');

            foreach(String word in InputWords)
            {
                Scanner.Scan(word);
            }

        }
    }
}

I search input string for any pascal-comment entry, replace it with whitespace, then I split input into substrings to match them to the following:

private void Initialize()
{
    MatchingTable = new Dictionary<TokenUnit.TokenType, Regex>();

    MatchingTable[TokenUnit.TokenType.Identifier] = new Regex
    (
        @"^[_a-zA-Z]\w*$",
        RegexOptions.Compiled | RegexOptions.Singleline
    );
    MatchingTable[TokenUnit.TokenType.NumberLiteral] = new Regex
    (
        @"(?:^\d+$)|(?:^\d+\.\d*$)|(?:^\d*\.\d+$)",
         RegexOptions.Compiled | RegexOptions.Singleline
    );
}
// ... Here it all comes together
public TokenUnit Scan(String input)
{
    foreach(KeyValuePair<TokenUnit.TokenType, Regex> node in this.MatchingTable)
    {
        if(node.Value.IsMatch(input))
        {
            return new TokenUnit
            {
                Type = node.Key
            };
        }
    }
    return new TokenUnit
    {
        Type = TokenUnit.TokenType.Unsupported
    };
}

Body:
The pattern appears to be correct, although it could be simplified:

^'(?:[^']+|'')*'$

Explanation:

^      # Match start of string
'      # Match the opening quote
(?:    # Match either...
 [^']+ # one or more characters except the quote character
 |     # or
 ''    # two quote characters (= escaped quote)
)*     # any number of times
'      # Then match the closing quote
$      # Match end of string

This regex will fail if the input you're checking it against contains anything besides a Pascal string (say, surrounding whitespace).

So if you want to use the regex to find Pascal strings within a larger text corpus, then you need to remove the ^ and $ anchors.

And if you want to allow double quotes, too, then you need to augment the regex:

^(?:'(?:[^']+|'')*'|"(?:[^"]+|"")*")$

In C#:

foundMatch = Regex.IsMatch(subjectString, "^(?:'(?:[^']+|'')*'|\"(?:[^\"]+|\"\")*\")$");

This regex will match strings like

'This matches.'
'This too, even though it ''contains quotes''.'
"Mixed quotes aren't a problem."
''

It won't match strings like

'The quotes aren't balanced or escaped.'
There is something 'before or after' the quotes.
    "Even whitespace is a problem."


问:
mapping 2-D array in react-native
Attached JSON:-

[
  {
    "category":"Faces",
    "items": [
      {
        "name": "Oh well!",
        "art" : "¯\\_(ツ)_/¯"
      },
      {
        "name": "Disapproving Look",
        "art":  "ಠ_ಠ"
      },
      {
        "name": "Disapproving Look 2",
        "art":  "ఠ_ఠ"
      },
      {
        "name": "Glasses Smile",
        "art":  "ʘ‿ʘ"
      },
      {
        "name": "Devious Smile",
        "art":  "ಠ‿ಠ"
      },
      {
        "name": "Frowning",
        "art": "ಠ╭╮ಠ"
      },
      {
        "name": "Yelling",
        "art": "ಠoಠ"
      },
      {
        "name": "Mustache Man",
        "art": "ಠ▃ಠ"
      },
      {
        "name": "Blank Stare",
        "art": "ರ_ರ"
      },
      {
        "name": "HUH?",
        "art":  "ლ(｀ー´ლ)"
      },
      {
        "name": "Rosy Cheeks",
        "art":  "(｡◕‿◕｡)"
      },
      {
        "name": "hehehe",
        "art":  "( ¬‿¬)"
      },
      {
        "name": "Pointing Out",
        "art":  "☜(⌒▽⌒)☞"
      },
      {
        "name": "Haha!",
        "art":  "☜(ﾟヮﾟ☜)"
      },
      {
        "name": "Run Away Crying",
        "art":  "ε=ε=ε=┌(;*´Д`)ﾉ"
      },
      {
        "name": "Cheers",
        "art":  "（ ^_^）o自自o（^_^ ）"
      },
      {
        "name": "Up All Night",
        "art":  "۞_۞"
      },
      {
        "name": "High",
        "art":  "q(❂‿❂)p"
      },
      {
        "name": "Dazed & Confused",
        "art":  "⊙﹏⊙"
      },
      {
        "name": "No Clue!",
        "art":  "¯\\_(⊙︿⊙)_/¯"
      },
      {
        "name": "I Dunno",
        "art":  "¯\\(°_o)/¯ "
      },
      {
        "name": "Staring Eyes",
        "art":  "Ꙭ"
      },
      {
        "name": "Cat Eyes",
        "art": "ф_ф"
      },
      {
        "name": "Winking",
        "art": "◕‿↼"
      },
      {
        "name": "Reaching Down",
        "art":  "(,,Ծ‸Ծ,,)"
      },
      {
        "name": "Just Woke up",
        "art":  "╰(´・｀)ﾉ"
      },
      {
        "name": "Sleep Walking",
        "art":  "(¬º-°)¬"
      },
      {
        "name": "Disappointed Look",
        "art":  "(-_-)"
      }
    ]
  },
  {
    "category": "Emotions",
    "items": [
      {
        "name": "Angry",
        "art":  "{{|└(>o< )┘|}}"
      },
      {
        "name": "Why, God, WHY!?",
        "art":  "щ（ﾟДﾟщ）"
      },
      {
        "name": "In Love",
        "art":  "♥（｡✿‿✿｡）❤"
      },
      {
        "name": "In Love 2",
        "art":  "♥‿♥"
      },
      {
        "name": "Puzzled",
        "art":  "く(＾_・)ゝ"
      },
      {
        "name": "Mad",
        "art":  "（　ﾟДﾟ）"
      },
      {
        "name": "Whatever",
        "art":  "（＾～＾）ノ"
      },
      {
        "name": "Happy",
        "art":  "ヽ(´▽`)/"
      },
      {
        "name": "Love at First Sight",
        "art":  "꒰♡ˊ͈ ु꒳ ूˋ͈꒱.⑅*♡"
      },
      {
        "name": "Need A Hug",
        "art":  "ヽ(´ー｀)ノ"
      },
      {
        "name": "So Beautiful!",
        "art":  "ಥ_ಥ"
      },
      {
        "name": "Sad / Crying",
        "art":  "ಥ﹏ಥ"
      },
      {
        "name": "Embarrased",
        "art":  "(﹡⌒▽⌒﹡)"
      },
      {
        "name": "Extra Embarrased",
        "art":  "(/ω＼)"
      },
      {
        "name": "No Thanks",
        "art": "(ღ˘⌣˘ღ)"
      },
      {
        "name": "I've Seen The Light",
        "art": "•✞_✞•"
      }
    ]
  },]```
</div>
</div>
</p>

<p><strong>Attempt in React-Native</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Textables extends Component{
  constructor(){
    super()
    this.state={data:[]}
  }

  getData(){
    return fetch('https://raw.githubusercontent.com/OTGApps/Textables/master/resources/content.json')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({data: responseJson});
      })
      .catch((error) => {
        console.error(error);
      });
  }

  componentDidMount(){
    this.getData();
  }

 render()
 {
      let articles= this.state.data.map(function(articleData, index){
        let articles1 = articleData.map(function(meow, j){
          return(<content>
            <Card><CardItem><Body>
            <Text>{meow.items.name}</Text></Body></CardItem></Card>
            <Card><CardItem><Body>
            <Text>{meow.items.art}</Text></Body></CardItem></Card></content>
          );
        });
        return(

            <Card><CardItem><Body>
            <Text>{articleData.category}</Text></Body></CardItem></Card>
        );
      });
        return(
          <Content>
          {articles}
        </Content>
        )
 }
}</code>```

Error:- undefined is not a function (evaluating 'articleData.map')
I'm trying to map the the items one by one by looping through each array.
Should I use index.map instead of articleData.map?

答:
articleData points to the object in the data array.  It looks like:

{
    "category": "Emotions",
    "items": [],
}

You want to use articleData.items.map.

Additionally, that getData function will probably not work how you want.  Since it's not bound to the class scope, it won't be able to access this.setState.  You'll probably want to either add this to your constructor:

this.getData = this.getData.bind(this)

or, you can change the function declaration:

getData = () => { /* your function */ }

Title: mapping 2-D array in react-native

Body:
Attached JSON:-

[
  {
    "category":"Faces",
    "items": [
      {
        "name": "Oh well!",
        "art" : "¯\\_(ツ)_/¯"
      },
      {
        "name": "Disapproving Look",
        "art":  "ಠ_ಠ"
      },
      {
        "name": "Disapproving Look 2",
        "art":  "ఠ_ఠ"
      },
      {
        "name": "Glasses Smile",
        "art":  "ʘ‿ʘ"
      },
      {
        "name": "Devious Smile",
        "art":  "ಠ‿ಠ"
      },
      {
        "name": "Frowning",
        "art": "ಠ╭╮ಠ"
      },
      {
        "name": "Yelling",
        "art": "ಠoಠ"
      },
      {
        "name": "Mustache Man",
        "art": "ಠ▃ಠ"
      },
      {
        "name": "Blank Stare",
        "art": "ರ_ರ"
      },
      {
        "name": "HUH?",
        "art":  "ლ(｀ー´ლ)"
      },
      {
        "name": "Rosy Cheeks",
        "art":  "(｡◕‿◕｡)"
      },
      {
        "name": "hehehe",
        "art":  "( ¬‿¬)"
      },
      {
        "name": "Pointing Out",
        "art":  "☜(⌒▽⌒)☞"
      },
      {
        "name": "Haha!",
        "art":  "☜(ﾟヮﾟ☜)"
      },
      {
        "name": "Run Away Crying",
        "art":  "ε=ε=ε=┌(;*´Д`)ﾉ"
      },
      {
        "name": "Cheers",
        "art":  "（ ^_^）o自自o（^_^ ）"
      },
      {
        "name": "Up All Night",
        "art":  "۞_۞"
      },
      {
        "name": "High",
        "art":  "q(❂‿❂)p"
      },
      {
        "name": "Dazed & Confused",
        "art":  "⊙﹏⊙"
      },
      {
        "name": "No Clue!",
        "art":  "¯\\_(⊙︿⊙)_/¯"
      },
      {
        "name": "I Dunno",
        "art":  "¯\\(°_o)/¯ "
      },
      {
        "name": "Staring Eyes",
        "art":  "Ꙭ"
      },
      {
        "name": "Cat Eyes",
        "art": "ф_ф"
      },
      {
        "name": "Winking",
        "art": "◕‿↼"
      },
      {
        "name": "Reaching Down",
        "art":  "(,,Ծ‸Ծ,,)"
      },
      {
        "name": "Just Woke up",
        "art":  "╰(´・｀)ﾉ"
      },
      {
        "name": "Sleep Walking",
        "art":  "(¬º-°)¬"
      },
      {
        "name": "Disappointed Look",
        "art":  "(-_-)"
      }
    ]
  },
  {
    "category": "Emotions",
    "items": [
      {
        "name": "Angry",
        "art":  "{{|└(>o< )┘|}}"
      },
      {
        "name": "Why, God, WHY!?",
        "art":  "щ（ﾟДﾟщ）"
      },
      {
        "name": "In Love",
        "art":  "♥（｡✿‿✿｡）❤"
      },
      {
        "name": "In Love 2",
        "art":  "♥‿♥"
      },
      {
        "name": "Puzzled",
        "art":  "く(＾_・)ゝ"
      },
      {
        "name": "Mad",
        "art":  "（　ﾟДﾟ）"
      },
      {
        "name": "Whatever",
        "art":  "（＾～＾）ノ"
      },
      {
        "name": "Happy",
        "art":  "ヽ(´▽`)/"
      },
      {
        "name": "Love at First Sight",
        "art":  "꒰♡ˊ͈ ु꒳ ूˋ͈꒱.⑅*♡"
      },
      {
        "name": "Need A Hug",
        "art":  "ヽ(´ー｀)ノ"
      },
      {
        "name": "So Beautiful!",
        "art":  "ಥ_ಥ"
      },
      {
        "name": "Sad / Crying",
        "art":  "ಥ﹏ಥ"
      },
      {
        "name": "Embarrased",
        "art":  "(﹡⌒▽⌒﹡)"
      },
      {
        "name": "Extra Embarrased",
        "art":  "(/ω＼)"
      },
      {
        "name": "No Thanks",
        "art": "(ღ˘⌣˘ღ)"
      },
      {
        "name": "I've Seen The Light",
        "art": "•✞_✞•"
      }
    ]
  },]

Attempt in React-Native

class Textables extends Component{
  constructor(){
    super()
    this.state={data:[]}
  }

  getData(){
    return fetch('https://raw.githubusercontent.com/OTGApps/Textables/master/resources/content.json')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({data: responseJson});
      })
      .catch((error) => {
        console.error(error);
      });
  }

  componentDidMount(){
    this.getData();
  }

 render()
 {
      let articles= this.state.data.map(function(articleData, index){
        let articles1 = articleData.map(function(meow, j){
          return(<content>
            <Card><CardItem>
            <Text>{meow.items.name}</Text></CardItem></Card>
            <Card><CardItem>
            <Text>{meow.items.art}</Text></CardItem></Card></content>
          );
        });
        return(

            <Card><CardItem>
            <Text>{articleData.category}</Text></CardItem></Card>
        );
      });
        return(
          <Content>
          {articles}
        </Content>
        )
 }
}

Error:- undefined is not a function (evaluating 'articleData.map')
I'm trying to map the the items one by one by looping through each array.
Should I use index.map instead of articleData.map?


问:
Razor select list (dropdownlistfor) setting default selected value
I have a select list which I set up in my view model first like this:

```<code>  public string selectedLocation { get; set; }

        public SelectList location = new SelectList(new[]
        {
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  {Text = "United States", Value = "US" , Selected = true },
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  { Text = "Australia", Value = "AU" },
            new SelectListItem  { Text = "China", Value = "CN" },
            new SelectListItem  { Text = "France", Value = "FR" },
            new SelectListItem  { Text = "Germany", Value = "DE" },
            new SelectListItem  { Text = "Italy", Value = "IT" },
            new SelectListItem  { Text = "Canada", Value = "CA" }
        }, "Value", "Text");
</code>```

As you can see I have set the default value for the US - select to true, thus this value should be selected in drop-down by some logic?

And this is where i show it in HTML:

```<code>@Html.DropDownListFor(model => model.selectedLocation, Model.location, new { @class = "select2", @style = "width:95%;border-left:2px solid #eee" })
</code>```

But the selected item in dropdown is always the first one, no matter what I set in viewmodel...

What am I doing wrong here ? :/

答:
So the source of the issue was that I had to set the model.selectedLocation value before passing the model into the view and rendering it like this:

```<code>public ActionResult Index()
{
   var model = new myClassViewModel();
   model.selectedLocation = "IT"; // as rene stated
   return View(model);
}
</code>```

Thanks to @rene

Body:
I have a select list which I set up in my view model first like this:

  public string selectedLocation { get; set; }

        public SelectList location = new SelectList(new[]
        {
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  {Text = "United States", Value = "US" , Selected = true },
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  { Text = "Australia", Value = "AU" },
            new SelectListItem  { Text = "China", Value = "CN" },
            new SelectListItem  { Text = "France", Value = "FR" },
            new SelectListItem  { Text = "Germany", Value = "DE" },
            new SelectListItem  { Text = "Italy", Value = "IT" },
            new SelectListItem  { Text = "Canada", Value = "CA" }
        }, "Value", "Text");

As you can see I have set the default value for the US - select to true, thus this value should be selected in drop-down by some logic?

And this is where i show it in HTML:

@Html.DropDownListFor(model => model.selectedLocation, Model.location, new { @class = "select2", @style = "width:95%;border-left:2px solid #eee" })

But the selected item in dropdown is always the first one, no matter what I set in viewmodel...

What am I doing wrong here ? :/

Body:
So the source of the issue was that I had to set the model.selectedLocation value before passing the model into the view and rendering it like this:

public ActionResult Index()
{
   var model = new myClassViewModel();
   model.selectedLocation = "IT"; // as rene stated
   return View(model);
}

Thanks to @rene


问:
Automatically scrolling TextView inside a RecyclerView
My current problem is the following: I have a RecyclerView and each element of this RecyclerView has a TextView.  I want that the TextView scrolls automatically. What if tried so far:

Customize TextView:

```<code>public class ScrollCustomTextView extends AppCompatTextView {
public ScrollCustomTextView(Context context) {
    super(context);
}

public ScrollCustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context,attrs,defStyle);
}

public ScrollCustomTextView(Context context, AttributeSet attrs) {
    super(context,attrs);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
    if (focused)
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
}

@Override
public void onWindowFocusChanged(boolean focused) {
    if(focused)
        super.onWindowFocusChanged(focused);
}

@Override
public boolean isFocused() {
    return true;
}

}
</code>```

and my .xml file looks like this:

```<code><package.ScrollCustomTextView
        android:id="@+id/main_idea_name"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/darkGreen"
        android:textSize="27dp"
        android:layout_marginTop="10dp"
        android:maxLines="1"
        android:textAppearance="@android:style/TextAppearance.Medium"

        />
</code>```

And in RecyclerView in the constructor for the ViewHolder I set

```<code>textView.setSelected(true);
</code>```

But it doesn't work. Does anyone have an idea to solve this?

Thanks.

答:
So here is the answer:

I put my TextView inside a HorizontalScrollView and added the following code to my adapter for the RecyclerView:

```<code>private void animateTextView(TextView mTextView) {
    int textWidth = getTextViewWidth(mTextView);
    int displayWidth = getDisplayWidth(mContext);

/* Start animation only when text is longer than dislay width. */
    if(displayWidth<=textWidth) {
        Animation mAnimation = new TranslateAnimation(
                0, -textWidth,
                0, 0);
        mAnimation.setDuration(10000);    // Set custom duration.
        mAnimation.setStartOffset(1000);    // Set custom offset.
        mAnimation.setRepeatMode(Animation.RESTART);    // This will animate text back ater it reaches end.
        mAnimation.setRepeatCount(Animation.INFINITE);    // Infinite animation.

        mTextView.startAnimation(mAnimation);
    }
}

private int getDisplayWidth(Context context) {
    int displayWidth;

    WindowManager windowManager = (WindowManager)context.getSystemService(
            Context.WINDOW_SERVICE);
    Display display = windowManager.getDefaultDisplay();
    Point screenSize = new Point();

    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(screenSize);
        displayWidth = screenSize.x;
    } else {
        displayWidth = display.getWidth();
    }

    return displayWidth;
}

private int getTextViewWidth(TextView textView) {
    textView.measure(0, 0);    // Need to set measure to (0, 0).
    return textView.getMeasuredWidth();
}
</code>```

And start the animation with:

```<code>animateTextView(txtView);
</code>```

Note: there is no more need for the customized TextView, just use a normal TextView.

Body:
My current problem is the following: I have a RecyclerView and each element of this RecyclerView has a TextView.  I want that the TextView scrolls automatically. What if tried so far:

Customize TextView:

public class ScrollCustomTextView extends AppCompatTextView {
public ScrollCustomTextView(Context context) {
    super(context);
}

public ScrollCustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context,attrs,defStyle);
}

public ScrollCustomTextView(Context context, AttributeSet attrs) {
    super(context,attrs);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
    if (focused)
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
}

@Override
public void onWindowFocusChanged(boolean focused) {
    if(focused)
        super.onWindowFocusChanged(focused);
}

@Override
public boolean isFocused() {
    return true;
}

}

and my .xml file looks like this:

<package.ScrollCustomTextView
        android:id="@+id/main_idea_name"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/darkGreen"
        android:textSize="27dp"
        android:layout_marginTop="10dp"
        android:maxLines="1"
        android:textAppearance="@android:style/TextAppearance.Medium"

        />

And in RecyclerView in the constructor for the ViewHolder I set

textView.setSelected(true);

But it doesn't work. Does anyone have an idea to solve this?

Thanks.

Body:
So here is the answer:

I put my TextView inside a HorizontalScrollView and added the following code to my adapter for the RecyclerView:

private void animateTextView(TextView mTextView) {
    int textWidth = getTextViewWidth(mTextView);
    int displayWidth = getDisplayWidth(mContext);

/* Start animation only when text is longer than dislay width. */
    if(displayWidth<=textWidth) {
        Animation mAnimation = new TranslateAnimation(
                0, -textWidth,
                0, 0);
        mAnimation.setDuration(10000);    // Set custom duration.
        mAnimation.setStartOffset(1000);    // Set custom offset.
        mAnimation.setRepeatMode(Animation.RESTART);    // This will animate text back ater it reaches end.
        mAnimation.setRepeatCount(Animation.INFINITE);    // Infinite animation.

        mTextView.startAnimation(mAnimation);
    }
}

private int getDisplayWidth(Context context) {
    int displayWidth;

    WindowManager windowManager = (WindowManager)context.getSystemService(
            Context.WINDOW_SERVICE);
    Display display = windowManager.getDefaultDisplay();
    Point screenSize = new Point();

    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(screenSize);
        displayWidth = screenSize.x;
    } else {
        displayWidth = display.getWidth();
    }

    return displayWidth;
}

private int getTextViewWidth(TextView textView) {
    textView.measure(0, 0);    // Need to set measure to (0, 0).
    return textView.getMeasuredWidth();
}

And start the animation with:

animateTextView(txtView);

Note: there is no more need for the customized TextView, just use a normal TextView.


问:
Fill out video file attributes
I have a large collection of video files, which have missing atributes like length, resolution, bitrate etc. I would like to fill those out somehow but im not sure what solution to use. It would take ages by hand but i'd rather see if a program can do it first. I tried searching for a solution but didnt find anything substantial.

The reason why, is becuase im trying to filter out the videos by atributes. If a vid is shorter than 30 minutes, i delete it. Can sort with the windows explorer, which cant do that if the atributes are missing.

答:
Since you asked this on StackOverflow and not on SuperUser I'm going to answer this as a programming question.

Those properties are provided by the Windows Property System. It is possible to write your own property provider and overwrite the system default provider registration but this is a fair amount of work if all you want to do is sort some files.

Title: Fill out video file attributes


问:
update column values with the other column values using inner join in postgres
While implementing the below code, I got error message, "relation "n" does not exist"

```<code>UPDATE n
    SET n.var_a = a.var_b
    FROM table_n n INNER JOIN
         table_a a
         ON n.var_c = a.var_d AND lower(n.var_e) = lower(a.var_f);
</code>```

However, the below code is working. What part should be corrected in the above code? I also tried with using full table names.

```<code>SELECT *
FROM table_n n INNER JOIN
     table_a a
     ON n.var_c = a.var_d AND lower(n.var_e) = lower(a.var_f);
</code>```

答:
You are pretty close.  This is the correct syntax for Postgres:

```<code>UPDATE table_n n
    SET var_a = a.var_b
    FROM table_a a
    WHERE n.var_c = a.var_d AND lower(n.var_e) = lower(a.var_f);
</code>```

In Postgres, you need to specify the table being updated in the UPDATE clause.  You can give it an alias, but aliases from the FROM clause are not recognized (hence your error).

Body:
While implementing the below code, I got error message, "relation "n" does not exist"

UPDATE n
    SET n.var_a = a.var_b
    FROM table_n n INNER JOIN
         table_a a
         ON n.var_c = a.var_d AND lower(n.var_e) = lower(a.var_f);

However, the below code is working. What part should be corrected in the above code? I also tried with using full table names.

SELECT *
FROM table_n n INNER JOIN
     table_a a
     ON n.var_c = a.var_d AND lower(n.var_e) = lower(a.var_f);

Body:
You are pretty close.  This is the correct syntax for Postgres:

UPDATE table_n n
    SET var_a = a.var_b
    FROM table_a a
    WHERE n.var_c = a.var_d AND lower(n.var_e) = lower(a.var_f);

In Postgres, you need to specify the table being updated in the UPDATE clause.  You can give it an alias, but aliases from the FROM clause are not recognized (hence your error).


问:
Getting multiple strings as inputs
The Question is to take three names as input and check whether the 4th input is the first letter of one of those three names.
*It needs to be only of alpha type and no other.

Sample Input:

```<code>@ON SNOW
ARYA STARK
HODOR
@
</code>```

Output:

```<code>NO
</code>```

My code:

```<code>#include <stdio.h>
#include <ctype.h>
int main(){
    char s1[100],s2[100],s3[100];
    char ch[1];
    scanf("%[^\n]s",s1);
    scanf("%[^\n]s",s2);
    scanf("%[^\n]s",s3);
    scanf("%s",ch);
    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");
}
</code>```

As I figured out that gets() no longer works, I tried scanf("%s",s1);.
But since it does not store the calude after the whitespace " ", I tried this scanf("%[^\n]s",s1);. But the scanning stops at the first name itself.

```<code>John Player
NO
</code>```

What is the way to store multiple strings in a char array without using loops and only using branching??

答:
Now before getting to the specified problem lets see what the actual problem is:

Problem with scanf()

The problem with scanf() is that it is really bad at managing overflows. And in case of chars or char sequences the newline character is read on the press of enter key in the subsequent scanning. There are numerous instances on SO that concern this problem. scanf() leaves the new line char in buffer? and Problems with scanf

Problem with gets()

The biggest drawback is that here you need to know the size of input before-hand. If you know your input extremely well, you may use it (Still I won't recommend). Why is the gets function so dangerous that it should not be used?

Problem with fgets()

There are two really common problems with fgets()

The syntax of fgets() is:

```<code>      char *fgets(char *restrict s, int n, FILE *restrict stream);`
</code>```

and generally used like

```<code>      fgets(char_array,100,stdin)
</code>```

First problem arises when the input is bigger than the integer n provided in the fgets() second parameter. When the input in the buffer is bigger than n it will strip off 1st n chars and allocate it the char pointer which might be a char array. But what about remaining chars? They still are there in the input buffer and will be allocated to next fgets(). Messing things up.

Second problem is that every time a new line feed is allocated to the end of char sequence when the input is smaller than the int n-1.

But if we think for a while the problems with fgets() can be tackled with a simple trick.

Just check for the last character in the char sequence which has been recently allocated. If it is new line, replace it by NULL. Else we know that the input was more than that int provided inside fgets(). So all we have to do is eat up the remaining chars in the input buffer.

Here is an example:

```<code>   char str1[5];
   char str2[5];
   fgets(str1,5,stdin);

   if(strlen(str1)>0){//to avoid Undefined Behavior in case of null byte input

       if(str1[strlen(str1)-1]=='\n'){

           str1[strlen(str1)-1]='\0';
       }
       else{

           while((getchar())!='\n');//eating the remaing chars in the buffer
       }
   }

   fgets(str2,5,stdin);

   if(strlen(str2)>0){

      if(str2[strlen(str2)-1]=='\n'){

         str2[strlen(str2)-1]='\0';

      }
      else{

         while((getchar())!='\n');
      }

   }
   printf("\n1.%s\n2.%s",str1,str2);
</code>```

You could even convert strings you got using fgets to float and integers using things like strol or sscanf, but beware they may not show independent behavior.

Now coming back to the solution to your problem:

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

int main(){
    char s1[100],s2[100],s3[100];
    char ch[2];//make ch atleast 2 char wide

    fgets(s1,100,stdin);
     if(strlen(s1)>0){

          if(s1[strlen(s1)-1]=='\n'){

             s1[strlen(s1)-1]='\0';

          }
          else{

             while((getchar())!='\n');
          }

    }

   fgets(s2,100,stdin);
     if(strlen(s2)>0){

          if(s2[strlen(s2)-1]=='\n'){

             s2[strlen(s2)-1]='\0';

          }
          else{

             while((getchar())!='\n');
          }

    }

   fgets(s3,100,stdin);
     if(strlen(s3)>0){

          if(s3[strlen(s3)-1]=='\n'){

             s3[strlen(s3)-1]='\0';

          }
          else{

             while((getchar())!='\n');
          }

    }

    fgets(ch,2,stdin);
      if(strlen(ch)>0){

          if(ch[strlen(ch)-1]=='\n'){

              ch[strlen(ch)-1]='\0';

          }
          else{

              while((getchar())!='\n');
          }

     }

    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");

        return 0;
}
</code>```

Title: Getting multiple strings as inputs

Body:
The Question is to take three names as input and check whether the 4th input is the first letter of one of those three names.
*It needs to be only of alpha type and no other.

Sample Input:

@ON SNOW
ARYA STARK
HODOR
@

Output:

NO

My code:

#include <stdio.h>
#include <ctype.h>
int main(){
    char s1[100],s2[100],s3[100];
    char ch[1];
    scanf("%[^\n]s",s1);
    scanf("%[^\n]s",s2);
    scanf("%[^\n]s",s3);
    scanf("%s",ch);
    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");
}

As I figured out that gets() no longer works, I tried scanf("%s",s1);.
But since it does not store the calude after the whitespace " ", I tried this scanf("%[^\n]s",s1);. But the scanning stops at the first name itself.

John Player
NO

What is the way to store multiple strings in a char array without using loops and only using branching??

Body:
Now before getting to the specified problem lets see what the actual problem is:

Problem with scanf()

The problem with scanf() is that it is really bad at managing overflows. And in case of chars or char sequences the newline character is read on the press of enter key in the subsequent scanning. There are numerous instances on SO that concern this problem. scanf() leaves the new line char in buffer? and Problems with scanf

Problem with gets()

The biggest drawback is that here you need to know the size of input before-hand. If you know your input extremely well, you may use it (Still I won't recommend). Why is the gets function so dangerous that it should not be used?

Problem with fgets()

There are two really common problems with fgets()

The syntax of fgets() is:

      char *fgets(char *restrict s, int n, FILE *restrict stream);`

and generally used like

      fgets(char_array,100,stdin)

First problem arises when the input is bigger than the integer n provided in the fgets() second parameter. When the input in the buffer is bigger than n it will strip off 1st n chars and allocate it the char pointer which might be a char array. But what about remaining chars? They still are there in the input buffer and will be allocated to next fgets(). Messing things up.

Second problem is that every time a new line feed is allocated to the end of char sequence when the input is smaller than the int n-1.

But if we think for a while the problems with fgets() can be tackled with a simple trick.

Just check for the last character in the char sequence which has been recently allocated. If it is new line, replace it by NULL. Else we know that the input was more than that int provided inside fgets(). So all we have to do is eat up the remaining chars in the input buffer.

Here is an example:

   char str1[5];
   char str2[5];
   fgets(str1,5,stdin);

   if(strlen(str1)>0){//to avoid Undefined Behavior in case of null byte input

       if(str1[strlen(str1)-1]=='\n'){

           str1[strlen(str1)-1]='\0';
       }
       else{

           while((getchar())!='\n');//eating the remaing chars in the buffer
       }
   }

   fgets(str2,5,stdin);

   if(strlen(str2)>0){

      if(str2[strlen(str2)-1]=='\n'){

         str2[strlen(str2)-1]='\0';

      }
      else{

         while((getchar())!='\n');
      }

   }
   printf("\n1.%s\n2.%s",str1,str2);

You could even convert strings you got using fgets to float and integers using things like strol or sscanf, but beware they may not show independent behavior.

Now coming back to the solution to your problem:

#include <stdio.h>
#include <string.h>

int main(){
    char s1[100],s2[100],s3[100];
    char ch[2];//make ch atleast 2 char wide

    fgets(s1,100,stdin);
     if(strlen(s1)>0){

          if(s1[strlen(s1)-1]=='\n'){

             s1[strlen(s1)-1]='\0';

          }
          else{

             while((getchar())!='\n');
          }

    }

   fgets(s2,100,stdin);
     if(strlen(s2)>0){

          if(s2[strlen(s2)-1]=='\n'){

             s2[strlen(s2)-1]='\0';

          }
          else{

             while((getchar())!='\n');
          }

    }

   fgets(s3,100,stdin);
     if(strlen(s3)>0){

          if(s3[strlen(s3)-1]=='\n'){

             s3[strlen(s3)-1]='\0';

          }
          else{

             while((getchar())!='\n');
          }

    }

    fgets(ch,2,stdin);
      if(strlen(ch)>0){

          if(ch[strlen(ch)-1]=='\n'){

              ch[strlen(ch)-1]='\0';

          }
          else{

              while((getchar())!='\n');
          }

     }

    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");

        return 0;
}


问:
Query not working as intended in Laravel
In order to get  entries from a certain period of time ( Last week, last month) i have the following code in my Controller:

```<code>$data=Pedido::where([
                ['sitio_id','=',$idSitio],['fechaPedido','>=','CURDATE()-INTERVAl '.$rango.' DAY']
                ])
        ->latest('fechaPedido')
        ->get();

        echo json_encode($data);
</code>```

now, when i execute it in my aplication, it returns all the entries in the Table "Pedidos", regardless of the  day interval i give it to it. I.E The site had no new entries in Pedidos since 24 days, so by week (7 days) it should return null.

Though when I ran a similar SQL query as below against my datqbase, it worked perfectly.

```<code>select * from `pedido` where (`sitio_d` = 1 and `fechaPedido` >= CURDATE()-INTERVAl 7 DAY) order by `fechaPedido` desc
</code>```

When i run it in the PHPMyAdmin, it returns an empty result, and if i change the interval there, it gives me the correct output.

But in the web app, it always returns all the entries in the table, regardless of the interval.

Tried working around with it using DB::raw, but it threw an empty result, regardless of the date.

Is there a reason of why this its not working? Or a way to check the raw SQL laravel its sending to the database?

Im Using Laravel 5.4, and MySql

答:
I would imagine the reason your query isn't working correctly is because you need to escape 'CURDATE()-INTERVAl '.$rango.' DAY'.

You can either use DB::raw():

```<code>$data =  Pedido::where('sitio_id', $idSitio)
    ->where('fechaPedido', '>=', DB::raw('CURDATE()-INTERVAl ' . $rango . ' DAY'))
    ->latest('fechaPedido')
    ->get();
</code>```

whereRaw:

```<code>$data =  Pedido::where('sitio_id', $idSitio)
    ->whereRaw('fechaPedido >= CURDATE()-INTERVAl ' . $rango . ' DAY')
    ->latest('fechaPedido')
    ->get();
</code>```

Or even just use a carbon instance to pass the date

```<code>$data =  Pedido::where('sitio_id', $idSitio)
    ->where('fechaPedido', '>=', \Carbon\Carbon::now()->subDays($rango)->startOfDay())
    ->latest('fechaPedido')
    ->get();
</code>```

Also, Eloquent will return a collection in this case so you can do $data->toJson() instead of json_encode($data).

Furthermore, if you're just going to return the json from the Route / Controller method you can just do return $data; and Laravel will convert it for you.

Hope this helps!

Body:
In order to get  entries from a certain period of time ( Last week, last month) i have the following code in my Controller:

$data=Pedido::where([
                ['sitio_id','=',$idSitio],['fechaPedido','>=','CURDATE()-INTERVAl '.$rango.' DAY']
                ])
        ->latest('fechaPedido')
        ->get();

        echo json_encode($data);

now, when i execute it in my aplication, it returns all the entries in the Table "Pedidos", regardless of the  day interval i give it to it. I.E The site had no new entries in Pedidos since 24 days, so by week (7 days) it should return null.

Though when I ran a similar SQL query as below against my datqbase, it worked perfectly.

select * from `pedido` where (`sitio_d` = 1 and `fechaPedido` >= CURDATE()-INTERVAl 7 DAY) order by `fechaPedido` desc

When i run it in the PHPMyAdmin, it returns an empty result, and if i change the interval there, it gives me the correct output.

But in the web app, it always returns all the entries in the table, regardless of the interval.

Tried working around with it using DB::raw, but it threw an empty result, regardless of the date.

Is there a reason of why this its not working? Or a way to check the raw SQL laravel its sending to the database?

Im Using Laravel 5.4, and MySql

Body:
I would imagine the reason your query isn't working correctly is because you need to escape 'CURDATE()-INTERVAl '.$rango.' DAY'.

You can either use DB::raw():

$data =  Pedido::where('sitio_id', $idSitio)
    ->where('fechaPedido', '>=', DB::raw('CURDATE()-INTERVAl ' . $rango . ' DAY'))
    ->latest('fechaPedido')
    ->get();

whereRaw:

$data =  Pedido::where('sitio_id', $idSitio)
    ->whereRaw('fechaPedido >= CURDATE()-INTERVAl ' . $rango . ' DAY')
    ->latest('fechaPedido')
    ->get();

Or even just use a carbon instance to pass the date

$data =  Pedido::where('sitio_id', $idSitio)
    ->where('fechaPedido', '>=', \Carbon\Carbon::now()->subDays($rango)->startOfDay())
    ->latest('fechaPedido')
    ->get();

Also, Eloquent will return a collection in this case so you can do $data->toJson() instead of json_encode($data).

Furthermore, if you're just going to return the json from the Route / Controller method you can just do return $data; and Laravel will convert it for you.

Hope this helps!


问:
C# How I can make a sum wih Console.Readline
The idea that I have is:

Set some variables with its numbers like int a=15, b=10, c=1

Then with the use of Console.Readline be able to do the sum, for example a+a+b wrote on the console must show 40.

I tried Console.WriteLine("sum: {0}",Console.Readline()); I could upload a image with the idea if this it's not enought sorry for my english.

答:
```<code>int sum = 0;
var values = new Dictionary<string, int>
{
    { "a", 1 },
    { "b", 2 },
    { "c", 3 }
};
var input = Console.ReadLine().Split('+');
foreach (string variable in input)
{
    sum += values.ContainsKey(variable) ? values[variable] : 0;
}
Console.WriteLine("Sum: {0}", sum);
</code>```

For example:

```<code>a+b+c
Sum: 6
</code>```

Body:
int sum = 0;
var values = new Dictionary<string, int>
{
    { "a", 1 },
    { "b", 2 },
    { "c", 3 }
};
var input = Console.ReadLine().Split('+');
foreach (string variable in input)
{
    sum += values.ContainsKey(variable) ? values[variable] : 0;
}
Console.WriteLine("Sum: {0}", sum);

For example:

a+b+c
Sum: 6


问:
How to declare WCF subtype(knownTypes) without having to reference it
We have a server that can return a "configuration", this configuration is a big and complex hierachy of classes.

Our application works by "packages", meaning that we have a "common" base, and then there is part of the application that will not be even installed.

It means that the configurations classes are not all in the same project, and we often have structure like:

```<code>public class SomeObject{
   public IEnumerable<ISomeObjectChild> Childs{get;set;}
}
public interface SomeObjectChild{
   //[...]
}
</code>```

And in some other project, have some class that implement them:

```<code>public class SomeChildImplementation: ISomeObjectChild{
   //[...]
}
</code>```

There is factory to instantiate those kind of childs and everything is working fine.

Now we have to transfer over the network this kind of configuration, using WCF.

My issue is that I know I should indicate what could be the types potentially implementing the ISomeObjectChild. I know that usually, we should declare them with [KnownType(typeof(SomeChildImplementation))], but it is not possible:

This class doesn't know all its possible childs

This class cannot even reference thoses childs

So how could I indicate what are the possible implementations?

(in this case it's with an interface, but I've some others cases with abstract classes).

答:
KnownTypesAttribute has another constructor that can be used to specify a method that will return an array of KnownTypes, see here

The implementation of this method can depend on how dynamic you want to be. Either configure the types you want to support in some configuration file or use System.Reflection to scan for classes that implement ISomeObjectChild

Body:
We have a server that can return a "configuration", this configuration is a big and complex hierachy of classes.

Our application works by "packages", meaning that we have a "common" base, and then there is part of the application that will not be even installed.

It means that the configurations classes are not all in the same project, and we often have structure like:

public class SomeObject{
   public IEnumerable<ISomeObjectChild> Childs{get;set;}
}
public interface SomeObjectChild{
   //[...]
}

And in some other project, have some class that implement them:

public class SomeChildImplementation: ISomeObjectChild{
   //[...]
}

There is factory to instantiate those kind of childs and everything is working fine.

Now we have to transfer over the network this kind of configuration, using WCF.

My issue is that I know I should indicate what could be the types potentially implementing the ISomeObjectChild. I know that usually, we should declare them with [KnownType(typeof(SomeChildImplementation))], but it is not possible:

This class doesn't know all its possible childs

This class cannot even reference thoses childs

So how could I indicate what are the possible implementations?

(in this case it's with an interface, but I've some others cases with abstract classes).


问:
Best way for ASP.NET MVC routing for not-so common scenarios?
UPDATE - 1/21/09:

The only way I've been able to get this working moderately well is to create routes that have additional path info... in other words instead of http://company.com/myDepartment/myTeam/action/id, the routes need to be built to handle paths
like http://company.com/department/myDepartment/team/myTeam and so on.

END UPDATE - 1/21/09:

I have two possible URL conventions that I need to be able to route to the same controllers/views

http://team.department.company.com/Action/id

http://department.company.com/Action/id

http://company.com/Action/id

The above has been pretty easy to handle, since the department/team aliases are in the hostname of the Uri.

However, when I want to implement the following, I've been unable to get it working satisfactorily:

http://company.com/department/team/Action/id

http://company.com/department/Action/id

http://company.com/Action/id

Here are the routes I've defined:

```<code>routes.MapRoute("departmentAndTeam1", "{departmentId}/{teamId}/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

routes.MapRoute("departmentAndTeam2", "{departmentId}/{teamId}/{controller}/{action}", new { controller = "Home", action = "Index" });

routes.MapRoute("departmentAndTeam3", "{departmentId}/{teamId}/{controller}", new { controller = "Home", action = "Index" });

routes.MapRoute("department", "{department}/{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = ""});

routes.MapRoute("departmentAndTeam4", "{departmentId}/{teamId}/", new { controller = "Home", action = "Index"});

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });
</code>```

The problem I'm having is now every action method in my controllers require a departmentId & teamId parameter.  I would really prefer just to be able to "pre-process" the department/team id values in the base controller class that I've got in the OnActionExecuting event handler.  Am I barking up the wrong tree?  Do I need to implement my own Mvc Route handler?

Note:  This is replacing a legacy app and the URL formats need to be kept/maintained.

EDIT:  First off, thanks for the responses so far.  Based on the responses I've received I think I've not been clear enough on one point.  This is (loosely) what my controller looks like:

```<code>public class ControllerBase : Controller
{
    DepartmentDTO department;
    TeamDTO team;
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        PopulateDept(filterContext.ActionParameters("departmentId");
        PopulateTeam(filterContext.ActionParameters("teamId");
    }
}
</code>```

However, with this scheme, all controllers that inherit from this class (and are routed appropriately with the routes listed above) expect (what I perceive to be redundant/uneeded) parameters in their action handlers.  I want to avoid having each handler require these "extra" parameters and am looking for suggestions.

Thanks!
-Giorgio

答:
First off, you don't need departmentAndTeam2 or departmentAndTeam3. departmentAndTeam1 can handle it because it has the defaults for controller, action and id.

Another thing I notice is that none of your example URLs have the controller specified in them. In that case, leave it out of the route and just leave it as the default. eg

for the URL

http://company.com/department/team/Action/id

use the route

```<code>routes.MapRoute("departmentAndTeam1", "{departmentId}/{teamId}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });
</code>```

Notice how "controller" will always be "Home" because it's never mentioned in the URL.

For the actions and URLs that you don't want to specify the department and team IDs, they should just be passing by all the other routes and just using the Default route. The fact that they aren't means that they are getting caught by one of the earlier routes. I think if you fix the earlier route's problems then it should fix the problems of needing the extra IDs.

Finally, if you are still haveing trouble, try using an MVC route debugger like this one from Phil Haacked http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx. I've used it to work out the problems with some of my routes and it is really helpful to see what it is actually doing and runtime.

OwnerDisplayName: Giorgio Galante

Body:
UPDATE - 1/21/09:

The only way I've been able to get this working moderately well is to create routes that have additional path info... in other words instead of http://company.com/myDepartment/myTeam/action/id, the routes need to be built to handle paths
like http://company.com/department/myDepartment/team/myTeam and so on.

END UPDATE - 1/21/09:

I have two possible URL conventions that I need to be able to route to the same controllers/views

http://team.department.company.com/Action/id

http://department.company.com/Action/id

http://company.com/Action/id

The above has been pretty easy to handle, since the department/team aliases are in the hostname of the Uri.

However, when I want to implement the following, I've been unable to get it working satisfactorily:

http://company.com/department/team/Action/id

http://company.com/department/Action/id

http://company.com/Action/id

Here are the routes I've defined:

routes.MapRoute("departmentAndTeam1", "{departmentId}/{teamId}/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

routes.MapRoute("departmentAndTeam2", "{departmentId}/{teamId}/{controller}/{action}", new { controller = "Home", action = "Index" });

routes.MapRoute("departmentAndTeam3", "{departmentId}/{teamId}/{controller}", new { controller = "Home", action = "Index" });

routes.MapRoute("department", "{department}/{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = ""});

routes.MapRoute("departmentAndTeam4", "{departmentId}/{teamId}/", new { controller = "Home", action = "Index"});

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

The problem I'm having is now every action method in my controllers require a departmentId & teamId parameter.  I would really prefer just to be able to "pre-process" the department/team id values in the base controller class that I've got in the OnActionExecuting event handler.  Am I barking up the wrong tree?  Do I need to implement my own Mvc Route handler?

Note:  This is replacing a legacy app and the URL formats need to be kept/maintained.

EDIT:  First off, thanks for the responses so far.  Based on the responses I've received I think I've not been clear enough on one point.  This is (loosely) what my controller looks like:

public class ControllerBase : Controller
{
    DepartmentDTO department;
    TeamDTO team;
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        PopulateDept(filterContext.ActionParameters("departmentId");
        PopulateTeam(filterContext.ActionParameters("teamId");
    }
}

However, with this scheme, all controllers that inherit from this class (and are routed appropriately with the routes listed above) expect (what I perceive to be redundant/uneeded) parameters in their action handlers.  I want to avoid having each handler require these "extra" parameters and am looking for suggestions.

Thanks!
-Giorgio

LastEditorDisplayName: Giorgio Galante

Body:
First off, you don't need departmentAndTeam2 or departmentAndTeam3. departmentAndTeam1 can handle it because it has the defaults for controller, action and id.

Another thing I notice is that none of your example URLs have the controller specified in them. In that case, leave it out of the route and just leave it as the default. eg

for the URL

http://company.com/department/team/Action/id

use the route

routes.MapRoute("departmentAndTeam1", "{departmentId}/{teamId}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

Notice how "controller" will always be "Home" because it's never mentioned in the URL.

For the actions and URLs that you don't want to specify the department and team IDs, they should just be passing by all the other routes and just using the Default route. The fact that they aren't means that they are getting caught by one of the earlier routes. I think if you fix the earlier route's problems then it should fix the problems of needing the extra IDs.

Finally, if you are still haveing trouble, try using an MVC route debugger like this one from Phil Haacked http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx. I've used it to work out the problems with some of my routes and it is really helpful to see what it is actually doing and runtime.


答:
Try something like this (run code snippet to see result):

var base_str = 'Billy Bob Joe whatever';

//try here limit 1 , 2, 3 and see console.log result
var base_split = base_str.split(' ',2);

var second_str = base_split.join(' ');

var second_split = base_str.split(second_str);

base_split.push(second_split[1].trim());

console.log(base_split);```

Title: Split string to maximum length and append the rest to the last array item

Body:
Is there a way for me to split a string into an array and limit to x and if there are more parts than the limit append to the last array item?

So, for example I have

'Billy Bob Joe'.split(' ', 2) // Outputs ["Billy", "Bob"]

I would like to output

["Billy", "Bob Joe"]

Is there a way for this to be easily done in JavaScript?


问:
When to use dequeueReusableCellWithIdentifier vs dequeueReusableCellWithIdentifier : forIndexPath
There are two overloads for dequeueReusableCellWithIdentifier and I'm trying to determine when should I use one vs the other?

The apple docs regarding the forIndexPath function states, "This method uses the index path to perform additional configuration based on the cell’s position in the table view."

I'm not sure how to interpret that though?

答:
For short:

dequeueReusableCell(withIdentifier, for) only works with prototype
  cells. If you tried to use it when the prototype cell is absence, it would crash the app.

Hollemans M. 2016, Chapter 2 Checklist, IOS Apprentice (5th Edition). pp: 156.


问:
Set time to stop in activity indicator while loading if it takes time to long to response swift 3
Swift 3 iOS 10: I want set the time interval to stop activity indicator if it's too long to responsd. When there is no response, it will be loading forever. Therefor, how can I stop it in the middle of the way?

答:
if </p>

```<code>activityIndicator.hidesWhenStopped = true
</code>```

<p>, then the moment you stop the activityIndicator, it should work, regardless of when. Otherwise provide some code so I can see the problem.</p>

Body:
if

activityIndicator.hidesWhenStopped = true

, then the moment you stop the activityIndicator, it should work, regardless of when. Otherwise provide some code so I can see the problem.


问:
Run two different versions of chrome using selenium (Python)
I have a scenario to run different versions of chrome in windows (for now let us consider only two). I have found the following way to run an instance of chrome:

```<code>chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy)
driver = webdriver.Chrome(
    chrome_options=chrome_options
)
</code>```

I have default chrome and another version (located in Downloads directory). How do I run any desired version?

EDIT:

I have some blogs written here and here. Hope this helps someone.

答:
One way is to define the location in the capabilities with the Options class:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
options.binary_location = r'C:/chromium-48/chrome.exe'
driver = webdriver.Chrome(chrome_options=options)
```

<p>or with <code>DesiredCapabilities</code>:</p>

<pre class="lang-py prettyprint-override"><code>from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

capa = DesiredCapabilities.CHROME;
capa['chromeOptions'] = {
  'binary': r'C:/chromium-48/chrome.exe',
  'args': []
}

driver = webdriver.Chrome(desired_capabilities=capa)
</code>```

But if you are looking for a scalable solution, then you should setup a grid with the different versions:

Start the hub:

java -jar selenium-server-standalone-2.53.1.jar -role hub -host 0.0.0.0 -port 4444
```

<ul>
<li>Start a node for version 48:</li>
</ul>

<pre class="lang-bash prettyprint-override"><code>java -jar selenium-server-standalone-2.53.1.jar
 -role node
 -hub http://localhost:4444/grid/register
 -browser platform=WINDOWS,browserName=chrome,version=48,chrome_binary="C:/chromium-48/chrome.exe"
</code>```

Start a node for version 54:

java -jar selenium-server-standalone-2.53.1.jar
 -role node
 -hub http://localhost:4444/grid/register
 -browser platform=WINDOWS,browserName=chrome,version=54,chrome_binary="C:/chromium-54/chrome.exe"
```

<p>You can then choose the version directly in the capabilities:</p>

<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
capa = {'browserName': 'chrome', 'version': '48', 'platform': 'ANY'}
driver = webdriver.Remote(command_executor='http://localhost:4444/wd/hub', desired_capabilities=capa)
</code>```

Body:
I have a scenario to run different versions of chrome in windows (for now let us consider only two). I have found the following way to run an instance of chrome:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy)
driver = webdriver.Chrome(
    chrome_options=chrome_options
)

I have default chrome and another version (located in Downloads directory). How do I run any desired version?

EDIT:

I have some blogs written here and here. Hope this helps someone.

Body:
One way is to define the location in the capabilities with the Options class:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
options.binary_location = r'C:/chromium-48/chrome.exe'
driver = webdriver.Chrome(chrome_options=options)

or with DesiredCapabilities:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

capa = DesiredCapabilities.CHROME;
capa['chromeOptions'] = {
  'binary': r'C:/chromium-48/chrome.exe',
  'args': []
}

driver = webdriver.Chrome(desired_capabilities=capa)

But if you are looking for a scalable solution, then you should setup a grid with the different versions:

Start the hub:

java -jar selenium-server-standalone-2.53.1.jar -role hub -host 0.0.0.0 -port 4444

Start a node for version 48:

java -jar selenium-server-standalone-2.53.1.jar
 -role node
 -hub http://localhost:4444/grid/register
 -browser platform=WINDOWS,browserName=chrome,version=48,chrome_binary="C:/chromium-48/chrome.exe"

Start a node for version 54:

java -jar selenium-server-standalone-2.53.1.jar
 -role node
 -hub http://localhost:4444/grid/register
 -browser platform=WINDOWS,browserName=chrome,version=54,chrome_binary="C:/chromium-54/chrome.exe"

You can then choose the version directly in the capabilities:

from selenium import webdriver
capa = {'browserName': 'chrome', 'version': '48', 'platform': 'ANY'}
driver = webdriver.Remote(command_executor='http://localhost:4444/wd/hub', desired_capabilities=capa)


问:
How to examine vsdo vars?
I would like to inspect the contents of vsyscall_gtod_data (all the time keeping related information that is needed to make clock_gettime() work).

I'm using gdb to single step through the assembly code of __vdso_clock_gettime() and I'm looking at the following section:

```<code>   0x00007ffff7ffaa71 <clock_gettime+129>:  cmp    eax,DWORD PTR [rbx]
   0x00007ffff7ffaa73 <clock_gettime+131>:  je     0x7ffff7ffaa47 <clock_gettime+87>
   0x00007ffff7ffaa75 <clock_gettime+133>:  jmp    0x7ffff7ffaa56 <clock_gettime+102>
   0x00007ffff7ffaa77 <clock_gettime+135>:  pause
   0x00007ffff7ffaa79 <clock_gettime+137>:  mov    r12d,DWORD PTR [rbx]
=> 0x00007ffff7ffaa7c <clock_gettime+140>:  test   r12b,0x1
   0x00007ffff7ffaa80 <clock_gettime+144>:  jne    0x7ffff7ffaa77 <clock_gettime+135>
   0x00007ffff7ffaa82 <clock_gettime+146>:  mov    eax,DWORD PTR [rip+0xffffffffffffd5fc]        # 0x7ffff7ff8084
   0x00007ffff7ffaa88 <clock_gettime+152>:  mov    DWORD PTR [rbp-0x1c],eax
   0x00007ffff7ffaa8b <clock_gettime+155>:  mov    rax,QWORD PTR [rip+0xffffffffffffd61e]        # 0x7ffff7ff80b0
   0x00007ffff7ffaa92 <clock_gettime+162>:  mov    QWORD PTR [rsi],rax
   0x00007ffff7ffaa95 <clock_gettime+165>:  mov    edx,DWORD PTR [rip+0xffffffffffffd5e9]        # 0x7ffff7ff8084
   0x00007ffff7ffaa9b <clock_gettime+171>:  mov    r10,QWORD PTR [rip+0xffffffffffffd616]        # 0x7ffff7ff80b8
   0x00007ffff7ffaaa2 <clock_gettime+178>:  cmp    edx,0x1
   0x00007ffff7ffaaa5 <clock_gettime+181>:  je     0x7ffff7ffabc0 <clock_gettime+464>
</code>```

That I believe is the assembly for the following C code (from linux-4.8.0/arch/x86/include/asm/vgtod.h):

```<code>static inline unsigned gtod_read_begin(const struct vsyscall_gtod_data *s)
{
    unsigned ret;

repeat:
    ret = ACCESS_ONCE(s->seq);
    if (unlikely(ret & 1)) {
        cpu_relax();
        goto repeat;
    }
    smp_rmb();
    return ret;
}
</code>```

(The assembly instruction pause matches the cpu_relax())

As I understand it struct vsyscall_gtod_data *s is held in rbx and the address is read in this instruction:

```<code>mov    r12d,DWORD PTR [rbx]
</code>```

Meaning that the debugged program can read this address, but when I try to examine it in gdb I get an error:

```<code>(gdb) x $rbx
0x7ffff7ff8080: Cannot access memory at address 0x7ffff7ff8080
(gdb)
</code>```

Any ideas of what's going on and how to examine that memory?

答:
I think you are trying to access a memory location that can be accessed only if you have "privilege level" 0 (OS level). Don't trust me on the name, I read it a couple of days ago on the Intel manual so I might get the jargon wrong, the concept should be right though.

I am not 100% sure that it would be enough to sudo, but trying will not hurt. I know some instruction counting registers have similar issues and they can be accessed from userspace if you sudo.

Title: How to examine vsdo vars?

Body:
I would like to inspect the contents of vsyscall_gtod_data (all the time keeping related information that is needed to make clock_gettime() work).

I'm using gdb to single step through the assembly code of __vdso_clock_gettime() and I'm looking at the following section:

   0x00007ffff7ffaa71 <clock_gettime+129>:  cmp    eax,DWORD PTR [rbx]
   0x00007ffff7ffaa73 <clock_gettime+131>:  je     0x7ffff7ffaa47 <clock_gettime+87>
   0x00007ffff7ffaa75 <clock_gettime+133>:  jmp    0x7ffff7ffaa56 <clock_gettime+102>
   0x00007ffff7ffaa77 <clock_gettime+135>:  pause
   0x00007ffff7ffaa79 <clock_gettime+137>:  mov    r12d,DWORD PTR [rbx]
=> 0x00007ffff7ffaa7c <clock_gettime+140>:  test   r12b,0x1
   0x00007ffff7ffaa80 <clock_gettime+144>:  jne    0x7ffff7ffaa77 <clock_gettime+135>
   0x00007ffff7ffaa82 <clock_gettime+146>:  mov    eax,DWORD PTR [rip+0xffffffffffffd5fc]        # 0x7ffff7ff8084
   0x00007ffff7ffaa88 <clock_gettime+152>:  mov    DWORD PTR [rbp-0x1c],eax
   0x00007ffff7ffaa8b <clock_gettime+155>:  mov    rax,QWORD PTR [rip+0xffffffffffffd61e]        # 0x7ffff7ff80b0
   0x00007ffff7ffaa92 <clock_gettime+162>:  mov    QWORD PTR [rsi],rax
   0x00007ffff7ffaa95 <clock_gettime+165>:  mov    edx,DWORD PTR [rip+0xffffffffffffd5e9]        # 0x7ffff7ff8084
   0x00007ffff7ffaa9b <clock_gettime+171>:  mov    r10,QWORD PTR [rip+0xffffffffffffd616]        # 0x7ffff7ff80b8
   0x00007ffff7ffaaa2 <clock_gettime+178>:  cmp    edx,0x1
   0x00007ffff7ffaaa5 <clock_gettime+181>:  je     0x7ffff7ffabc0 <clock_gettime+464>

That I believe is the assembly for the following C code (from linux-4.8.0/arch/x86/include/asm/vgtod.h):

static inline unsigned gtod_read_begin(const struct vsyscall_gtod_data *s)
{
    unsigned ret;

repeat:
    ret = ACCESS_ONCE(s->seq);
    if (unlikely(ret & 1)) {
        cpu_relax();
        goto repeat;
    }
    smp_rmb();
    return ret;
}

(The assembly instruction pause matches the cpu_relax())

As I understand it struct vsyscall_gtod_data *s is held in rbx and the address is read in this instruction:

mov    r12d,DWORD PTR [rbx]

Meaning that the debugged program can read this address, but when I try to examine it in gdb I get an error:

(gdb) x $rbx
0x7ffff7ff8080: Cannot access memory at address 0x7ffff7ff8080
(gdb)

Any ideas of what's going on and how to examine that memory?


问:
Split string to maximum length and append the rest to the last array item
Is there a way for me to split a string into an array and limit to x and if there are more parts than the limit append to the last array item?

So, for example I have

```<code>'Billy Bob Joe'.split(' ', 2) // Outputs ["Billy", "Bob"]
</code>```

I would like to output

```<code>["Billy", "Bob Joe"]
</code>```

Is there a way for this to be easily done in JavaScript?

答:
Here is what I came up with, but it's not super optimized

function explode(del, str, limit) {
  let items = str.split(del), r = []
  for(let i = 0; i < limit - 1; i++){ r.push(items.shift()) }
  r.push(items.join(' '))
  return r
}

console.log(explode(' ', 'Billy Bob Joe', 2));
console.log(explode(' ', 'a b c d e f g h', 4));```


问:
How do we use a Lookup table in Mule DataWeave
I would like to know how we can define our customer LookUpTable in DataWeave.

I am not able to find options to define custom LookUpTable

I am looking for some lookup options like how we do it in DataMapper as below

Can Someone help me with this

答:
Refer the below url's might be helpful- first link explains the way where datamapper used to have ( where in datamapper itself in table format you have defined the custom datas whereas in dataweave  externally create .csv or .txt for lookup and refer it via scripts

https://gandham38.wordpress.com/2016/08/19/dataweave-lookup-example/

Custom Lookup in dataweave

https://forums.mulesoft.com/questions/59409/how-to-properly-use-the-dataweave-lookup-function.html


问:
BufferedImage in java larger than 2^31 pixels
I need to create a very large image in java and so far I've been using the java.awt.image.BufferedImage class. But it seems that this class stores it's pixels with an int as it can not go past 2^31 pixels. I've thought about creating smaller images and stitching them together, but the problem is the photo editors I try like Adobe Photoshop can't even  import photos larger than 30,000 pixels in any dimension.

I've thought about making my own image class but I am not knowledgeable enough to make everything to go into that.

Any suggestions?
Thank You

答:
You'll probably struggle to load an image of that size memory because the memory footprint of an image of 2^31 x 1px would be:

```<code>2^31px * 1px * 4 bytes/px = 4,294,967,296 bytes = ~4.2 GB
</code>```

A 2^31px x 4px image would already consume more memory than most computers have. Stitching the images together is the correct design for such a situation. A simple solution would be to keep a multidimensional array of images and load them in and out of memory based on your requirements.

ImageMagick is a mature utility for processing images, and it can support very large image sizes. Since you say you want to write a large image file, I would suggest using the montage feature. Render parts of your fractal and save them to disk, then once rendering is finished, invoke the ImageMagick montage command from your program to generate the final large file.

Body:
You'll probably struggle to load an image of that size memory because the memory footprint of an image of 2^31 x 1px would be:

2^31px * 1px * 4 bytes/px = 4,294,967,296 bytes = ~4.2 GB

A 2^31px x 4px image would already consume more memory than most computers have. Stitching the images together is the correct design for such a situation. A simple solution would be to keep a multidimensional array of images and load them in and out of memory based on your requirements.

ImageMagick is a mature utility for processing images, and it can support very large image sizes. Since you say you want to write a large image file, I would suggest using the montage feature. Render parts of your fractal and save them to disk, then once rendering is finished, invoke the ImageMagick montage command from your program to generate the final large file.