问:
MemoryError does not cause program to quit
I have a Python3.4 (64-bit) program that is meant to load a lot of data (it takes about 15 Gb of disk space, but I discard half the columns) into a simple dict. The code is as follows:

```<code>print('Reading accessions', file=sys.stderr)
taxids = {}
taxfile = open('prot.accession2taxid')
taxfile.readline()
for line in taxfile:
    l = line.rstrip().split('\t')
    taxids[l[0]]=int(l[2])
with open('/dev/shm/taxids.pickle', mode='w') as pickle_file:
    pickle.dump(taxids, '/dev/shm/taxids.pickle')
    print('Dumped', file=sys.stderr)
</code>```

The file is, basically, a TSV:

```<code>[amorozov@node006 nr]$ head -n 3 prot.accession2taxid
accession       accession.version       taxid   gi
APZ74649        APZ74649.1      36984   1137646701
AQT41667        AQT41667.1      1686310 1150388099
</code>```

When the memory consumption, as measured by htop, reaches about 40 Gb (out of 64 Gb available), the following exception is printed to the console:

```<code>Traceback (most recent call last):
  File "../../scripts/rename_sequences.py", line 66, in <module>
    taxids[l[0]]=int(l[2])
MemoryError
</code>```

However, the script does not crash, and it even continues doing something. The single core it was running on is still 100% loaded, but no further output is generated, nor does the program continue, as file in /dev/shm/ is not generated. I understand that from a practical point of view the answer is "use SQL" (although I kinda hoped I'd manage to fit ~8 gig of plaintext into 64 gig of memory; maybe it leaks somewhere?), but what is even happening? The exception doesn't seem to get caught, but it doesn't crash the script either.

答: A hypothesis proposed by Rhomboid at reddit: the script actually does terminate, but termination takes a lot of time because GC takes some time to collect bazillion of objects in the dict. At the very least, it is supported by the fact that if I leave the process running, it does finish in several minutes.</p>

Body:
I have a Python3.4 (64-bit) program that is meant to load a lot of data (it takes about 15 Gb of disk space, but I discard half the columns) into a simple dict. The code is as follows:

print('Reading accessions', file=sys.stderr)
taxids = {}
taxfile = open('prot.accession2taxid')
taxfile.readline()
for line in taxfile:
    l = line.rstrip().split('\t')
    taxids[l[0]]=int(l[2])
with open('/dev/shm/taxids.pickle', mode='w') as pickle_file:
    pickle.dump(taxids, '/dev/shm/taxids.pickle')
    print('Dumped', file=sys.stderr)

The file is, basically, a TSV:

[amorozov@node006 nr]$ head -n 3 prot.accession2taxid
accession       accession.version       taxid   gi
APZ74649        APZ74649.1      36984   1137646701
AQT41667        AQT41667.1      1686310 1150388099

When the memory consumption, as measured by htop, reaches about 40 Gb (out of 64 Gb available), the following exception is printed to the console:

Traceback (most recent call last):
  File "../../scripts/rename_sequences.py", line 66, in <module>
    taxids[l[0]]=int(l[2])
MemoryError

However, the script does not crash, and it even continues doing something. The single core it was running on is still 100% loaded, but no further output is generated, nor does the program continue, as file in /dev/shm/ is not generated. I understand that from a practical point of view the answer is "use SQL" (although I kinda hoped I'd manage to fit ~8 gig of plaintext into 64 gig of memory; maybe it leaks somewhere?), but what is even happening? The exception doesn't seem to get caught, but it doesn't crash the script either.


来源: stackexchange

问:
Unable to Start the Name Node in hadoop
I am running the hadoop in my local system but while running ./start-all.sh command its running all functionality except Name Node while running it's getting connection refused and in log file prints below exception

```<code>java.io.ioexception : there appears to be a gap in the edit log, we expected txid 1, but got txid 291.
</code>```

Can You please help me.

答:
The metadata in Hadoop NN consists of:

fsimage: contains the complete state of the file system at a point in time

edit logs: contains each file system change (file creation/deletion/modification) that was made after the most recent fsimage.

If you list all files inside your NN workspace directory, you'll see files include:

```<code>fsimage_0000000000000000000 (fsimage)
fsimage_0000000000000000000.md5
edits_0000000000000003414-0000000000000003451 (edit logs, there're many ones with different name)
seen_txid (a separated file contains last seen transaction id)
</code>```

When NN starts, Hadoop will load fsimage and apply all edit logs, and meanwhile do a lot of consistency  checks, it'll abort if the check failed. Let's make it happen, I'll rm edits_0000000000000000001-0000000000000000002 from many of my edit logs in my NN workspace, and then try to sbin/start-dfs.sh, I'll get error message in log like:

```<code>java.io.IOException: There appears to be a gap in the edit log.  We expected txid 1, but got txid 3.
</code>```

So your error message indicates that your edit logs is inconsitent(may be corrupted or maybe some of them are missing). If you just want to play hadoop on your local and don't care its data, you could simply hadoop namenode -format to re-format it and start from beginning, otherwise you need to recovery your edit logs, from SNN or somewhere you backed up before.

ContentLicense: CC BY-SA 3.0

Title: Unable to Start the Name Node in hadoop

Body:
I am running the hadoop in my local system but while running ./start-all.sh command its running all functionality except Name Node while running it's getting connection refused and in log file prints below exception

java.io.ioexception : there appears to be a gap in the edit log, we expected txid 1, but got txid 291.

Can You please help me.

Body:
The metadata in Hadoop NN consists of:

fsimage: contains the complete state of the file system at a point in time

edit logs: contains each file system change (file creation/deletion/modification) that was made after the most recent fsimage.

If you list all files inside your NN workspace directory, you'll see files include:

fsimage_0000000000000000000 (fsimage)
fsimage_0000000000000000000.md5
edits_0000000000000003414-0000000000000003451 (edit logs, there're many ones with different name)
seen_txid (a separated file contains last seen transaction id)

When NN starts, Hadoop will load fsimage and apply all edit logs, and meanwhile do a lot of consistency  checks, it'll abort if the check failed. Let's make it happen, I'll rm edits_0000000000000000001-0000000000000000002 from many of my edit logs in my NN workspace, and then try to sbin/start-dfs.sh, I'll get error message in log like:

java.io.IOException: There appears to be a gap in the edit log.  We expected txid 1, but got txid 3.

So your error message indicates that your edit logs is inconsitent(may be corrupted or maybe some of them are missing). If you just want to play hadoop on your local and don't care its data, you could simply hadoop namenode -format to re-format it and start from beginning, otherwise you need to recovery your edit logs, from SNN or somewhere you backed up before.


问:
Clear all cookies from WebView
I am currently developing an application for Windows Phone 10 using UWP, in which I need a WebView that will set up several cookies in the process. The WebView can be instantiated many times, and I have noticed that the cookies do not get cleared on multiple instantiations, which makes it a bit difficult for my workflow (say, for instance, a user has to log in using the WebView, then when re-instantiating, the old state will be there).

I have tried using the clearTemporaryWebDataAsync to now avail. What is worse is that I don't know in advance the domains associated to the cookies, so I cannot do something like this:

```<code>HttpBaseProtocolFilter myFilter = new HttpBaseProtocolFilter();
HttpCookieManager cookieManager = myFilter.CookieManager;
HttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("https://url.com"));
foreach (HttpCookie cookie in myCookieJar)
{
cookieManager.DeleteCookie(cookie);
}
</code>```

Is there anything in the API that might help me wipe out all the cookies for the WebView, or at least get a list of them so that then I can use DeleteCookie on each?

答:
What is worse is that I don't know in advance the domains associated to the cookies, so I cannot do something like this:

AFAIK, there isn't a method for clearing cache data except ClearTemporaryWebDataAsync, but the code snippet you provided does clear cookies. For what you consider about don't know in advance the domains to the cookies, you may get the current navigating Uri by the WebViewNavigationStartingEventArgs of NavigationStarting event handle. For example,

```<code>private void WebViewControl2_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
    Uri gotouri = args.Uri;
    HttpBaseProtocolFilter myFilter = new HttpBaseProtocolFilter();
    HttpCookieManager cookieManager = myFilter.CookieManager;
    HttpCookieCollection myCookieJar = cookieManager.GetCookies(gotouri);
    foreach (HttpCookie cookie in myCookieJar)
    {
        cookieManager.DeleteCookie(cookie);
    }
}
</code>```

And this will clear the cookies of current Uri. But this will clear the cookies every time the WebView navigates. You may need to set a flag to ensure if the WebView is a new instance depending on your app logic.

Another thing, in apps compiled for Windows 10, WebView uses the Microsoft Edge rendering engine to display HTML content. Clear cookies of current WebView instance may also clear others, which is same as you found cookies still exists when you have a new instance.

ContentLicense: CC BY-SA 4.0

Title: Clear all cookies from WebView

Body:
I am currently developing an application for Windows Phone 10 using UWP, in which I need a WebView that will set up several cookies in the process. The WebView can be instantiated many times, and I have noticed that the cookies do not get cleared on multiple instantiations, which makes it a bit difficult for my workflow (say, for instance, a user has to log in using the WebView, then when re-instantiating, the old state will be there).

I have tried using the clearTemporaryWebDataAsync to now avail. What is worse is that I don't know in advance the domains associated to the cookies, so I cannot do something like this:

HttpBaseProtocolFilter myFilter = new HttpBaseProtocolFilter();
HttpCookieManager cookieManager = myFilter.CookieManager;
HttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("https://url.com"));
foreach (HttpCookie cookie in myCookieJar)
{
cookieManager.DeleteCookie(cookie);
}

Is there anything in the API that might help me wipe out all the cookies for the WebView, or at least get a list of them so that then I can use DeleteCookie on each?

Body:
What is worse is that I don't know in advance the domains associated to the cookies, so I cannot do something like this:

AFAIK, there isn't a method for clearing cache data except ClearTemporaryWebDataAsync, but the code snippet you provided does clear cookies. For what you consider about don't know in advance the domains to the cookies, you may get the current navigating Uri by the WebViewNavigationStartingEventArgs of NavigationStarting event handle. For example,

private void WebViewControl2_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
    Uri gotouri = args.Uri;
    HttpBaseProtocolFilter myFilter = new HttpBaseProtocolFilter();
    HttpCookieManager cookieManager = myFilter.CookieManager;
    HttpCookieCollection myCookieJar = cookieManager.GetCookies(gotouri);
    foreach (HttpCookie cookie in myCookieJar)
    {
        cookieManager.DeleteCookie(cookie);
    }
}

And this will clear the cookies of current Uri. But this will clear the cookies every time the WebView navigates. You may need to set a flag to ensure if the WebView is a new instance depending on your app logic.

Another thing, in apps compiled for Windows 10, WebView uses the Microsoft Edge rendering engine to display HTML content. Clear cookies of current WebView instance may also clear others, which is same as you found cookies still exists when you have a new instance.


问:
How to have a Text Area in my Web application?
I want to make a blog page in my web application. I want to have a large text area to enter atleast 300 words in my blog page. it should have spell check. making bold option. It should be like the s*ame window in StackOverFlow where am entering my question now*.

How to achieve this. Any suggestions Please?

答: Have a look at CKEditor. It is one of the best free editors i know of.</p>

ContentLicense: CC BY-SA 2.5


问:
What is difference between tf.variable_scope and variable_scope.variable_scope in Tensorflow?
I know what tf.variable_scope means as it is clearly stated in the document. But in this example, there is a variable_scope.variable_scope. And seems it has not been covered in the documentation. I wonder what is their difference?

答:
They are the same function. The reason it's prefixed with variable_scope (instead of tf) in the source code is simply because it is inside the tensorflow package, as opposed to outside (like you). If you browse around the source code more, you'll notice lots of familiar methods with unfamiliar dot-prefixes like that, and for the same reason.

This is not TensorFlow specific, it is just how one imports packages for files within the source code of a python module. If you're interested in learning more about this concept, look into the meaning of __init__.py files and how they're used in python.


问:
How to use readarray / mapfile on only a portion of a file?
I'm working with molecular coordinate files, where the first line is the number of atoms followed by a blank line, and each line following being the x, y, and z coordinates for a given atom.

```<code>7

O    0    -0.1   -1.5
H    0     0.8   -1.9
H    0     0.1   -0.5
N    0     0      1.5
H    0    -1      1.7
H   -0.8   0.4    1.9
H    0.8   0.4    1.9
</code>```

I would like to create an array where each element is a line of the file, so it would look something like this:

```<code>r1=(O    0    -0.1   -1.5)
r2=(H    0     0.8   -1.9)
</code>```

I would use the readarray or mapfile command, but I only want to make elements out of the 3rd through 10th rows. Is there a way to give those commands ranges?

答:
the syntax is simple, but note that the lines won't be split into arrays, the output will be a one dimensional array, where each line is an array element.

```<code>readarray -s 2 arr < file
echo ${arr[0]}
</code>```

will give

```<code>O 0 -0.1 -1.5
</code>```

to create a two dimensional array requires some additional code, however you can split each line when needed if you have a sequential program.

another approach is filtering the input file for the lines you're interested in (e.g. sed -n '3,10p' file)

Body:
I'm working with molecular coordinate files, where the first line is the number of atoms followed by a blank line, and each line following being the x, y, and z coordinates for a given atom.

7

O    0    -0.1   -1.5
H    0     0.8   -1.9
H    0     0.1   -0.5
N    0     0      1.5
H    0    -1      1.7
H   -0.8   0.4    1.9
H    0.8   0.4    1.9

I would like to create an array where each element is a line of the file, so it would look something like this:

r1=(O    0    -0.1   -1.5)
r2=(H    0     0.8   -1.9)

I would use the readarray or mapfile command, but I only want to make elements out of the 3rd through 10th rows. Is there a way to give those commands ranges?

Body:
the syntax is simple, but note that the lines won't be split into arrays, the output will be a one dimensional array, where each line is an array element.

readarray -s 2 arr < file
echo ${arr[0]}

will give

O 0 -0.1 -1.5

to create a two dimensional array requires some additional code, however you can split each line when needed if you have a sequential program.

another approach is filtering the input file for the lines you're interested in (e.g. sed -n '3,10p' file)


问:
The cheapest way to compare two sets of strings
I have to sets of strings

```<code>set 1:

    "hello"
    "world"
    "stackoverflow"

set 2:
    "world"
    "hello"
    "stackoverflow"
</code>```

Before I tried to compare the content, I know exactly that these two sets contain only unique values. So I am not thinking about java Set for unique test.

So in Java, what should be the cheapest way to compare these two sets? By cheapest, I mean memory like.

I know I can do ArrayList.contains() forLoop, is there a better way?

And I was told Java HashSet consumes 5 times more resources than ArrayList when containing same length of contents. Is that true?

UPDATE

I don't have sample for you, since this is just an idea came to my mind.

By two sets of strings, I meant literally set, this set can also be stored in Java ArrayList.

what I want

is to compare these two sets of string to know if they are containing the same contents. of course I know before the actions that they both containing unique contents.

UPDATE

Sorry, this is not a practical problem I ran across with. This is just an idea I am wondering about.

答:
I have absolutely no idea about the performance of this, but just to add a possible solution...

```<code>String[] a = {"hello","world","stackoverflow"};
String[] b = {"world","hello","stackoverflow"};
Arrays.sort(a);
Arrays.sort(b);
System.out.println(Arrays.equals(a,b) ? "same" : "different");
</code>```

Result:

```<code>same
</code>```

Body:
I have to sets of strings

set 1:

    "hello"
    "world"
    "stackoverflow"

set 2:
    "world"
    "hello"
    "stackoverflow"

Before I tried to compare the content, I know exactly that these two sets contain only unique values. So I am not thinking about java Set for unique test.

So in Java, what should be the cheapest way to compare these two sets? By cheapest, I mean memory like.

I know I can do ArrayList.contains() forLoop, is there a better way?

And I was told Java HashSet consumes 5 times more resources than ArrayList when containing same length of contents. Is that true?

UPDATE

I don't have sample for you, since this is just an idea came to my mind.

By two sets of strings, I meant literally set, this set can also be stored in Java ArrayList.

what I want

is to compare these two sets of string to know if they are containing the same contents. of course I know before the actions that they both containing unique contents.

UPDATE

Sorry, this is not a practical problem I ran across with. This is just an idea I am wondering about.

Body:
I have absolutely no idea about the performance of this, but just to add a possible solution...

String[] a = {"hello","world","stackoverflow"};
String[] b = {"world","hello","stackoverflow"};
Arrays.sort(a);
Arrays.sort(b);
System.out.println(Arrays.equals(a,b) ? "same" : "different");

Result:

same


问:
How do I call a class from another class(not inheritance) in Java?
I can't remember what it's called when another class's method in java for example in a main class you call the scanner class to scan in user input?</p>

答:
Here is a table of many UML relationships

http://publib.boulder.ibm.com/infocenter/rtnlhelp/v6r0m0/index.jsp?topic=/com.ibm.xtools.modeler.doc/topics/rreltyp.html


问:
Pandas dataframe group values in the order in which they appear
I have a dataframe that looks like this:

Would like to create a new dataframe that takes the values of A and B and arranges them like this:

答:
You will need to create a new column that is essentially a sub-index for each value in A.  Then you can sort on the sub-index.

```<code>df = pd.DataFrame([[1,40],[1,39],[1,73],
                   [2,58],[2,65],[2,22],
                   [3,9],[3,0],[3,21]], columns=list('AB'))

for a in df.A.unique():
    df.loc[df.index[df.A==a],'x'] = list(range(sum(df.A==a)))

df
# returns:
   A   B  x
0  1  40  0
1  1  39  1
2  1  73  2
3  2  58  0
4  2  65  1
5  2  22  2
6  3   9  0
7  3   0  1
8  3  21  2

df.sort_values(by=['x','A'])[['A','B']]
# returns:
   A   B
0  1  40
3  2  58
6  3   9
1  1  39
4  2  65
7  3   0
2  1  73
5  2  22
8  3  21
</code>```

Body:
You will need to create a new column that is essentially a sub-index for each value in A.  Then you can sort on the sub-index.

df = pd.DataFrame([[1,40],[1,39],[1,73],
                   [2,58],[2,65],[2,22],
                   [3,9],[3,0],[3,21]], columns=list('AB'))

for a in df.A.unique():
    df.loc[df.index[df.A==a],'x'] = list(range(sum(df.A==a)))

df
# returns:
   A   B  x
0  1  40  0
1  1  39  1
2  1  73  2
3  2  58  0
4  2  65  1
5  2  22  2
6  3   9  0
7  3   0  1
8  3  21  2

df.sort_values(by=['x','A'])[['A','B']]
# returns:
   A   B
0  1  40
3  2  58
6  3   9
1  1  39
4  2  65
7  3   0
2  1  73
5  2  22
8  3  21


问:
Why Is the Compiler Complaining About My Transform Argument to FlatMap?
I have defined a protocol and an Array extension. The compiler is reporting an error on the invocation of flatMap in the extension's encode method: Cannot convert value of type 'T?' to closure result type '_'

```<code>public protocol Encodable {
    typealias Properties = Dictionary<String, Any>
    func encode() -> Properties
    init?(_ properties: Properties?)
}

extension Array where Element : Encodable.Properties {
    func encode<T:Encodable>(type: T.Type) -> [T] {
        return flatMap{ T($0) } // <= Compiler Error
    }
}
</code>```

The compiler has obviously found the initializer defined in the Encodable protocol - T($0) will produce a T?.

flatMap has an appropriate overload which should produces a [T].

I have no idea what "closure result type '_'" might mean.

xcode 8.3 is using swift 3.1 (perhaps I should not have updated Xcode?)

Any ideas?

答:
Compiling your code in a small project, I can find another error:

```<code><unknown>:0: error: type 'Element' constrained to non-protocol type 'Encodable.Properties'
</code>```

So, the constraint Element : Encodable.Properties is invalid and Swift cannot find a suitable initializer for T($0). It is often found that Swift generates inappropriate diagnostics in case of issues related to type inference.

As far as I tested, this code compiles with Swift 3.1/Xcode 8.3:

```<code>extension Array where Element == Encodable.Properties {
    func encode<T:Encodable>(type: T.Type) -> [T] {
        return flatMap{ T($0) }
    }
}
</code>```

Body:
I have defined a protocol and an Array extension. The compiler is reporting an error on the invocation of flatMap in the extension's encode method: Cannot convert value of type 'T?' to closure result type '_'

public protocol Encodable {
    typealias Properties = Dictionary<String, Any>
    func encode() -> Properties
    init?(_ properties: Properties?)
}

extension Array where Element : Encodable.Properties {
    func encode<T:Encodable>(type: T.Type) -> [T] {
        return flatMap{ T($0) } // <= Compiler Error
    }
}

The compiler has obviously found the initializer defined in the Encodable protocol - T($0) will produce a T?.

flatMap has an appropriate overload which should produces a [T].

I have no idea what "closure result type '_'" might mean.

xcode 8.3 is using swift 3.1 (perhaps I should not have updated Xcode?)

Any ideas?

Body:
Compiling your code in a small project, I can find another error:

<unknown>:0: error: type 'Element' constrained to non-protocol type 'Encodable.Properties'

So, the constraint Element : Encodable.Properties is invalid and Swift cannot find a suitable initializer for T($0). It is often found that Swift generates inappropriate diagnostics in case of issues related to type inference.

As far as I tested, this code compiles with Swift 3.1/Xcode 8.3:

extension Array where Element == Encodable.Properties {
    func encode<T:Encodable>(type: T.Type) -> [T] {
        return flatMap{ T($0) }
    }
}


问:
Adjust ActiveCell.FormulaR1C1
Hi I have a question I have code that i made with macro recorder:

```<code>ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"
</code>```

how can I adjust this code so it would be somthing like thi:

```<code>'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)
</code>```

I have values in a different sheet called New_Order in column N, O, P.  i want to sum these values and auto fill entire column in worksheet Registration. the complete code looks like this:

```<code> Sub Registrereren()

Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False

On Error Resume Next

Dim oWkSht As Worksheet
Dim LastColumn As Long
Dim c As Date
Dim myCell As Range
Dim LastRow As Long

Sheets("Registration").Activate

Set oWkSht = ThisWorkbook.Sheets("Registration")
LastColumn = oWkSht.Range("A" & Columns.Count).End(xlToRight).Column
LastRow = oWkSht.Range("C" & Rows.Count).End(xlUp).Row

c = Date

Set myCell = oWkSht.Range("1:1").Find(What:=c, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns)

If Not myCell Is Nothing Then
    myCell.Offset(1, 0).Select

    ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"
    'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)
    myCell.Offset(1, 0).Select
    Range(myCell.Offset(1), Cells(LastRow, myCell.Column)).Select
    Selection.FillDown

End If

Sheets("Main").Activate

Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub
</code>```

答:
I've made a number of assumptions and, as a result, a number of corrections.  I assume that you have entries in column "A" of the Registration sheet that match the number of rows you have in the New_Order sheet. </p>

```<code>Option Explicit

Sub Registrereren()

  Application.Calculation = xlCalculationManual
  Application.EnableEvents = False
  Application.ScreenUpdating = False

  On Error Resume Next

  Dim oWkSht As Worksheet
  Dim LastColumn As Long
  Dim c As Date
  Dim myCell As Range
  Dim LastRow As Long

  Sheets("Registration").Activate

  Set oWkSht = ThisWorkbook.Sheets("Registration")
  LastColumn = oWkSht.Cells(1, oWkSht.Columns.Count).End(xlToLeft).Column
  LastRow = oWkSht.Cells(oWkSht.Rows.Count, "A").End(xlUp).row

  c = Date
  Set myCell = oWkSht.Cells(1, 1).Resize(, LastColumn).Find(What:=c, LookIn:=xlFormulas, _
               lookat:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns)

  If Not myCell Is Nothing Then
    myCell.Offset(1, 0).Formula = "=New_Order!N1+New_Order!O1+New_Order!P1"
    Range(myCell.Offset(1), Cells(LastRow, myCell.Column)).Select
    Selection.FillDown
  End If

  Sheets("Main").Activate

  Application.Calculation = xlCalculationAutomatic
  Application.EnableEvents = True
  Application.ScreenUpdating = True

End Sub
</code>```

Title: Adjust ActiveCell.FormulaR1C1

Body:
Hi I have a question I have code that i made with macro recorder:

ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"

how can I adjust this code so it would be somthing like thi:

'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)

I have values in a different sheet called New_Order in column N, O, P.  i want to sum these values and auto fill entire column in worksheet Registration. the complete code looks like this:

 Sub Registrereren()

Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False

On Error Resume Next

Dim oWkSht As Worksheet
Dim LastColumn As Long
Dim c As Date
Dim myCell As Range
Dim LastRow As Long

Sheets("Registration").Activate

Set oWkSht = ThisWorkbook.Sheets("Registration")
LastColumn = oWkSht.Range("A" & Columns.Count).End(xlToRight).Column
LastRow = oWkSht.Range("C" & Rows.Count).End(xlUp).Row

c = Date

Set myCell = oWkSht.Range("1:1").Find(What:=c, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns)

If Not myCell Is Nothing Then
    myCell.Offset(1, 0).Select

    ActiveCell.FormulaR1C1 = "=New_Order!RC[-42]+New_Order!RC[-41]+New_Order!RC[-40]"
    'ActiveCell.Formula = Sheets("New_Order").Range(n & LastRow) + Sheets("New_Order").Range(O & LastRow) + Sheets("New_Order").Range(p & LastRow)
    myCell.Offset(1, 0).Select
    Range(myCell.Offset(1), Cells(LastRow, myCell.Column)).Select
    Selection.FillDown

End If

Sheets("Main").Activate

Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

Body:
I've made a number of assumptions and, as a result, a number of corrections.  I assume that you have entries in column "A" of the Registration sheet that match the number of rows you have in the New_Order sheet.

Option Explicit

Sub Registrereren()

  Application.Calculation = xlCalculationManual
  Application.EnableEvents = False
  Application.ScreenUpdating = False

  On Error Resume Next

  Dim oWkSht As Worksheet
  Dim LastColumn As Long
  Dim c As Date
  Dim myCell As Range
  Dim LastRow As Long

  Sheets("Registration").Activate

  Set oWkSht = ThisWorkbook.Sheets("Registration")
  LastColumn = oWkSht.Cells(1, oWkSht.Columns.Count).End(xlToLeft).Column
  LastRow = oWkSht.Cells(oWkSht.Rows.Count, "A").End(xlUp).row

  c = Date
  Set myCell = oWkSht.Cells(1, 1).Resize(, LastColumn).Find(What:=c, LookIn:=xlFormulas, _
               lookat:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns)

  If Not myCell Is Nothing Then
    myCell.Offset(1, 0).Formula = "=New_Order!N1+New_Order!O1+New_Order!P1"
    Range(myCell.Offset(1), Cells(LastRow, myCell.Column)).Select
    Selection.FillDown
  End If

  Sheets("Main").Activate

  Application.Calculation = xlCalculationAutomatic
  Application.EnableEvents = True
  Application.ScreenUpdating = True

End Sub


问:
Client Server Programming in java
I am just working on my assignment of client-server and found an program online of a server.java as:

```<code>import java.io.*;
import java.net.*;

public class MyServer{

    public static void main(String [] args){
        try{
        ServerSocket ssc = new ServerSocket(7500);

        Socket newSsc = ssc.accept();
        DataInputStream din = new DataInputStream(newSsc.getInputStream());
        DataOutputStream dout = new DataOutputStream(newSsc.getOutputStream());

        PrintWriter pw = new PrintWriter(dout);
        pw.println("Hello! Welcome to vinit's server.");
        boolean more_data = true;
        while(more_data){
            String line = din.readLine();
            if(line == null){
                more_data = false;
            }
            else{
                pw.println("From Server "+line + "\n");
                System.out.println("From Client "+line);
                if(line.trim().equals("QUIT"))
                    more_data = false;
            }
        }
            newSsc.close();
        }
        catch(IOException e){
            System.out.println("IO error");

        }

    }
}
</code>```

THen after I used this server by typing the command as

$ telnet 127.0.0.1 7500

Now I want to ask how my server will be getting null from client, i mean what should be entered so that server will get null

Thanks in Advance.

答: When you close the connection.</p>

Title: Client Server Programming in java

Body:
I am just working on my assignment of client-server and found an program online of a server.java as:

import java.io.*;
import java.net.*;

public class MyServer{

    public static void main(String [] args){
        try{
        ServerSocket ssc = new ServerSocket(7500);

        Socket newSsc = ssc.accept();
        DataInputStream din = new DataInputStream(newSsc.getInputStream());
        DataOutputStream dout = new DataOutputStream(newSsc.getOutputStream());

        PrintWriter pw = new PrintWriter(dout);
        pw.println("Hello! Welcome to vinit's server.");
        boolean more_data = true;
        while(more_data){
            String line = din.readLine();
            if(line == null){
                more_data = false;
            }
            else{
                pw.println("From Server "+line + "\n");
                System.out.println("From Client "+line);
                if(line.trim().equals("QUIT"))
                    more_data = false;
            }
        }
            newSsc.close();
        }
        catch(IOException e){
            System.out.println("IO error");

        }

    }
}

THen after I used this server by typing the command as

$ telnet 127.0.0.1 7500

Now I want to ask how my server will be getting null from client, i mean what should be entered so that server will get null

Thanks in Advance.

Body: When you close the connection.


问:
SSH command throw 'Permission denied (publickey)' message error
I'm trying to execute an ssh command specific ssh -NL and I try with other command but in every execution I have this message
Permission denied (publickey) I already create my public and private keys in the .ssh folder.

So i don't know if somebody has the same problem and found some solution.

Hope you can help me.

答:
It depend why you have to do tunnelling for git (mentioned in the tags of the question)

ssh -NL is for tunning as in *

```<code>sudo ssh -NL 80:localhost:80 root@<IP or hostname>
</code>```

-N - Just set up the tunnel. Do not prepare a command stream.

-L - Local. Create a "Forward Tunnel". Forward local port 80 to remote port 80 via SSH (which is on port 22).

That means a simply ssh -T user@server should work first.

Check ssh -Tv user@server to see which public key is used, and make sure that public key is registered on the remote server side in ~user/.ssh/authorized_keys.

Body:
It depend why you have to do tunnelling for git (mentioned in the tags of the question)

ssh -NL is for tunning as in *

sudo ssh -NL 80:localhost:80 root@<IP or hostname>

-N - Just set up the tunnel. Do not prepare a command stream.

-L - Local. Create a "Forward Tunnel". Forward local port 80 to remote port 80 via SSH (which is on port 22).

That means a simply ssh -T user@server should work first.

Check ssh -Tv user@server to see which public key is used, and make sure that public key is registered on the remote server side in ~user/.ssh/authorized_keys.


问:
How do I get VSCode to load source maps for NPM dependencies?
I have a dependency that is written in TypeScript.  The dependency includes source maps and original source in the NPM package.  If I set a breakpoint in my code and then step into the dependency, it correctly steps into the TypeScript rather than the compiled JavaScript.  However, if I set a breakpoint in the TypeScript code and then launch my app, VSCode says

Breakpoint ignored because generated code not found (source map problem?).

If I set a breakpoint after stepping into the dependency everything works.

I believe the problem here is that source maps are one-way, so when I have a breakpoint in a TypeScript source file, it doesn't know where that is in JavaScript (which is required to actually set the breakpoint via node debugger).  Once the JavaScript file is open, VSCode is able to match the two up and now breakpoints work.

So the question is, how can I make it so that my TS breakpoints work from startup, without having to first step into the file?  The dependency is many files and having to reset my breakpoints every run is problematic, especially since the particular issue I am debugging runs into socket connection timeouts if I take too long (more than a couple seconds).

What I want is a way to tell TypeScript, "parse these JavaScript files when the debugger is launched and sync up the source maps so breakpoints match up correctly".

I know that the general functionality is available because I can successfully debug the dependency itself (I am the maintainer of the dependency) via breakpoints in TypeScript files.  It just seems that some information is lost when it is loaded as an NPM module.

答:
This is exactly what the outFiles attribute in the launch.json file is for - set it to a glob pattern that includes the javascript files in the node module (and your own code). The debug adapter will look at those files for sourcemap references, so it can resolve breakpoints in the TS files immediately.

Examples:

"outFiles": [ "${workspaceRoot}/myOutFiles/**/*.js",  "${workspaceRoot}/node_modules/**/*.js" ]

If you know of just a select set of node modules that include sourcemaps, you can improve performance like this:

"outFiles": [ "${workspaceRoot}/node_modules/{module_a,module_b}/**/*.js" ]

From this issue: https://github.com/Microsoft/vscode-node-debug/issues/82#issuecomment-290642560


问:
I'm having lots of trouble getting my SQL procedure to work properly
I'm trying to do a practice question for my SQL class and I'm having lots of trouble getting my query to work properly, here's my code - can anyone help me?

Write a stored procedure called LookUpCustomer that accepts any part of a Customers last name.

  Return all the customer attributes for those customers from the customer table.

Code:

```<code>Create Procedure LookUpCustomer
    (@CustomerLastName varchar(30) = null)
as
    select CustomerLastName
    from Customer
    where @CustomerLastName like ('_[A-Z]_')
</code>```

I'm getting these results:

```<code>CustomerLastName:
Simpson,
Jones,
Forman,
smilie,
Lauper,
Marley,
Presely,
Clapton,
Johnson,
Douglas,
Leno,
Little,
Tyler,
McDonald,
Carlson,
</code>```

but I need it so it takes any part of a customer last name, I don't know if this is working properly, thanks to all that help out!

答:
Please try the following...

```<code>CREATE PROCEDURE LookUpCustomer ( @CustomerLastNamePart VARCHAR( 30 ) = NULL ) AS
    SELECT CustomerLastName
    FROM Customer
    WHERE CustomerLastName LIKE '%{@CustomerLastNamePart}%'
</code>```

Further reading...

https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

MySQL query String contains

If you have any questions or comments, then please feel free to post a Comment accordingly.

Body:
I'm trying to do a practice question for my SQL class and I'm having lots of trouble getting my query to work properly, here's my code - can anyone help me?

Write a stored procedure called LookUpCustomer that accepts any part of a Customers last name.

  Return all the customer attributes for those customers from the customer table.

Code:

Create Procedure LookUpCustomer
    (@CustomerLastName varchar(30) = null)
as
    select CustomerLastName
    from Customer
    where @CustomerLastName like ('_[A-Z]_')

I'm getting these results:

CustomerLastName:
Simpson,
Jones,
Forman,
smilie,
Lauper,
Marley,
Presely,
Clapton,
Johnson,
Douglas,
Leno,
Little,
Tyler,
McDonald,
Carlson,

but I need it so it takes any part of a customer last name, I don't know if this is working properly, thanks to all that help out!

Body:
Please try the following...

CREATE PROCEDURE LookUpCustomer ( @CustomerLastNamePart VARCHAR( 30 ) = NULL ) AS
    SELECT CustomerLastName
    FROM Customer
    WHERE CustomerLastName LIKE '%{@CustomerLastNamePart}%'

Further reading...

https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

MySQL query String contains

If you have any questions or comments, then please feel free to post a Comment accordingly.


问:
Solution with map gave AC and Solution with unordered_map gave WA. why?
I am looking for any difference between map and unordere_map which is now known by most of people.

The problem : Problem Link

the solution with map: Accepted Solution

```<code>#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    map<int,int> mp;
    map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl;
    return 0;
}
</code>```

The solution with unordered_map: WA Solution

```<code>#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    unordered_map<int,int> mp;
    unordered_map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl;
    return 0;
}

Input :
       98
       7 12 13 19 17 7 3 18 9 18 13 12 3 13 7 9 18 9 18 9 13 18 13 13 18 18 17 17 13 3 12 13 19 17 19 12 18 13 7 3 3 12 7 13 7 3 17 9 13 13 13 12 18 18 9 7 19 17 13 18 19 9 18 18 18 19 17 7 12 3 13 19 12 3 9 17 13 19 12 18 13 18 18 18 17 13 3 18 19 7 12 9 18 3 13 13 9 7
Output : 10
Expected Output : 30
</code>```

As far as I know that only difference with map and unordered_map is that map contain key in sorted fashion while unordered_map not.

答: mp[(X-1)] may need to insert a new element into the map (if the key X-1 wasn't present already). With std::map, inserting a new element doesn't invalidate any existing iterators. With std::unordered_map, it may (if insertion happens to trigger rehashing). When it does, it becomes invalid and the subsequent ++it exhibits undefined behavior.

Body:
I am looking for any difference between map and unordere_map which is now known by most of people.

The problem : Problem Link

the solution with map: Accepted Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    map<int,int> mp;
    map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl;
    return 0;
}

The solution with unordered_map: WA Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    unordered_map<int,int> mp;
    unordered_map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl;
    return 0;
}

Input :
       98
       7 12 13 19 17 7 3 18 9 18 13 12 3 13 7 9 18 9 18 9 13 18 13 13 18 18 17 17 13 3 12 13 19 17 19 12 18 13 7 3 3 12 7 13 7 3 17 9 13 13 13 12 18 18 9 7 19 17 13 18 19 9 18 18 18 19 17 7 12 3 13 19 12 3 9 17 13 19 12 18 13 18 18 18 17 13 3 18 19 7 12 9 18 3 13 13 9 7
Output : 10
Expected Output : 30

As far as I know that only difference with map and unordered_map is that map contain key in sorted fashion while unordered_map not.


问:
Spring Integration: Hooking web services to a FIFO queue
I'm still struggling with Spring Integration- here's my scenario:

A web service gets a request from client A

web service puts the request onto a queue

A queue consumer processes the messages FIFO and sends a response that gets routed back to the web service

Web services sends response back to client A

There will be multiple web services all feeding messages onto this queue, and I need to ensure that they are truly processed in the order that they're received.

What pieces of Spring Integration do I need to wire together?

答:
You should look at either the http (for REST) or ws (for POX/SOAP) "inbound-gateway" elements in Spring Integration. Either one can be connected to a shared, Queue-backed channel via the "request-channel" attribute (the routing of a reply back through the same gateway can be handled behind the scenes). I would recommend starting by browsing through the samples. This blog should help you get up and running: http://blog.springsource.com/2010/09/29/new-spring-integration-samples/

Hope that helps.
-Mark


答:
Try :
select CustomerLastName from Customer WHERE    CustomerLastName LIKE '%' +@CustomerLastName+'%' </p>

Title: I'm having lots of trouble getting my SQL procedure to work properly


问:
Access Raspberry Pi mySQL Database through a simple html
I am working on a simple IoT school project with the Raspberry Pi and a few environments sensors. I used mySQL to store the data. I want to make a simple HTML and PHP to query the data from a device connect to the local network but i don not know how to do it. ( I have read through some android app solution but I wonder if there is a solution in HTML and PHP).
Thanks in advance.</p>

答:
probably the easiet way would be to install a lamp stack, which is short for Linux, Apache, MySQL, PHP

if you have rasbian installed (debian based) you can do sudo apt-get install lamp-server^

then put php files in /var/www/html/

you can access mysql with mysqli in php

and then access it by going to typing the pi's ip into a web browser


问:
Convert float number from nonuniform ranges
So I have this, relatively easy, problem and wondering if the solution for it already exists.

I have to convert a value from one range to another. If there was just one range, like this:

```<code> {-30.0, 30.0} -> {25.0, 50.0}
</code>```

that would have been easy.
But I have a set of ranges:

```<code> {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}
</code>```

One solution is to do a linear search on each access.
Another solution is to make the ranges to have equivalent length so that the input value could be directly mapped.

Does anyone know a better than linear search solution? Or if a container that performs this kind of conversion already exist?

Thanks so much.

答:
As @javaLover replies, instead of linear - O(n) operations,
when n - number of ranges, you can find suitable range by O(log n)
operations, for example with std::map:

```<code>#include <utility>
#include <map>
#include <algorithm>
#include <iostream>

int main()
{
    using Range = std::pair<double, double>;
    struct RangeLess {
        bool operator()(const Range &a, const Range &b) const {
            return a.first < b.first && a.second < b.second;
        }
    };
    using RangeMap = std::map<Range, Range, RangeLess>;
    const RangeMap ranges_map = {
        {{-30.0, -20.0}, {25.0, 30.0}},
        {{-20.0, 0.0}, {30.0, 40.0}},
        { {1.0, 30.0}, {40.0, 50.0}},
    };
    auto map_point = [&ranges_map](double x) -> double {
        const Range x_range = {x, x};
        auto it = ranges_map.find(x_range);
        if (it == ranges_map.end()) {
            return x;
        } else {
            const Range &in = it->first;
            const Range &out = it->second;

            return (x - in.first) / (in.second - in.first) * (out.second - out.first) + out.first;
        }
    };

    const double patterns[] = {-40, -30, -25, -20, 0.5, 5, 40};
    for (auto &&x : patterns) {
        std::cout << x << " -> " << map_point(x) << "\n";
    }
}
</code>```

Body:
So I have this, relatively easy, problem and wondering if the solution for it already exists.

I have to convert a value from one range to another. If there was just one range, like this:

 {-30.0, 30.0} -> {25.0, 50.0}

that would have been easy.
But I have a set of ranges:

 {-30.0, -20.0} -> {25.0, 30.0}
 {-20.0,   0.0} -> {30.0, 40.0}
 {  0.0,  30.0} -> {40.0, 50.0}

One solution is to do a linear search on each access.
Another solution is to make the ranges to have equivalent length so that the input value could be directly mapped.

Does anyone know a better than linear search solution? Or if a container that performs this kind of conversion already exist?

Thanks so much.

Body:
As @javaLover replies, instead of linear - O(n) operations,
when n - number of ranges, you can find suitable range by O(log n)
operations, for example with std::map:

#include <utility>
#include <map>
#include <algorithm>
#include <iostream>

int main()
{
    using Range = std::pair<double, double>;
    struct RangeLess {
        bool operator()(const Range &a, const Range &b) const {
            return a.first < b.first && a.second < b.second;
        }
    };
    using RangeMap = std::map<Range, Range, RangeLess>;
    const RangeMap ranges_map = {
        {{-30.0, -20.0}, {25.0, 30.0}},
        {{-20.0, 0.0}, {30.0, 40.0}},
        { {1.0, 30.0}, {40.0, 50.0}},
    };
    auto map_point = [&ranges_map](double x) -> double {
        const Range x_range = {x, x};
        auto it = ranges_map.find(x_range);
        if (it == ranges_map.end()) {
            return x;
        } else {
            const Range &in = it->first;
            const Range &out = it->second;

            return (x - in.first) / (in.second - in.first) * (out.second - out.first) + out.first;
        }
    };

    const double patterns[] = {-40, -30, -25, -20, 0.5, 5, 40};
    for (auto &&x : patterns) {
        std::cout << x << " -> " << map_point(x) << "\n";
    }
}


问:
maintain different versions of the code simultaneously using git
I got a code that I'm required to optimize. I would like to maintain a set of versions of the code (each version can be described as a composition of some features, optimizations) simultaneously. Eventually, I'll decide which version is the best one. I do not want to merge these versions into fewer versions. However, I would like to be able to make a (minor) modification to a (big) source file which may divert across the versions and I want this modification to write through more than one (possibly all) versions. How can I achieve that with git?

For example let us consider 3 versions: v1, v2, v3 and source code file source.cpp which has lots of code that is different across all versions but class A method aMethod() is identical. I would like to update the method and write the update to versions v1 and v2 only.

How can I do that?

If I modify source.cpp, for example, in v1, than merge it to v2 there will be a merge conflict (because source.cpp is different in v1, v2). Is there any way to avoid the conflict? If not, what is the best way to deal with the merge conflict int this case?
By the way, I don't want to increase code granularity so that the aMethod() will be placed in a dedicated file, because there is already lots of source code written and there will be too much overhead for doing this for any such modification that I describe.

Thanks in advance,

Daniel

答: Have you tried git cherry-pick? If you do "git merge" from branch v1 to branch v2 all commits that are in v1 and not in v2 will be merged over, thats not what you want. If you just cherry-pick the single commit with your change I don't think there will be a merge conflict.</p>


问:
Angular TypeScript Directive's Link method doesn't get called
I am trying to implement a Role-Based-Access-Control system where the allowed resources will be loaded from server after login. I could manage to check it using raw JavaScript code.

```<code>angular.module('app').directive('accessControl',
[
    'AuthService', function (authService) {
        return {
            restrict: 'A',
            scope: "=",
            link: function (scope, element, attrs) {
                scope.canShow = function(resource) {
                    var allowedResources = authService.accountInfo.resources;
                    return allowedResources.indexOf(resource) !== -1;
                }

            }
        }
    }
]);
</code>```

But since my whole application is in TypeScript, I have been trying to make the directive in pure TypeScript, but unfortunately I am unable to do so. Here is my TS code.

```<code>export class AccessControl implements ng.IDirective {

    public authService: App.AuthService;
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;

    constructor(authService: App.AuthService) {
        this.authService = authService;
        console.log('authservice: ', authService);
        AccessControl.prototype.link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
            scope["canShow"] = function (resource: string) {
                // some logic
                console.log('can show' + resource);
                return true;
            };
        };
    }

    public static factory(): ng.IDirectiveFactory  {
        var directive = (authService: App.AuthService) => {
            return new AccessControl(authService);
        };

        directive['$inject'] = ['AuthService'];
        return directive;
    }

    restrict = "A";
    scope: "=";
}

angular.module('app').directive('accessControl', AccessControl.factory());
</code>```

The link function never gets called.
Any help or pointer will be highly appreciated.

答:
We have always declared the link as just a public function on the class. You don't need a public scope variable on your directive class unless you are using isolate scope (in which case it would be an object with each scope variable or method specifically passed). Also, you can set $inject directly on the directive without the bracket property notation you're using. Here's how we have created directives with TypeScript:

```<code>namespace app.directives {
    export class AccessControl implements ng.IDirective {

        public restrict = "A";

        constructor(private authService: App.AuthService) {
            console.log("authservice: ", this.authService);
        }

        public link(scope: ng.IScope,
                    element: ng.IAugmentedJQuery,
                    attrs: ng.IAttributes) {
            console.log("in link function of directive", scope);
        }

        public static factory(): ng.IDirectiveFactory  {
            var directive = (authService: App.AuthService) => {
                return new AccessControl(authService);
            };

            directive.$inject = ["AuthService"];
            return directive;
        }
    }

    angular.module("app")
        .directive("accessControl", AccessControl.factory());
}
</code>```

Body:
I am trying to implement a Role-Based-Access-Control system where the allowed resources will be loaded from server after login. I could manage to check it using raw JavaScript code.

angular.module('app').directive('accessControl',
[
    'AuthService', function (authService) {
        return {
            restrict: 'A',
            scope: "=",
            link: function (scope, element, attrs) {
                scope.canShow = function(resource) {
                    var allowedResources = authService.accountInfo.resources;
                    return allowedResources.indexOf(resource) !== -1;
                }

            }
        }
    }
]);

But since my whole application is in TypeScript, I have been trying to make the directive in pure TypeScript, but unfortunately I am unable to do so. Here is my TS code.

export class AccessControl implements ng.IDirective {

    public authService: App.AuthService;
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;

    constructor(authService: App.AuthService) {
        this.authService = authService;
        console.log('authservice: ', authService);
        AccessControl.prototype.link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
            scope["canShow"] = function (resource: string) {
                // some logic
                console.log('can show' + resource);
                return true;
            };
        };
    }

    public static factory(): ng.IDirectiveFactory  {
        var directive = (authService: App.AuthService) => {
            return new AccessControl(authService);
        };

        directive['$inject'] = ['AuthService'];
        return directive;
    }

    restrict = "A";
    scope: "=";
}

angular.module('app').directive('accessControl', AccessControl.factory());

The link function never gets called.
Any help or pointer will be highly appreciated.

Body:
We have always declared the link as just a public function on the class. You don't need a public scope variable on your directive class unless you are using isolate scope (in which case it would be an object with each scope variable or method specifically passed). Also, you can set $inject directly on the directive without the bracket property notation you're using. Here's how we have created directives with TypeScript:

namespace app.directives {
    export class AccessControl implements ng.IDirective {

        public restrict = "A";

        constructor(private authService: App.AuthService) {
            console.log("authservice: ", this.authService);
        }

        public link(scope: ng.IScope,
                    element: ng.IAugmentedJQuery,
                    attrs: ng.IAttributes) {
            console.log("in link function of directive", scope);
        }

        public static factory(): ng.IDirectiveFactory  {
            var directive = (authService: App.AuthService) => {
                return new AccessControl(authService);
            };

            directive.$inject = ["AuthService"];
            return directive;
        }
    }

    angular.module("app")
        .directive("accessControl", AccessControl.factory());
}


问:
How we can read Xml Response from DocuSign event Notification (DocuSign Connect Functionality) in C#
I have try to Implement Docusign Connect Functionality. I have Enable Docusign Connect functionality. I have create Envelop and Pass the Event Notification object and also configuration is done Admin Connect
Configuration related Setting in Docusign

When Send Mail regarding Sign in (Complete) recipient. and recipient sign in the
document complete. It will call my configuration related url. i didn't understand
how should i received the xml responce in my method.

Success Log Screen

答:
Your app must include a listener HTTPS URL that DocuSign can POST to. This URL must be available on the public internet; it can’t be blocked by a firewall.

See this DocuSign blog post for setting up connect.


问:
jQuery or CSS changing and fading background-position on hover
I have tried a few things but at this point now, i want to fadeout change background position and fadein but not working.... any ideas? or a better solution?

```<code>  $('.collection-hover a').on("mouseenter touchstart", function(event) {
    $(this).find('.collection-list-hover-desc').fadeIn(1000);
    $(this).animate({backgroundPosition: "-50% 100%"});
  });
  $('.collection-hover a').on("mouseleave touchend", function(event) {
    $(this).find('.collection-list-hover-desc').fadeOut(1000);
    $(this).animate({backgroundPosition: "0 0"});
  });
</code>```

snippet of html

```<code><li class="collection-list-item grid-item first collection-hover">
   <a href="/collections/butterfly-sofa" class="position-left" data-image="//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1491014401" style="background-image: url("//cdn.shopify.com/s/files/1/1839/7697/collections/category-panel-butterfly.jpg?v=1491014401"); height: 108.009px;">
  <div class="collection-list-hover-desc">

    <p>Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.</p>
  </div>
  <div class="collection-list-hover-button">
    <span class="button" style="
    padding: 5px 8px;
">Entdecken</span>
  </div>
</a>
</li>
</code>```

答:
This CSS should point you in the right direction:

https://jsfiddle.net/mikatalk/7aLuk4yL/

```<code>a {
// your css ...
  position: relative;
  &:after {
    content: " ";
    position: absolute;
    top:0; right:0; bottom:0; left:0;
    background: pink;
    transition: all ease 300ms;
    z-index: -1;
  }
  &:hover {
    &:after {
      transition: color ease 700ms;
      background: red;
      transition: top ease 300ms;
      top: 50%;
    }
  }
}
</code>```

Body:
I have tried a few things but at this point now, i want to fadeout change background position and fadein but not working.... any ideas? or a better solution?

  $('.collection-hover a').on("mouseenter touchstart", function(event) {
    $(this).find('.collection-list-hover-desc').fadeIn(1000);
    $(this).animate({backgroundPosition: "-50% 100%"});
  });
  $('.collection-hover a').on("mouseleave touchend", function(event) {
    $(this).find('.collection-list-hover-desc').fadeOut(1000);
    $(this).animate({backgroundPosition: "0 0"});
  });

snippet of html

Dein eigener Ruhepol in einer hektischen Welt. Der durch eine Struktur im Inneren formstabile Sitzsack vereint Komfort und Ästhetik.

    Entdecken

Body:
This CSS should point you in the right direction:

https://jsfiddle.net/mikatalk/7aLuk4yL/

a {
// your css ...
  position: relative;
  &:after {
    content: " ";
    position: absolute;
    top:0; right:0; bottom:0; left:0;
    background: pink;
    transition: all ease 300ms;
    z-index: -1;
  }
  &:hover {
    &:after {
      transition: color ease 700ms;
      background: red;
      transition: top ease 300ms;
      top: 50%;
    }
  }
}


问:
AWS Athena JDBC Driver ResultSet.getCharacterStream method not implemented
I have an Athena/PrestoDB query that returns up to 300 million device ids.  This screen shot shows the query when executed in the AWS UI.  The results were displayed in under 1 minute and I downloaded the full results (319MB) in a few minutes from the link provided in the UI.

When I execute the same query over the JDBC connection I'm receiving a method not implemented error.  It appears the AthenaJDBC41-1.0.0.jar from the AWS docs has not implemented the getCharacterStream yet.

```<code>ActiveRecord::StatementInvalid: ActiveRecord::JDBCError: com.amazonaws.athena.jdbc.NotImplementedException: Method ResultSet.getCharacterStream is not yet implemented: SELECT distinct(device_id) FROM presales.sightings_v3 WHERE DATE(date) BETWEEN DATE('2016-03-01') AND DATE('2016-03-02') AND ( contains(audiences, 1133) OR contains(audiences, 1149) OR contains(audiences, 1184) );
</code>```

I'm using driver AthenaJDBC41-1.0.0.jar from the AWS docs and my example connection can be seen here.

My guess is that the method ResultSet.getCharacterStream is only used with large results since my other queries work fine.

Ideally I would like this response to contain the query_id or S3 Path vs streaming the big data results.  I'm curious how the Athena UI generates a link to the results on S3?

答:
You can get the query id from the ResultSet

```<code>((AthenaStatementClient)((AthenaResultSet)rs).getClient()).getQueryExecutionId()
</code>```

With that you can build the S3 Path with

```<code><s3_staging_dir>/<query_id>.csv
</code>```

Body:
I have an Athena/PrestoDB query that returns up to 300 million device ids.  This screen shot shows the query when executed in the AWS UI.  The results were displayed in under 1 minute and I downloaded the full results (319MB) in a few minutes from the link provided in the UI.

When I execute the same query over the JDBC connection I'm receiving a method not implemented error.  It appears the AthenaJDBC41-1.0.0.jar from the AWS docs has not implemented the getCharacterStream yet.

ActiveRecord::StatementInvalid: ActiveRecord::JDBCError: com.amazonaws.athena.jdbc.NotImplementedException: Method ResultSet.getCharacterStream is not yet implemented: SELECT distinct(device_id) FROM presales.sightings_v3 WHERE DATE(date) BETWEEN DATE('2016-03-01') AND DATE('2016-03-02') AND ( contains(audiences, 1133) OR contains(audiences, 1149) OR contains(audiences, 1184) );

I'm using driver AthenaJDBC41-1.0.0.jar from the AWS docs and my example connection can be seen here.

My guess is that the method ResultSet.getCharacterStream is only used with large results since my other queries work fine.

Ideally I would like this response to contain the query_id or S3 Path vs streaming the big data results.  I'm curious how the Athena UI generates a link to the results on S3?

Body:
You can get the query id from the ResultSet

((AthenaStatementClient)((AthenaResultSet)rs).getClient()).getQueryExecutionId()

With that you can build the S3 Path with

<s3_staging_dir>/<query_id>.csv


答:
You have to gracefully close the TCP connection, simply CTRL+C or killing the telnet program won't do, it'll result in an exception in the Java code.

This is a challenge with telnet, depending on your keyboard layout and OS.

```
$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
^]
telnet> quit
Connection closed.
```

Basically, once inside telnet you'll have to press the telnet escape key, which on  my keyboard is CTRL+å and type quit , and on an US keyboard probably is what the telnet program tells you, just CTRL+]

If you're using the netcat program instead of telnet, you can just hit ctrl+d , or pipe some text to it, and the connection will be closed normally.

```<code>echo "Some text" | nc localhost 7500
</code>```

Title: Client Server Programming in java

Body:
You have to gracefully close the TCP connection, simply CTRL+C or killing the telnet program won't do, it'll result in an exception in the Java code.

This is a challenge with telnet, depending on your keyboard layout and OS.

$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
^]
telnet> quit
Connection closed.

Basically, once inside telnet you'll have to press the telnet escape key, which on  my keyboard is CTRL+å and type quit , and on an US keyboard probably is what the telnet program tells you, just CTRL+]

If you're using the netcat program instead of telnet, you can just hit ctrl+d , or pipe some text to it, and the connection will be closed normally.

echo "Some text" | nc localhost 7500


问:
Erlang - use of lists when the size is consistently changing over time
I am new to Erlang and I am learning by building a really small chat program in pure Erlang.

I would like for clients to be able to connect to a server and then send messages to each other. But this is all done on a local machine and not over a network just for learning.

I have a list of all the clients that have connected to the server.

If client A sends a message to client B, I get the desired output in client A's terminal but I can't work out how to get the message from client A to be displayed on client B's terminal.

Or do I have to set each client with it's own mini server

```<code>-module(server).
-export([start/0]).
-export([server/1]).
-export([connect/0]).
-export([sendMessage/2]).

%%
%% The Server
%%
start() ->
    EmptyList = [],
    Pid = spawn(server, server, [EmptyList]),
    register(chatServe, Pid).

server(ListOfClients) ->
    receive
        {Client, connect} ->
            Client ! {chatServe, connected},
            List = clientList(ListOfClients, Client),
            server(List);

        {Client, message, MessageBody} ->
            List = ListOfClients,
            lists:foreach(fun(X) -> X ! {chatServe, new_message, MessageBody} end, List),
            Client ! {chatServe, received},
            server(List)
    end.

%%
%% The client will call rpc:call(server@local, server, connect, [])
%% to connect
%%
connect() ->
    chatServe ! {self(), connect},
    receive
        {chatServe, connected} -> connected
    end.

%%
%% The send message method takes two args
%%
%%
sendMessage(SendTo, MessageBody) ->
    chatServe ! {self(), message, MessageBody},
    receive
       {chatServe, received} -> received
    end.

receiveMessage(SendTo, SendFrom, MessageBody) ->
    receive
        {}
    end.

%%
%% Some helper functions
%%

clientList(List, Client) when length(List) =:= 0 ->
    io:format("List Size = 1~n"),
    [Client];
clientList(List, Client) ->
    io:format("List size = ~p~n", [length(List) + 1]),
    [Client | List].

forwardMessage(SendTo, SentFrom, MessageBody, [H | T]) when H =:= SendTo ->
    SendTo ! {SentFrom, message, MessageBody};
forwardMessage(SendTo, SentFrom, MessageBody, [H | T]) ->
    forwardMessage(SendTo, SentFrom, MessageBody, T);
forwardMessage(SendTo, SentFrom, MessageBody, []) -> [].
</code>```

In the terminal of the client I am calling
    rpc:call(host, mod, function, args).

So my question is how can I get Client A to send a message to Client B through server C, with Client A displaying success, and Client B displaying the message that was sent?

Thanks in advance

答:
In this example my server is an Erlang node and every client is an erlang node too.

Code:

```<code>-module(test).
-export([server_start/1, client_start/2]).
-export([server_new_message/2, client_new_message/2]).

server_start(ServerName) ->
    {ok, _Pid} = net_kernel:start([ServerName, shortnames]),
    erlang:register(server, erlang:self()),
    io:format("Server '~p' started.~nMessages: ~n ~n", [erlang:node()]),
    server_loop().

server_loop() ->
    receive
        {msg, Name, Text} ->
            io:format("~p: ~p~n", [Name, Text]),
            Receivers = lists:delete(Name, erlang:nodes()),
            rpc:multicall(Receivers, ?MODULE, client_new_message, [Name, Text]),
            server_loop()
    end.

%% Server runs this function in client's node.
%% 'client' process in client's node will receive this message and print it
client_new_message(Name, Text) ->
    client ! {msg, Name, Text}.

client_start(ServerName, ClientName) ->
    {ok, _Pid} = net_kernel:start([ClientName, shortnames]),
    pong = net_adm:ping(ServerName),
    timer:sleep(1000), % wait for updating erlang:nodes()
    Other = lists:delete(ServerName, erlang:nodes()),
    io:format("Client '~p' connected to server '~p'.~nOnline users: ~p~n", [erlang:node(), ServerName, Other]),
    erlang:register(client, spawn_link(fun print/0)),
    client_loop(ServerName).

print() ->
    receive
        {msg, Name, Text} ->
            io:format("~p: ~p~n", [Name, Text]),
            print()
    end.

client_loop(ServerName) ->
    rpc:call(ServerName, ?MODULE, server_new_message, [erlang:node(), io:get_line(">>> ")]),
    client_loop(ServerName).

%% Clients run this function in server's node
%% 'server' process will receive messages and print them and broadcast them
server_new_message(Name, Text) ->
    server ! {msg, Name, Text}.
</code>```

Run:

I open 3 Erlang shells.
In shell 1 i run server:

```<code>p@jahanbakhsh ~/Desktop $ erl
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> test:server_start(local_chat_server).
Server 'local_chat_server@jahanbakhsh' started.
Messages:
</code>```

Server is waiting for messages.

In shell 2 i run client 1:

```<code>p@jahanbakhsh ~/Desktop $ erl
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> test:client_start('local_chat_server@jahanbakhsh', client_1).
Client 'client_1@jahanbakhsh' connected to server 'local_chat_server@jahanbakhsh'.
Online users: []
>>>
</code>```

Now i can send message from this terminal, but wait.
I run client 2 in shell 3:

```<code>p@jahanbakhsh ~/Desktop $ erl
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> test:client_start('local_chat_server@jahanbakhsh', client_2).
Client 'client_2@jahanbakhsh' connected to server 'local_chat_server@jahanbakhsh'.
Online users: [client_1@jahanbakhsh]
>>>
</code>```

I send a message ("Test message") from shell 2 or client 1.

In shell 1 or server i have:

```<code>client_1@jahanbakhsh: "Test message\n" - sent to [client_2@jahanbakhsh]
</code>```

In shell 3 or client 2 i have:

```<code>client_1@jahanbakhsh: "Test message\n"
>>>
</code>```

Body:
I am new to Erlang and I am learning by building a really small chat program in pure Erlang.

I would like for clients to be able to connect to a server and then send messages to each other. But this is all done on a local machine and not over a network just for learning.

I have a list of all the clients that have connected to the server.

If client A sends a message to client B, I get the desired output in client A's terminal but I can't work out how to get the message from client A to be displayed on client B's terminal.

Or do I have to set each client with it's own mini server

-module(server).
-export([start/0]).
-export([server/1]).
-export([connect/0]).
-export([sendMessage/2]).

%%
%% The Server
%%
start() ->
    EmptyList = [],
    Pid = spawn(server, server, [EmptyList]),
    register(chatServe, Pid).

server(ListOfClients) ->
    receive
        {Client, connect} ->
            Client ! {chatServe, connected},
            List = clientList(ListOfClients, Client),
            server(List);

        {Client, message, MessageBody} ->
            List = ListOfClients,
            lists:foreach(fun(X) -> X ! {chatServe, new_message, MessageBody} end, List),
            Client ! {chatServe, received},
            server(List)
    end.

%%
%% The client will call rpc:call(server@local, server, connect, [])
%% to connect
%%
connect() ->
    chatServe ! {self(), connect},
    receive
        {chatServe, connected} -> connected
    end.

%%
%% The send message method takes two args
%%
%%
sendMessage(SendTo, MessageBody) ->
    chatServe ! {self(), message, MessageBody},
    receive
       {chatServe, received} -> received
    end.

receiveMessage(SendTo, SendFrom, MessageBody) ->
    receive
        {}
    end.

%%
%% Some helper functions
%%

clientList(List, Client) when length(List) =:= 0 ->
    io:format("List Size = 1~n"),
    [Client];
clientList(List, Client) ->
    io:format("List size = ~p~n", [length(List) + 1]),
    [Client | List].

forwardMessage(SendTo, SentFrom, MessageBody, [H | T]) when H =:= SendTo ->
    SendTo ! {SentFrom, message, MessageBody};
forwardMessage(SendTo, SentFrom, MessageBody, [H | T]) ->
    forwardMessage(SendTo, SentFrom, MessageBody, T);
forwardMessage(SendTo, SentFrom, MessageBody, []) -> [].

In the terminal of the client I am calling
    rpc:call(host, mod, function, args).

So my question is how can I get Client A to send a message to Client B through server C, with Client A displaying success, and Client B displaying the message that was sent?

Thanks in advance

Body:
In this example my server is an Erlang node and every client is an erlang node too.

Code:

-module(test).
-export([server_start/1, client_start/2]).
-export([server_new_message/2, client_new_message/2]).

server_start(ServerName) ->
    {ok, _Pid} = net_kernel:start([ServerName, shortnames]),
    erlang:register(server, erlang:self()),
    io:format("Server '~p' started.~nMessages: ~n ~n", [erlang:node()]),
    server_loop().

server_loop() ->
    receive
        {msg, Name, Text} ->
            io:format("~p: ~p~n", [Name, Text]),
            Receivers = lists:delete(Name, erlang:nodes()),
            rpc:multicall(Receivers, ?MODULE, client_new_message, [Name, Text]),
            server_loop()
    end.

%% Server runs this function in client's node.
%% 'client' process in client's node will receive this message and print it
client_new_message(Name, Text) ->
    client ! {msg, Name, Text}.

client_start(ServerName, ClientName) ->
    {ok, _Pid} = net_kernel:start([ClientName, shortnames]),
    pong = net_adm:ping(ServerName),
    timer:sleep(1000), % wait for updating erlang:nodes()
    Other = lists:delete(ServerName, erlang:nodes()),
    io:format("Client '~p' connected to server '~p'.~nOnline users: ~p~n", [erlang:node(), ServerName, Other]),
    erlang:register(client, spawn_link(fun print/0)),
    client_loop(ServerName).

print() ->
    receive
        {msg, Name, Text} ->
            io:format("~p: ~p~n", [Name, Text]),
            print()
    end.

client_loop(ServerName) ->
    rpc:call(ServerName, ?MODULE, server_new_message, [erlang:node(), io:get_line(">>> ")]),
    client_loop(ServerName).

%% Clients run this function in server's node
%% 'server' process will receive messages and print them and broadcast them
server_new_message(Name, Text) ->
    server ! {msg, Name, Text}.

Run:

I open 3 Erlang shells.
In shell 1 i run server:

p@jahanbakhsh ~/Desktop $ erl
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> test:server_start(local_chat_server).
Server 'local_chat_server@jahanbakhsh' started.
Messages:

Server is waiting for messages.

In shell 2 i run client 1:

p@jahanbakhsh ~/Desktop $ erl
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> test:client_start('local_chat_server@jahanbakhsh', client_1).
Client 'client_1@jahanbakhsh' connected to server 'local_chat_server@jahanbakhsh'.
Online users: []
>>>

Now i can send message from this terminal, but wait.
I run client 2 in shell 3:

p@jahanbakhsh ~/Desktop $ erl
Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> test:client_start('local_chat_server@jahanbakhsh', client_2).
Client 'client_2@jahanbakhsh' connected to server 'local_chat_server@jahanbakhsh'.
Online users: [client_1@jahanbakhsh]
>>>

I send a message ("Test message") from shell 2 or client 1.

In shell 1 or server i have:

client_1@jahanbakhsh: "Test message\n" - sent to [client_2@jahanbakhsh]

In shell 3 or client 2 i have:

client_1@jahanbakhsh: "Test message\n"
>>>


问:
Failing to send data from Action Controller to AJAX Caller ,Serializing context model of a dynamic proxy property
I'm trying to send the queried data gathered from the context back to the ajax caller with the following status

1-The source code server side succeeds querying the data.
2-The source code server side succeeds sending the data in case HTTPPOST or HTTPGET is used
3-No exceptions or errors at the source code
4-applying  JSON(queried object) method doesn't make a change
The scenario goes as follow:-
using ajax call as follows

```<code>$.ajax({
                    type: "POST",
                    url: '@Url.Action("MainCatItems", "Cachier")',
                    contentType: "application/json; charset=utf-8",
                    data: datas,
                    dataType: "json",
                    success: successFunc,
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                });
</code>```

calling an Action Controller

```<code>[HttpPost]
    public ActionResult MainCatItems(int mainCatNo)
    {
        var results = ......//fetching data from Context
        return Json(new { data = results }, JsonRequestBehavior.AllowGet);
    }
</code>```

, the call succeeds sending my parameters to the action but sending a response back to the ajax call from the controller is a little bit confusing as I have two cases:

The First: (working perfectly)
I'm returning data queried from a table class in my Entity Framework (RegisterNotification Class)

```<code>public partial class RegisterNotification
{
    //setters and getters
}
</code>```

which is a single class with no navigational property declared inside

The Second(where the problem is.)
I'm returning data queried from a table class in my Entity Framework
(Item Class"partial class")

Part One:-

```<code>public *partial* class Item
{
    // setters and getters
}
</code>```

Part Two:-

```<code> public *partial* class Item
{
    //setters and getters
}
</code>```

which is a partial class with navigational properties declared inside

This case doesn't work and when getting back to the ajax call it alerts the error function message saying an "internal server error 500"
I have tried parsing the queried data to a JSON Object in my controller:-

```<code>var t = Json(res,"application/json; charset=utf-8",JsonRequestBehavior.AllowGet);
</code>```

Queried Data at source code server side Watch:

Client Side error message details

But again with failure.
Thanks for concerning.

答:
set ProxyCreationEnabled to false like this

```<code>[HttpPost]
public ActionResult MainCatItems(int mainCatNo)
{
    entity.Configuration.ProxyCreationEnabled = false;
    var results = _model.Item.Where(x => x.MenuCategoryID == mainCatNo).ToList();
    return Json(new { data = results }, JsonRequestBehavior.AllowGet);
}
</code>```

you are using entity framework generated proxy object which might be causing problems in serializing

Body:
I'm trying to send the queried data gathered from the context back to the ajax caller with the following status

1-The source code server side succeeds querying the data.
2-The source code server side succeeds sending the data in case HTTPPOST or HTTPGET is used
3-No exceptions or errors at the source code
4-applying  JSON(queried object) method doesn't make a change
The scenario goes as follow:-
using ajax call as follows

$.ajax({
                    type: "POST",
                    url: '@Url.Action("MainCatItems", "Cachier")',
                    contentType: "application/json; charset=utf-8",
                    data: datas,
                    dataType: "json",
                    success: successFunc,
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                });

calling an Action Controller

[HttpPost]
    public ActionResult MainCatItems(int mainCatNo)
    {
        var results = ......//fetching data from Context
        return Json(new { data = results }, JsonRequestBehavior.AllowGet);
    }

, the call succeeds sending my parameters to the action but sending a response back to the ajax call from the controller is a little bit confusing as I have two cases:

The First: (working perfectly)
I'm returning data queried from a table class in my Entity Framework (RegisterNotification Class)

public partial class RegisterNotification
{
    //setters and getters
}

which is a single class with no navigational property declared inside

The Second(where the problem is.)
I'm returning data queried from a table class in my Entity Framework
(Item Class"partial class")

Part One:-

public *partial* class Item
{
    // setters and getters
}

Part Two:-

 public *partial* class Item
{
    //setters and getters
}

which is a partial class with navigational properties declared inside

This case doesn't work and when getting back to the ajax call it alerts the error function message saying an "internal server error 500"
I have tried parsing the queried data to a JSON Object in my controller:-

var t = Json(res,"application/json; charset=utf-8",JsonRequestBehavior.AllowGet);

Queried Data at source code server side Watch:

Client Side error message details

But again with failure.
Thanks for concerning.

Body:
set ProxyCreationEnabled to false like this

[HttpPost]
public ActionResult MainCatItems(int mainCatNo)
{
    entity.Configuration.ProxyCreationEnabled = false;
    var results = _model.Item.Where(x => x.MenuCategoryID == mainCatNo).ToList();
    return Json(new { data = results }, JsonRequestBehavior.AllowGet);
}

you are using entity framework generated proxy object which might be causing problems in serializing


问:
Images auto resize with screen height, no scrollbar - CSS
Two days have been passed with it. But I didn't found any solution yet. Conditions is-

1. No scrollbar (vertical or horizontal),

2. Screen height is unknown, so all content (images and text) should be auto-resize with screen height,

My code is here-

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML Quickstart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico">
    <!-- Bootstrap fremwork main css -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <style>
        #padding{
            padding: 15px;
        }
        img{
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="myDiv">
        <div class="container">
            <div class="row">
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
            </div>

            <div class="row">
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
            </div>

            <div class="row">
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/000/fff.jpg" class="img-responsive" alt="">
                </div>
                <div class="col-md-4" id="padding">
                    <img src="https://dummyimage.com/300x300/ccc/fff.jpg" class="img-responsive" alt="">
                </div>
            </div>

            <div class="row">
                <div class="col-md-12"><h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis dignissimosus.</h2></div>
            </div>

        </div>  <!-- end container -->
    </div> <!-- end myDiv -->

</body>
</html>
</code>```

I've tried with this link and it.

Since content (not many contents) is large than screen height, so is it possible to adapt screen height?

Please write a comment if you've any solution, suggestion or anything.

Thanks.

答:
```<code>img {
    display: block;
    max-width: 100%;
    height: auto;
}
</code>```

Body:
Two days have been passed with it. But I didn't found any solution yet. Conditions is-

1. No scrollbar (vertical or horizontal),

2. Screen height is unknown, so all content (images and text) should be auto-resize with screen height,

My code is here-

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>HTML Quickstart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis dignissimosus.

I've tried with this link and it.

Since content (not many contents) is large than screen height, so is it possible to adapt screen height?

Please write a comment if you've any solution, suggestion or anything.

Thanks.


问:
Caffe with OpenCV 3 and NVIDIA Digits: OpenCV version conflict (2.4 vs 3.0)
Background:

I wish to use both Caffe and Digits such that I can use Caffe within the Digits framework or external to it.

However, for a particular project, I require that Caffe uses OpenCV 3 and not OpenCV 2.4, which Digits installs by default. This project uses Caffe external to Digits, and does not make any use of the Digits framework.

It appears that by installing Digits, my OpenCV 3 installation was "clobbered" with OpenCV 2.4, which is now causing problems within my original Caffe installation.

To make things clearer, below is a listing of the steps that I have taken.

From a fresh Ubuntu 14.04 installation:

Installed Caffe dependencies (except OpenCV) as per the Ubuntu
install guide

Installed OpenCV 3 from source to /usr/local

Tested OpenCV installation

Demos worked fine including OpenCV
3-specific code

Compiled Caffe, setting the Makefile.config to use OpenCV 3

Tested Caffe installation

All tests passed, demos worked fine

Installed Digits as per the install guide

Caffe and OpenCV 2.4 were installed by default by the installer script

OpenCV 3 clobbered by OpenCV 2.4 (?)

Carried out the steps from the Digits Getting Started guide

All steps were successful

Suspected OpenCV conflict, so tried to compile a Caffe demo

Error occurred relating to OpenCV 3.0 and 2.4 conflict -- details below.

Compilation command:

g++ classification.cpp -o classification -I/home/josh/software/caffe/include/ -L/home/josh/software/caffe/build/lib/ -lcaffe -I/usr/local/cuda/include -L/usr/local/cuda/lib64 -lcuda -lcudart -lcublas -lcurand -I/home/josh/software/cudnn/include/ -L/home/josh/software/cudnn/lib64/ -lcudnn -L/usr/lib/x86_64-linux-gnu/ -lglog -L/usr/local/lib -lboost_system -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs -DUSE_OPENCV

Error message:

/usr/bin/ld: warning: libopencv_core.so.3.0, needed by /home/josh/software/caffe/build/lib//libcaffe.so, may conflict with libopencv_core.so.2.4
  /usr/bin/ld: /tmp/ccHaWcOl.o: undefined reference to symbol '_ZN2cv6String10deallocateEv'
  //usr/local/lib/libopencv_core.so.3.0: error adding symbols: DSO missing from command line
  collect2: error: ld returned 1 exit status

Questions:

How do I best resolve the OpenCV version conflict without breaking either Caffe/Digits installations?

Do I need to remove OpenCV and reinstall Caffe and Digits?

If so, what do I need to do differently to prevent the OpenCV version conflicts while still allowing Caffe (with OpenCV 3) and Digits to work side-by-side?

答:
if you install Caffe, using opencv3.0 is not a good ideal. Caffe is not very compatible with it. And if you persist in using it , please remove 2.4 version, using command sudo apt-get autoremove libopencv-dev.
The reason for this version conflict, is you install libopencv-dev (default version is 2.4) and install opencv with 3.0. So remove it, and then compile caffe.


问:
500 URL Rewrite Module Error ASP.NET Core
I am running a reverse proxy (RP) server (Win 2012 R2) in my DMZ. That then connects to my LAN server running Win 2008 R2. I also have the same RP server in front of another Win 2012 R2 LAN box.

We're deploying our first ASP.NET Core app on the LAN behind the RP. It works perfect is the LAN box is Win 2012 R2. However, if we move the app to our production Win 2008 R2 machine, it works except when there is a controller that returns a HTML view (instead of XML or JSON). Again, the exact same code works on a Win 2012 R2 LAN box but not a Win 2008 R2 LAN box.

Here's the RP web.config (same for both LAN servers except for the IPs and domain)

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="ReverseProxyInboundRule1" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://10.0.0.254/{R:1}" />
            </rule>
        </rules>
        <outboundRules>
            <rule name="ReverseProxyOutboundRule1" preCondition="ResponseIsHtml1">
                <match filterByTags="A, Form, Img" pattern="^http(s)?://10.0.0.254/(.*)" />
                <action type="Rewrite" value="http{R:1}://our-public-domain.com/{R:2}" />
            </rule>
            <preConditions>
                <preCondition name="ResponseIsHtml1">
                    <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
                </preCondition>
            </preConditions>
        </outboundRules>
    </rewrite>
</system.webServer>
</code>```

On the Win 2008 R2 LAN box, here's the web.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
        </handlers>
        <aspNetCore processPath=".\MyApp.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
    </system.webServer>
</configuration>
<!--ProjectGuid: 5x8x39x8-580x-4xx2-955x-76x4x4685415-->
</code>```

As I said, the configuration on the same RP server when connecting to the Win 2012 R2 or Win 2008 R2 boxes. Additionally, we have other sites on the Window 2008 R2 that do NOT use ASP.NET Core and those work just fine but none have a view as they just return XML, JSON, and text.

Any insight?

答:
I see you have Response Rewrite in the rule. This can cause 500 error from URLRewrite module in the RP server if the response is compressed. You can see details by checking the sub statuscode. For Gzip encoding this is normally 500.52 .You can see this in the IIS log of RP server

More details on substatuscode iis status code

if the error is 500.52,check this

Body:
I am running a reverse proxy (RP) server (Win 2012 R2) in my DMZ. That then connects to my LAN server running Win 2008 R2. I also have the same RP server in front of another Win 2012 R2 LAN box.

We're deploying our first ASP.NET Core app on the LAN behind the RP. It works perfect is the LAN box is Win 2012 R2. However, if we move the app to our production Win 2008 R2 machine, it works except when there is a controller that returns a HTML view (instead of XML or JSON). Again, the exact same code works on a Win 2012 R2 LAN box but not a Win 2008 R2 LAN box.

Here's the RP web.config (same for both LAN servers except for the IPs and domain)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="ReverseProxyInboundRule1" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://10.0.0.254/{R:1}" />
            </rule>
        </rules>
        <outboundRules>
            <rule name="ReverseProxyOutboundRule1" preCondition="ResponseIsHtml1">
                <match filterByTags="A, Form, Img" pattern="^http(s)?://10.0.0.254/(.*)" />
                <action type="Rewrite" value="http{R:1}://our-public-domain.com/{R:2}" />
            </rule>
            <preConditions>
                <preCondition name="ResponseIsHtml1">
                    <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
                </preCondition>
            </preConditions>
        </outboundRules>
    </rewrite>
</system.webServer>

On the Win 2008 R2 LAN box, here's the web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
        </handlers>
        <aspNetCore processPath=".\MyApp.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
    </system.webServer>
</configuration>

As I said, the configuration on the same RP server when connecting to the Win 2012 R2 or Win 2008 R2 boxes. Additionally, we have other sites on the Window 2008 R2 that do NOT use ASP.NET Core and those work just fine but none have a view as they just return XML, JSON, and text.

Any insight?


问:
confused with CMD and ENTRYPOINT in dockerfile
I have known that in the dockerfile, when ENTRYPOINT and CMD are both provided, the values in CMD will be as default parameter of ENTRYPOINT, then when running a container with additional parameter, the additional parameter will replace the values of CMD in dockerfile.

but when I see the dockerfile of mongodb, I'm confused, the entrypoint and cmd part of its dockerfile:

```<code>ENTRYPOINT ["docker-entrypoint.sh"]

EXPOSE 27017
CMD ["mongod"]
</code>```

I know when I run docker run mongo:latest this will be docker-entrypoint.sh mongod, but when I run docker run mongo:latest --auth, why could it run correctly? Won't it be docker-entrypoint.sh --auth? since the --auth will replace mongod, so why I run docker run mongo --auth but it works fine?

答:
The mongod Dockerfile references docker-entrypoint.sh.

That script docker-entrypoint.sh starts by testing if the first parameter begins with '-' (as in '--auth'):

```<code>if [ "${1:0:1}" = '-' ]; then
    set -- mongod "$@"
fi
</code>```

So the arguments become mongod --auth, not just --auth.

Meaning:

if you have to pass any argument after mongod, you don't have to type mongod first when using docker run: it will be added for you in docker-entrypoint.sh

if you don't have any argument to pass after mongod, you don't have to type mongod either: CMD will provide it for you to the ENTRYPOINT docker-entrypoint.sh.

Body:
I have known that in the dockerfile, when ENTRYPOINT and CMD are both provided, the values in CMD will be as default parameter of ENTRYPOINT, then when running a container with additional parameter, the additional parameter will replace the values of CMD in dockerfile.

but when I see the dockerfile of mongodb, I'm confused, the entrypoint and cmd part of its dockerfile:

ENTRYPOINT ["docker-entrypoint.sh"]

EXPOSE 27017
CMD ["mongod"]

I know when I run docker run mongo:latest this will be docker-entrypoint.sh mongod, but when I run docker run mongo:latest --auth, why could it run correctly? Won't it be docker-entrypoint.sh --auth? since the --auth will replace mongod, so why I run docker run mongo --auth but it works fine?

Body:
The mongod Dockerfile references docker-entrypoint.sh.

That script docker-entrypoint.sh starts by testing if the first parameter begins with '-' (as in '--auth'):

if [ "${1:0:1}" = '-' ]; then
    set -- mongod "$@"
fi

So the arguments become mongod --auth, not just --auth.

Meaning:

if you have to pass any argument after mongod, you don't have to type mongod first when using docker run: it will be added for you in docker-entrypoint.sh

if you don't have any argument to pass after mongod, you don't have to type mongod either: CMD will provide it for you to the ENTRYPOINT docker-entrypoint.sh.