问:
How to encrypt a password field in django
I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field.
I referred to this link

Password field in Django model

But the answer is old and need to know what the present approach is.

My model is as below

```<code>class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
</code>```

答:
in your view</p>

```<code>from django.contrib.auth.hashers import make_password
crew_password = 'take the input if you are using form'
form = FormName(commit=False)
form.crew_password=make_password(crew_password)
form.save()
</code>```

Body:
I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field.
I referred to this link

Password field in Django model

But the answer is old and need to know what the present approach is.

My model is as below

class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)

Body:
in your view

from django.contrib.auth.hashers import make_password
crew_password = 'take the input if you are using form'
form = FormName(commit=False)
form.crew_password=make_password(crew_password)
form.save()


来源: stackexchange

问:
Command to search a file based on the input in the other file
I am on Linux platform and I would need help with the command that will accomplish my task or any suggestion on how to accomplish this.

I have 2 text files, the first file has a list of ID's (Log ID ) and the second file is a log file that has entries of various activities with Log ID.

Basically, I would like to pick a log id from the first file and search if this log id is present in the second file.

The first file has 15000 Log Id's and manually it wouldn't be possible to check each.

Here is my coding attempt:

grep -q "LogID: 1005534" logfile.txt && echo "yes" || echo "no"

But how to iterate the command with all the log-id's I have?

Here is the logID and actual log file

答:
I think your own attempt, using grep, is quite close.

Based on the two files quoted at the end of this answer as demo

(a MCVE by you would have been nice...), I propose to make three lists, using:

positive: grep -of Ids.txt Logfile.txt | sort -u

negative a: grep -vf Ids.txt Logfile.txt | grep -o "LogID: .*" | sort -u

negative b: grep -o "LogID: .*" Logfile.txt >InIDs.txt && grep -vf InIDs.txt IDs.txt | sort -u

Note:

If you system has two "sort" programs, e.g. Windows and GNU, make sure to use the GNU version, i.e. by giving full path to binary; windows sort does not know -u option.

These files have UNIX line endings (only LF, not CRLF), that is important.

Assumption: The string "LogID: dddddd" only occurs at the end of lines

(this assumption can be slightly relaxed, maybe removed, with more sophisticated regexes)

Environment IDs.txt

(note the 1005539, 1005540 not contained in Logfile.txt):

```<code>LogID: 1005534
LogID: 1005535
LogID: 1005536
LogID: 1005537
LogID: 1005538
LogID: 1005539
LogID: 1005540
</code>```

Environment Logfile.txt

(note the 1005548 not contained in IDs.txt and the lines with identical ID):

```<code>blabla LogID: 1005534
bloblo LogID: 1005536
blaablaa LogID: 1005534
blublu LogID: 1005537
blibli LogID: 1005548
bluubluu LogID: 1005537
bleble LogID: 1005538
</code>```

Output, positive:

```<code>LogID: 1005534
LogID: 1005536
LogID: 1005537
LogID: 1005538
</code>```

Output, negative a

(those which are in Logfile.txt but not in IDs.txt):

```<code>LogID: 1005548
</code>```

Output, negative b

(those which are in IDs.txt but not in Logfile.txt):

```<code>LogID: 1005535
LogID: 1005539
LogID: 1005540
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think your own attempt, using grep, is quite close.

Based on the two files quoted at the end of this answer as demo

(a MCVE by you would have been nice...), I propose to make three lists, using:

positive: grep -of Ids.txt Logfile.txt | sort -u

negative a: grep -vf Ids.txt Logfile.txt | grep -o "LogID: .*" | sort -u

negative b: grep -o "LogID: .*" Logfile.txt >InIDs.txt && grep -vf InIDs.txt IDs.txt | sort -u

Note:

If you system has two "sort" programs, e.g. Windows and GNU, make sure to use the GNU version, i.e. by giving full path to binary; windows sort does not know -u option.

These files have UNIX line endings (only LF, not CRLF), that is important.

Assumption: The string "LogID: dddddd" only occurs at the end of lines

(this assumption can be slightly relaxed, maybe removed, with more sophisticated regexes)

Environment IDs.txt

(note the 1005539, 1005540 not contained in Logfile.txt):

LogID: 1005534
LogID: 1005535
LogID: 1005536
LogID: 1005537
LogID: 1005538
LogID: 1005539
LogID: 1005540

Environment Logfile.txt

(note the 1005548 not contained in IDs.txt and the lines with identical ID):

blabla LogID: 1005534
bloblo LogID: 1005536
blaablaa LogID: 1005534
blublu LogID: 1005537
blibli LogID: 1005548
bluubluu LogID: 1005537
bleble LogID: 1005538

Output, positive:

LogID: 1005534
LogID: 1005536
LogID: 1005537
LogID: 1005538

Output, negative a

(those which are in Logfile.txt but not in IDs.txt):

LogID: 1005548

Output, negative b

(those which are in IDs.txt but not in Logfile.txt):

LogID: 1005535
LogID: 1005539
LogID: 1005540


问:
Xamarin: Unable to cater for multiple devices editing an existing project which initially catered for only 1 device
Good day all, I am currently editing an existing project which was initially only created for a specific Tablet, However, I would like to make it compatible on any device.

The snag is, both "supports-screens and compatible-screens":

  <compatible-screens>
    <screen android:screenSize="small" android:screenDensity="ldpi" />
    <screen android:screenSize="small" android:screenDensity="mdpi" />
    <screen android:screenSize="small" android:screenDensity="hdpi" />
    <screen android:screenSize="small" android:screenDensity="xhdpi" />
    <screen android:screenSize="small" android:screenDensity="280" />
    <screen android:screenSize="small" android:screenDensity="360" />
    <screen android:screenSize="small" android:screenDensity="420" />
    <screen android:screenSize="small" android:screenDensity="480" />
    <screen android:screenSize="small" android:screenDensity="560" />

    <screen android:screenSize="normal" android:screenDensity="ldpi" />
    <screen android:screenSize="normal" android:screenDensity="mdpi" />
    <screen android:screenSize="normal" android:screenDensity="hdpi" />
    <screen android:screenSize="normal" android:screenDensity="xhdpi" />
    <screen android:screenSize="normal" android:screenDensity="280" />
    <screen android:screenSize="normal" android:screenDensity="360" />
    <screen android:screenSize="normal" android:screenDensity="420" />
    <screen android:screenSize="normal" android:screenDensity="480" />
    <screen android:screenSize="normal" android:screenDensity="560" />

    <screen android:screenSize="large" android:screenDensity="ldpi" />
    <screen android:screenSize="large" android:screenDensity="mdpi" />
    <screen android:screenSize="large" android:screenDensity="hdpi" />
    <screen android:screenSize="large" android:screenDensity="xhdpi" />
    <screen android:screenSize="large" android:screenDensity="280" />
    <screen android:screenSize="large" android:screenDensity="360" />
    <screen android:screenSize="large" android:screenDensity="420" />
    <screen android:screenSize="large" android:screenDensity="480" />
    <screen android:screenSize="large" android:screenDensity="560" />

    <screen android:screenSize="xlarge" android:screenDensity="ldpi" />
    <screen android:screenSize="xlarge" android:screenDensity="mdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="hdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="xhdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="280" />
    <screen android:screenSize="xlarge" android:screenDensity="360" />
    <screen android:screenSize="xlarge" android:screenDensity="420" />
    <screen android:screenSize="xlarge" android:screenDensity="480" />
    <screen android:screenSize="xlarge" android:screenDensity="560" />
  </compatible-screens>```

..seems NOT to work. I am really stuck with this. Any ideas would be much appreciated.

答:
If you refer to compatible-screens document, you can find the following statements:

The Android system does not read the  manifest element (neither at install-time nor at runtime). This element is informational only and may be used by external services (such as Google Play) to better understand the application's compatibility with specific screen configurations and enable filtering for users. Any screen configuration that is not declared in this element is a screen with which the application is not compatible. Thus, external services (such as Google Play) should not provide the application to devices with such screens.

So, compatible-screens only offer information for external services. If you want to offer support for devices with different screen sizes. You need to Provide different layouts for different screen sizes. For detailed steps of supporting multiple screens, please refer to How to Support Multiple Screens.

Body:
Good day all, I am currently editing an existing project which was initially only created for a specific Tablet, However, I would like to make it compatible on any device.

The snag is, both "supports-screens and compatible-screens":

  <compatible-screens>
    <screen android:screenSize="small" android:screenDensity="ldpi" />
    <screen android:screenSize="small" android:screenDensity="mdpi" />
    <screen android:screenSize="small" android:screenDensity="hdpi" />
    <screen android:screenSize="small" android:screenDensity="xhdpi" />
    <screen android:screenSize="small" android:screenDensity="280" />
    <screen android:screenSize="small" android:screenDensity="360" />
    <screen android:screenSize="small" android:screenDensity="420" />
    <screen android:screenSize="small" android:screenDensity="480" />
    <screen android:screenSize="small" android:screenDensity="560" />

    <screen android:screenSize="normal" android:screenDensity="ldpi" />
    <screen android:screenSize="normal" android:screenDensity="mdpi" />
    <screen android:screenSize="normal" android:screenDensity="hdpi" />
    <screen android:screenSize="normal" android:screenDensity="xhdpi" />
    <screen android:screenSize="normal" android:screenDensity="280" />
    <screen android:screenSize="normal" android:screenDensity="360" />
    <screen android:screenSize="normal" android:screenDensity="420" />
    <screen android:screenSize="normal" android:screenDensity="480" />
    <screen android:screenSize="normal" android:screenDensity="560" />

    <screen android:screenSize="large" android:screenDensity="ldpi" />
    <screen android:screenSize="large" android:screenDensity="mdpi" />
    <screen android:screenSize="large" android:screenDensity="hdpi" />
    <screen android:screenSize="large" android:screenDensity="xhdpi" />
    <screen android:screenSize="large" android:screenDensity="280" />
    <screen android:screenSize="large" android:screenDensity="360" />
    <screen android:screenSize="large" android:screenDensity="420" />
    <screen android:screenSize="large" android:screenDensity="480" />
    <screen android:screenSize="large" android:screenDensity="560" />

    <screen android:screenSize="xlarge" android:screenDensity="ldpi" />
    <screen android:screenSize="xlarge" android:screenDensity="mdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="hdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="xhdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="280" />
    <screen android:screenSize="xlarge" android:screenDensity="360" />
    <screen android:screenSize="xlarge" android:screenDensity="420" />
    <screen android:screenSize="xlarge" android:screenDensity="480" />
    <screen android:screenSize="xlarge" android:screenDensity="560" />
  </compatible-screens>

..seems NOT to work. I am really stuck with this. Any ideas would be much appreciated.


问:
Tweet text from a page
I want to take some text from the HTML page and tweet it out.

Here is my HTML page -

function change() {
  quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"];
  auth = ["Raj", "Mogambo", "Gabbar"];
  min = 0;
  max = 3;
  num = Math.floor(Math.random() * (max - min)) + min;
  q = quotes[num]
  document.getElementById("quote").innerHTML = quotes[num];
  document.getElementById("author").innerHTML = auth[num];
  if (num == 0) {
    document.getElementById("bod").style.color = 'white';
    document.body.style.backgroundColor = 'green';
    document.getElementById("another").style.backgroundColor = 'green';
    document.getElementById("tweet").style.backgroundColor = 'green';
  }
  if (num == 1) {
    document.getElementById("bod").style.color = 'black';
    document.body.style.backgroundColor = 'yellow';
    document.getElementById("another").style.backgroundColor = 'yellow';
    document.getElementById("another").style.color = 'black';
    document.getElementById("tweet").style.color = 'black';
    document.getElementById("tweet").style.backgroundColor = 'yellow';
  }
  if (num == 2) {
    document.getElementById("bod").style.color = 'white';
    document.body.style.backgroundColor = 'blue';
    document.getElementById("another").style.backgroundColor = 'blue';
    document.getElementById("tweet").style.backgroundColor = 'blue';
  }

}

function twitter() {
  text = document.getElementById('quote').innerHTML;
  // document.getElementById('tw').innerHTML = text;

  $('.twitter-button').attr("href", 'https://twitter.com/intent/tweet?text=' + text);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body id='bod'>
  <h1>Quotes</h1>
  <div class='text'>
    <p id='quote'>You're fired!</p>
    <br>
    <p id='author'>Vince McMahon</p>

    <button id='another' class='btn btn-primary' onclick='change()'>Another Quote</button>
    <br>
    <br>

      <button type="button" onclick='twitter()' class="btn btn-primary" id='tw'>Tweet!</button>
    </code>```

Whenever I click on the tweet button, there is no text on the twitter page. Just a blank box.

Link to Codepen - https://codepen.io/pranavgoel25/pen/ZybNRv?editors=1010

答:
I have tweeked a code bit:

```<code>    var quotes = ["Naam toh suna hi hoga","Mogambo Khush Hua","Kitne aadmi the?"];

function change(){
  auth = ["Raj","Mogambo","Gabbar"];
  min = 0;
  max = 3;
  num = Math.floor(Math.random() * (max - min)) + min;
  q = quotes[num]
  document.getElementById("quote").innerHTML = quotes[num];
  document.getElementById("author").innerHTML = auth[num];
  document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[num]);
  if (num == 0){
    document.getElementById("bod").style.color='white';
    document.body.style.backgroundColor = 'green';
  document.getElementById("another").style.backgroundColor='green';
  document.getElementById("tweet").style.backgroundColor='green';
  }
  if (num == 1){
    document.getElementById("bod").style.color='black';
    document.body.style.backgroundColor = 'yellow';
  document.getElementById("another").style.backgroundColor='yellow';
    document.getElementById("another").style.color='black';
    document.getElementById("tweet").style.color='black';
  document.getElementById("tweet").style.backgroundColor='yellow';
  }
  if (num == 2){
    document.getElementById("bod").style.color='white';
    document.body.style.backgroundColor = 'blue';
  document.getElementById("another").style.backgroundColor='blue';
  document.getElementById("tweet").style.backgroundColor='blue';
  }

}

window.onload = function(){
  document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[0]);
}
</code>```

Working Demo:
https://codepen.io/anon/pen/BZjQBe?editors=1010

Title: Tweet text from a page

Body:
I want to take some text from the HTML page and tweet it out.

Here is my HTML page -

function change() {
  quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"];
  auth = ["Raj", "Mogambo", "Gabbar"];
  min = 0;
  max = 3;
  num = Math.floor(Math.random() * (max - min)) + min;
  q = quotes[num]
  document.getElementById("quote").innerHTML = quotes[num];
  document.getElementById("author").innerHTML = auth[num];
  if (num == 0) {
    document.getElementById("bod").style.color = 'white';
    document.body.style.backgroundColor = 'green';
    document.getElementById("another").style.backgroundColor = 'green';
    document.getElementById("tweet").style.backgroundColor = 'green';
  }
  if (num == 1) {
    document.getElementById("bod").style.color = 'black';
    document.body.style.backgroundColor = 'yellow';
    document.getElementById("another").style.backgroundColor = 'yellow';
    document.getElementById("another").style.color = 'black';
    document.getElementById("tweet").style.color = 'black';
    document.getElementById("tweet").style.backgroundColor = 'yellow';
  }
  if (num == 2) {
    document.getElementById("bod").style.color = 'white';
    document.body.style.backgroundColor = 'blue';
    document.getElementById("another").style.backgroundColor = 'blue';
    document.getElementById("tweet").style.backgroundColor = 'blue';
  }

}

function twitter() {
  text = document.getElementById('quote').innerHTML;
  // document.getElementById('tw').innerHTML = text;

  $('.twitter-button').attr("href", 'https://twitter.com/intent/tweet?text=' + text);
};

Quotes

You're fired!

Vince McMahon

    <button id='another' class='btn btn-primary' onclick='change()'>Another Quote</button>

      <button type="button" onclick='twitter()' class="btn btn-primary" id='tw'>Tweet!</button>

Whenever I click on the tweet button, there is no text on the twitter page. Just a blank box.

Link to Codepen - https://codepen.io/pranavgoel25/pen/ZybNRv?editors=1010

Body:
I have tweeked a code bit:

    var quotes = ["Naam toh suna hi hoga","Mogambo Khush Hua","Kitne aadmi the?"];

function change(){
  auth = ["Raj","Mogambo","Gabbar"];
  min = 0;
  max = 3;
  num = Math.floor(Math.random() * (max - min)) + min;
  q = quotes[num]
  document.getElementById("quote").innerHTML = quotes[num];
  document.getElementById("author").innerHTML = auth[num];
  document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[num]);
  if (num == 0){
    document.getElementById("bod").style.color='white';
    document.body.style.backgroundColor = 'green';
  document.getElementById("another").style.backgroundColor='green';
  document.getElementById("tweet").style.backgroundColor='green';
  }
  if (num == 1){
    document.getElementById("bod").style.color='black';
    document.body.style.backgroundColor = 'yellow';
  document.getElementById("another").style.backgroundColor='yellow';
    document.getElementById("another").style.color='black';
    document.getElementById("tweet").style.color='black';
  document.getElementById("tweet").style.backgroundColor='yellow';
  }
  if (num == 2){
    document.getElementById("bod").style.color='white';
    document.body.style.backgroundColor = 'blue';
  document.getElementById("another").style.backgroundColor='blue';
  document.getElementById("tweet").style.backgroundColor='blue';
  }

}

window.onload = function(){
  document.getElementById('twitterBtn').setAttribute("href", 'https://twitter.com/intent/tweet?text=twee' + quotes[0]);
}

Working Demo:
https://codepen.io/anon/pen/BZjQBe?editors=1010


问:
My VBS script is looking for file in wrong directory

The macro I had written was working fine until I happened to change the file path to a relative one.

Here is the actual macro:

```<code>Public Sub refreshXLS()
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Path = ThisWorkbook.Path & "\requiredSource\TestData1.xlsm"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub
</code>```

I updated it to:

```<code>Public Sub refreshXLS()

    Dim xlApp
    Dim xlBook
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim fullpath
    fullpath = fso.GetAbsolutePathName(".")
    Set fso = Nothing
    Set xlApp = CreateObject("Excel.Application")
    Path = xlApp.Workbooks.Open(fullpath & "\TestData1.xlsm")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub
</code>```

I also tried to use:

```<code>Workbooks.Open FileName:= ThisWorkbook.Path & "\TestData1.xlms".
</code>```

This didn't help either.

答:
Public Sub refreshXLS()
    Dim fso As Object
    Dim file As Object
    Dim extension As String

    Set fso = CreateObject("Scripting.FileSystemObject")

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In fso.GetFolder(ThisWorkbook.Path).Files
        extension = LCase(fso.GetExtensionName(file.Path))
        If extension = "xlsx" Or extension = "xls" Then
            With Workbooks.Open(file.Path)
                .UpdateLink Name:=.LinkSources
                .Close True
            End With
        End If
    Next

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub
```

<p>This will process all the files in the same folder where the current <code>xlsm</code> file is stored. If the files to be processed are under the <code>requiredSource</code> folder then you should change the <code>GetFolder</code> to something like</p>

```For Each file In fso.GetFolder(fso.BuildPath(ThisWorkbook.Path, "RequiredSource")).Files
```

<p><strong>edited</strong> to adapt to comments</p>

<p>The <code>vbs</code> file could be something like (assumes the previous <code>refreshXLS</code> is inside a module)</p>

```Option Explicit

Const macroWorkbook = "TestData1.xlsm"
Const macroName = "refreshXLS"

Dim fso
    Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim workbook
    With CreateObject("Excel.Application")
        Set workbook = .Workbooks.Open(fso.BuildPath( _
            fso.GetFile( WScript.ScriptFullName ).ParentFolder.Path _
            , macroWorkbook _
        ))
        .Application.Run "'" & Replace(workbook.Name, "'", "''") & "'!" & macroName
        .ActiveWorkbook.Close
        .Quit
    End With

    WScript.Quit
```

Body:
The macro I had written was working fine until I happened to change the file path to a relative one.

Here is the actual macro:

Public Sub refreshXLS()
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Path = ThisWorkbook.Path & "\requiredSource\TestData1.xlsm"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub

I updated it to:

Public Sub refreshXLS()

    Dim xlApp
    Dim xlBook
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim fullpath
    fullpath = fso.GetAbsolutePathName(".")
    Set fso = Nothing
    Set xlApp = CreateObject("Excel.Application")
    Path = xlApp.Workbooks.Open(fullpath & "\TestData1.xlsm")
    Set folder = fso.GetFolder(Path)

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In folder.Files
        If Right(file.Name, 4) = "xlsx" Or Right(file.Name, 3) = "xls" Then
            Workbooks.Open Path & file.Name
            ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
            ActiveWorkbook.Close True
         End If
    Next

        With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub

I also tried to use:

Workbooks.Open FileName:= ThisWorkbook.Path & "\TestData1.xlms".

This didn't help either.

Body:
Public Sub refreshXLS()
    Dim fso As Object
    Dim file As Object
    Dim extension As String

    Set fso = CreateObject("Scripting.FileSystemObject")

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
        .AskToUpdateLinks = False
    End With

    For Each file In fso.GetFolder(ThisWorkbook.Path).Files
        extension = LCase(fso.GetExtensionName(file.Path))
        If extension = "xlsx" Or extension = "xls" Then
            With Workbooks.Open(file.Path)
                .UpdateLink Name:=.LinkSources
                .Close True
            End With
        End If
    Next

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = True
        .EnableEvents = True
        .AskToUpdateLinks = False
    End With
End Sub

This will process all the files in the same folder where the current xlsm file is stored. If the files to be processed are under the requiredSource folder then you should change the GetFolder to something like

For Each file In fso.GetFolder(fso.BuildPath(ThisWorkbook.Path, "RequiredSource")).Files

edited to adapt to comments

The vbs file could be something like (assumes the previous refreshXLS is inside a module)

Option Explicit

Const macroWorkbook = "TestData1.xlsm"
Const macroName = "refreshXLS"

Dim fso
    Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim workbook
    With CreateObject("Excel.Application")
        Set workbook = .Workbooks.Open(fso.BuildPath( _
            fso.GetFile( WScript.ScriptFullName ).ParentFolder.Path _
            , macroWorkbook _
        ))
        .Application.Run "'" & Replace(workbook.Name, "'", "''") & "'!" & macroName
        .ActiveWorkbook.Close
        .Quit
    End With

    WScript.Quit


问:
Unable to center content using margin auto
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body>
      <div class="row bg_color">
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2015/16</h3>
               <hr>
               <ul>
                  <li>The Best FIFA Men's Player 2016</li>
                  <li>FIFA Club World Cup</li>
                  <li>France Football Ballon D'Or 2016</li>
                  <li>UEFA Best Player in Europe</li>
                  <li>UEFA Euro 2016 (Portugal)</li>
                  <li>UEFA Champions League (Real Madrid)</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2014/15</h3>
               <hr>
               <ul>
                  <li>Pichichi Award</li>
                  <li>European Golden Boot 2015</li>
                  <li>FIFA Ballon D'Or 2014</li>
                  <li>Globe Soccer Best Player of the Year</li>
                  <li>Globe Soccer Fan's Favourite Player Award</li>
                  <li>IFFHS Trophy for Best Striker  on the planet</li>
               </ul>
            </div>
            <div class="col-xs-12 col-sm-4 col-md-4 stats_box">
               <h3>2013/14</h3>
               <hr>
               <ul>
                  <li>Club World Cup</li>
                  <li>BBC Overseas Sports  Personality Award</li>
                  <li>World's Top  Goalscorer 2013</li>
                  <li>Pichichi Award</li>
                  <li>Best Player, Best Forward in La Liga</li>
                  <li>UEFA Best Player in Europe</li>
               </ul>
            </div>
         </div>

</body>
</code>```

CSS:

```<code> .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}
</code>```

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

答:
Try to add this CSS code in your style,

```<code>@media only screen and (max-width: 768px) {
.stats_box {
    width: 100%;
}
.center-col{
    float: none;
    margin: 0 auto;
}
}
</code>```

and in the HTML,

```<code><div class="col-xs-12 col-sm-4 col-md-4 stats_box center-col">
</code>```

Please make sure that you removed the margin:200pxin .stats_box. Hope this will help!

Body:
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

2015/16

The Best FIFA Men's Player 2016

FIFA Club World Cup

France Football Ballon D'Or 2016

UEFA Best Player in Europe

UEFA Euro 2016 (Portugal)

UEFA Champions League (Real Madrid)

2014/15

Pichichi Award

European Golden Boot 2015

FIFA Ballon D'Or 2014

Globe Soccer Best Player of the Year

Globe Soccer Fan's Favourite Player Award

IFFHS Trophy for Best Striker  on the planet

2013/14

Club World Cup

BBC Overseas Sports  Personality Award

World's Top  Goalscorer 2013

Pichichi Award

Best Player, Best Forward in La Liga

UEFA Best Player in Europe

CSS:

 .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

Body:
Try to add this CSS code in your style,

@media only screen and (max-width: 768px) {
.stats_box {
    width: 100%;
}
.center-col{
    float: none;
    margin: 0 auto;
}
}

and in the HTML,

<div class="col-xs-12 col-sm-4 col-md-4 stats_box center-col">

Please make sure that you removed the margin:200pxin .stats_box. Hope this will help!


问:
Join SQL tables
Suppose that in table "ab" I have the names of the students that get along from class "a" and class "b", identically I have table "ac" and "bc". What SQL query should I use in order to get all the combinations possible of students who can form groups (i.e. "get along together")? And how can i extend this to n classes?
For example: John from class a gets along with Jen from class b and Steff from class c, and Jen and Steff get along. Therefore John, Jen and Steff can form a group).</p>

答:
The initial query can be satisfied by the code

```<code>select ab.a, ab.b, ac.c
from
ab inner join
bc on ab.b = bc.b inner join
ac on ac.a = ab.a and bc.c = ac.c
</code>```

Stepping up to n classes will get progressively more complex as n=4 would be the same query with the additional three joins

```<code>inner join ad on ab.a = ad.a
inner join bd on bd.b = ab.b and ad.d = bd.d
inner join cd on cd.c = ac.c and ad.d = cd.d
</code>```

2 classes requires 1 table and no joins,

3 classes requires 3 tables and 2 joins,

4 classes requires 6 tables and 5 joins

So we can see it getting progressively more complex as we proceed

Title: Join SQL tables

Body:
The initial query can be satisfied by the code

select ab.a, ab.b, ac.c
from
ab inner join
bc on ab.b = bc.b inner join
ac on ac.a = ab.a and bc.c = ac.c

Stepping up to n classes will get progressively more complex as n=4 would be the same query with the additional three joins

inner join ad on ab.a = ad.a
inner join bd on bd.b = ab.b and ad.d = bd.d
inner join cd on cd.c = ac.c and ad.d = cd.d

2 classes requires 1 table and no joins,

3 classes requires 3 tables and 2 joins,

4 classes requires 6 tables and 5 joins

So we can see it getting progressively more complex as we proceed

ContentLicense: CC BY-SA 2.5


问:
Python: can't import dictionary from another file
I have problems importing a dictionary from an other file (I'm using python 2.7)

```<code># src/config/config_bankheist.py
bankheist_config = {

    ###############################
    # SECTION 1 : ENTERY OF HEIST #
    ###############################
    'activation_command': '!bankheist',

    (...) # More key/values here

} # End of bankheist_config
</code>```

And when I try to import it in the main file where it's used:

```<code>#src/lib/commands/bankheist.py
import string

from src.lib.timers import InfiniteTimer
import src.lib.irc as irc_

from src.config.config import config
from src.config.config_bankheist import bankheist_config as bankheist

def check_init_status():
    try:
        return bankheist['init_status']
    except KeyError:
        bankheist['init_status'] = False
        return False
</code>```

So here i try to return the value by the key 'init_status'. The first time, it won't find the key, as bankheist isn't initiated yet... So normaly I would ket a KeyError not found. Instead, I get a TypeError: 'function' object has no attribute '__ getitem __'.

I tried adding the init_status key to the dictionary and initialize it on False, I even tried to import is as a global variable (say that it's global on the config file, and global on the define methode), I tried to put the bankhiest_config as bankhiest in the same file, and it stil don't works..

I have something similar with config_command.py (same folder as config_bankheist.py) and commands.py (same folder as bankheist.py) and that works.. So I'm not sure what I am doiing wrong here.

Thanks in advance,
Laurens

PS: if interested, full code is on github: https://github.com/LaurensScheldeman/TwitchBot/commits/master

答:
you have function object named bankheist, so your imported dict object is overwritten after bankheist function definition

try to leave initial dict object name bankheist_config

```<code>import string

from src.lib.timers import InfiniteTimer
import src.lib.irc as irc_

from src.config.config import config
from src.config.config_bankheist import bankheist_config

def check_init_status():
    try:
        return bankheist_config['init_status']
    except KeyError:
        bankheist_config['init_status'] = False
        return False
</code>```

Body:
I have problems importing a dictionary from an other file (I'm using python 2.7)

# src/config/config_bankheist.py
bankheist_config = {

    ###############################
    # SECTION 1 : ENTERY OF HEIST #
    ###############################
    'activation_command': '!bankheist',

    (...) # More key/values here

} # End of bankheist_config

And when I try to import it in the main file where it's used:

#src/lib/commands/bankheist.py
import string

from src.lib.timers import InfiniteTimer
import src.lib.irc as irc_

from src.config.config import config
from src.config.config_bankheist import bankheist_config as bankheist

def check_init_status():
    try:
        return bankheist['init_status']
    except KeyError:
        bankheist['init_status'] = False
        return False

So here i try to return the value by the key 'init_status'. The first time, it won't find the key, as bankheist isn't initiated yet... So normaly I would ket a KeyError not found. Instead, I get a TypeError: 'function' object has no attribute '__ getitem __'.

I tried adding the init_status key to the dictionary and initialize it on False, I even tried to import is as a global variable (say that it's global on the config file, and global on the define methode), I tried to put the bankhiest_config as bankhiest in the same file, and it stil don't works..

I have something similar with config_command.py (same folder as config_bankheist.py) and commands.py (same folder as bankheist.py) and that works.. So I'm not sure what I am doiing wrong here.

Thanks in advance,
Laurens

PS: if interested, full code is on github: https://github.com/LaurensScheldeman/TwitchBot/commits/master

Body:
you have function object named bankheist, so your imported dict object is overwritten after bankheist function definition

try to leave initial dict object name bankheist_config

import string

from src.lib.timers import InfiniteTimer
import src.lib.irc as irc_

from src.config.config import config
from src.config.config_bankheist import bankheist_config

def check_init_status():
    try:
        return bankheist_config['init_status']
    except KeyError:
        bankheist_config['init_status'] = False
        return False


问:
doinbackground() method is not called in aync task
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

```<code>private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}
</code>```

Any help is appreciated.
Thank you

答:
Enclose everything in onPostExecuted() with runOnUIThread():

```<code>runOnUiThread(new Runnable() {
@Override
public void run() {

}});
</code>```

Body:
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}

Any help is appreciated.
Thank you

Body:
Enclose everything in onPostExecuted() with runOnUIThread():

runOnUiThread(new Runnable() {
@Override
public void run() {

}});


问:
VSTS Build and NuGet Publisher - 405 Method Not Allowed
I'm trying to configure VSTS build that will publish NuGet package to internal feed. Puckage is being created successfully but have issue with NuGet Publisher.
When NuGet publisher is trying to publish package then I got error:

```<code>Using credentials from config. UserName: VssSessionToken
Pushing PackageName_20170608-081053 to 'https://...visualstudio.com/_packaging/b5ae5df2-b73e-4af2-...-66df-4340-8e68-9d4be0071ba8/nuget/v2/'...
PUT https://...visualstudio.com/_packaging/b5ae5df2-b73e-4af2-...-66df-4340-8e68-9d4be0071ba8/nuget/v2/
System.InvalidOperationException: Failed to process request. 'Method Not Allowed'.
The remote server returned an error: (405) Method Not Allowed.. ---> System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.
...
Error: d:\a\_tasks\NuGetPublisher_333b11bd-d341-\0.2.34\node_modules\nuget-task-common\NuGet\3.3.0\NuGet.exe failed with return code: 1
Packages failed to publish
</code>```

I've already checked permissions to feed and Project Collection Build Service is added as a contributor. I've also tried to play with NuGet versions but it didn't help.

答:
The issue was that I was trying to publish to release view. Instead I have to push the package to a feed first.

Here are details:
https://github.com/Microsoft/vsts-tasks/issues/4493

Body:
I'm trying to configure VSTS build that will publish NuGet package to internal feed. Puckage is being created successfully but have issue with NuGet Publisher.
When NuGet publisher is trying to publish package then I got error:

Using credentials from config. UserName: VssSessionToken
Pushing PackageName_20170608-081053 to 'https://...visualstudio.com/_packaging/b5ae5df2-b73e-4af2-...-66df-4340-8e68-9d4be0071ba8/nuget/v2/'...
PUT https://...visualstudio.com/_packaging/b5ae5df2-b73e-4af2-...-66df-4340-8e68-9d4be0071ba8/nuget/v2/
System.InvalidOperationException: Failed to process request. 'Method Not Allowed'.
The remote server returned an error: (405) Method Not Allowed.. ---> System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.
...
Error: d:\a\_tasks\NuGetPublisher_333b11bd-d341-\0.2.34\node_modules\nuget-task-common\NuGet\3.3.0\NuGet.exe failed with return code: 1
Packages failed to publish

I've already checked permissions to feed and Project Collection Build Service is added as a contributor. I've also tried to play with NuGet versions but it didn't help.


问:
Namespace in xamarin
I have xamarin application and want to use:

```<code>using System.Media;
</code>```

but it writes me: SeverityThe type or namespace name 'Media' does not exist in the namespace 'System' (are you missing an assembly reference?)
What can I do? Thanks

答: If you're trying to use it on a PCL project most likely its because those libraries are not available. Portable Class Libraries only offer a subset of the full .NET functionality. You can probably try installing a related NuGet Package like the one Gusman suggested and use its functions to achieve your aim instead. </p>

Title: Namespace in xamarin

Body:
I have xamarin application and want to use:

using System.Media;

but it writes me: SeverityThe type or namespace name 'Media' does not exist in the namespace 'System' (are you missing an assembly reference?)
What can I do? Thanks


问:
NullReferenceException 6
I am getting wrong .Plz anyone help

** System.NullReferenceException: Object reference not set to an instance of an object.

//Line 35:   SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);

```<code> if(!IsPostBack)

    {
        if( Session["Login"] == null && Request.Cookies["Login"]==null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {

            string cs = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {

                SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);
                cmd.CommandType = CommandType.StoredProcedure;
                 con.Open();
                 using (SqlDataReader rdr = cmd.ExecuteReader())
                 {
                     while (rdr.Read())
                     {
                       LabelUN.Text = rdr["UserName"].ToString();
                     }
                 }
                 con.Close();
            }

            Response.ClearHeaders();
            Response.AddHeader("Cache-Control", "no-cache,no-store,max-age=0,must-revalidate");
            Response.AddHeader("Pragma", "no-cache");

        }
    }

}
</code>```

答: Request.Cookies["Login"]["UserName"] could be the issue in your case. Please watch the value of this code while debugging. This might be null and as you are using .ToString() it can throw Null Reference Exception. Another thing the command is Select * from UserInfm - you have not specified 'from'</p>

Title: NullReferenceException 6

Body:
I am getting wrong .Plz anyone help

** System.NullReferenceException: Object reference not set to an instance of an object.

//Line 35:   SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);

 if(!IsPostBack)

    {
        if( Session["Login"] == null && Request.Cookies["Login"]==null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {

            string cs = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {

                SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);
                cmd.CommandType = CommandType.StoredProcedure;
                 con.Open();
                 using (SqlDataReader rdr = cmd.ExecuteReader())
                 {
                     while (rdr.Read())
                     {
                       LabelUN.Text = rdr["UserName"].ToString();
                     }
                 }
                 con.Close();
            }

            Response.ClearHeaders();
            Response.AddHeader("Cache-Control", "no-cache,no-store,max-age=0,must-revalidate");
            Response.AddHeader("Pragma", "no-cache");

        }
    }

}


问:
When do you have to worry about thread safety?
What are some situations where you need to worry about whether a static method is thread safe?

For example, if I have static utility function that doesn't touch any static class level variables, is that method already thread safe? If I have a static method that does touch static class variables, is that method potentially not thread safe?

Thanks in advance.

答: It is thread-safe if no mutable resources, such as, class variables are accessed -- however, you have to make sure that your method does not call any other methods that access any mutable resources.</p>


问:
how to Implement jQuery Validation rule for multiselect box?
Here is my html select box (options will come by ajax call) with multiselect function and validation

```<code><select id="chapterId" name="chapter[]" class="multiselect-ui form-control" multiple="multiple"></select>

$('#chapterId').multiselect({
        includeSelectAllOption: true
    });

var $validator = $("#orderPaper").validate({
            rules: {
                 'chapter[]': {required: true, min: 1},
            },
            messages: {
                'chapter[]': {required: "Please select chapter"},
            }
});
</code>```

also multiselect.js is included properly.
its shows error every time 'Please select chapter' weather chapters selected or not.
I also checked that chapters are selected properly i can also get selected chapter ids.
but the jquery error is showing every time.

答:
You just need to use custom validation rule. Try with this.</p>

```<code>var $validator = $("#orderPaper").validate({
    rules: {
        'chapter[]': {required: true, needsSelection: true},
    },
    messages: {
        'chapter[]': {required: "Please select chapter", needsSelection: "Please select chapter"},
    }
});
$.validator.addMethod("needsSelection", function (value, element) {
    var count = $(element).find('option:selected').length;
    return count > 0;
});
</code>```

Body:
Here is my html select box (options will come by ajax call) with multiselect function and validation

<select id="chapterId" name="chapter[]" class="multiselect-ui form-control" multiple="multiple"></select>

$('#chapterId').multiselect({
        includeSelectAllOption: true
    });

var $validator = $("#orderPaper").validate({
            rules: {
                 'chapter[]': {required: true, min: 1},
            },
            messages: {
                'chapter[]': {required: "Please select chapter"},
            }
});

also multiselect.js is included properly.
its shows error every time 'Please select chapter' weather chapters selected or not.
I also checked that chapters are selected properly i can also get selected chapter ids.
but the jquery error is showing every time.

Body:
You just need to use custom validation rule. Try with this.

var $validator = $("#orderPaper").validate({
    rules: {
        'chapter[]': {required: true, needsSelection: true},
    },
    messages: {
        'chapter[]': {required: "Please select chapter", needsSelection: "Please select chapter"},
    }
});
$.validator.addMethod("needsSelection", function (value, element) {
    var count = $(element).find('option:selected').length;
    return count > 0;
});


问:
nltk words corpus does not contain "okay"?
The NLTK word corpus does not have the phrase "okay", "ok", "Okay"?

```<code>> from nltk.corpus import words
> words.words().__contains__("check")
> True

> words.words().__contains__("okay")
> False

> len(words.words())
> 236736
</code>```

Any ideas why?

答:
TL;DR

```<code>from nltk.corpus import words
from nltk.corpus import wordnet

manywords = words.words() + wordnet.words()
</code>```

In Long

From the docs, the nltk.corpus.words are words a list of words from "http://en.wikipedia.org/wiki/Words_(Unix)

Which in Unix, you can do:

```<code>ls /usr/share/dict/
</code>```

And reading the README:

```<code>$ cd /usr/share/dict/
/usr/share/dict$ cat README
#   @(#)README  8.1 (Berkeley) 6/5/93
# $FreeBSD$

WEB ---- (introduction provided by jaw@riacs) -------------------------

Welcome to web2 (Webster's Second International) all 234,936 words worth.
The 1934 copyright has lapsed, according to the supplier.  The
supplemental 'web2a' list contains hyphenated terms as well as assorted
noun and adverbial phrases.  The wordlist makes a dandy 'grep' victim.

     -- James A. Woods    {ihnp4,hplabs}!ames!jaw    (or jaw@riacs)

Country names are stored in the file /usr/share/misc/iso3166.

FreeBSD Maintenance Notes ---------------------------------------------

Note that FreeBSD is not maintaining a historical document, we're
maintaining a list of current [American] English spellings.

A few words have been removed because their spellings have depreciated.
This list of words includes:
    corelation (and its derivatives)    "correlation" is the preferred spelling
    freen               typographical error in original file
    freend              archaic spelling no longer in use;
                    masks common typo in modern text

--

A list of technical terms has been added in the file 'freebsd'.  This
word list contains FreeBSD/Unix lexicon that is used by the system
documentation.  It makes a great ispell(1) personal dictionary to
supplement the standard English language dictionary.
</code>```

Since it's a fixed list of 234,936, there are bound to be words that don't exist in that list.

If you need to extend your word list, you can add to the list using the words from WordNet using nltk.corpus.wordnet.words().

Most probably, all you need is a large enough corpus of text, e.g. Wikipedia dump and then tokenize it and extract all unique words.

Body:
The NLTK word corpus does not have the phrase "okay", "ok", "Okay"?

> from nltk.corpus import words
> words.words().__contains__("check")
> True

> words.words().__contains__("okay")
> False

> len(words.words())
> 236736

Any ideas why?

Body:
TL;DR

from nltk.corpus import words
from nltk.corpus import wordnet

manywords = words.words() + wordnet.words()

In Long

From the docs, the nltk.corpus.words are words a list of words from "http://en.wikipedia.org/wiki/Words_(Unix)

Which in Unix, you can do:

ls /usr/share/dict/

And reading the README:

$ cd /usr/share/dict/
/usr/share/dict$ cat README
#   @(#)README  8.1 (Berkeley) 6/5/93
# $FreeBSD$

WEB ---- (introduction provided by jaw@riacs) -------------------------

Welcome to web2 (Webster's Second International) all 234,936 words worth.
The 1934 copyright has lapsed, according to the supplier.  The
supplemental 'web2a' list contains hyphenated terms as well as assorted
noun and adverbial phrases.  The wordlist makes a dandy 'grep' victim.

     -- James A. Woods    {ihnp4,hplabs}!ames!jaw    (or jaw@riacs)

Country names are stored in the file /usr/share/misc/iso3166.

FreeBSD Maintenance Notes ---------------------------------------------

Note that FreeBSD is not maintaining a historical document, we're
maintaining a list of current [American] English spellings.

A few words have been removed because their spellings have depreciated.
This list of words includes:
    corelation (and its derivatives)    "correlation" is the preferred spelling
    freen               typographical error in original file
    freend              archaic spelling no longer in use;
                    masks common typo in modern text

--

A list of technical terms has been added in the file 'freebsd'.  This
word list contains FreeBSD/Unix lexicon that is used by the system
documentation.  It makes a great ispell(1) personal dictionary to
supplement the standard English language dictionary.

Since it's a fixed list of 234,936, there are bound to be words that don't exist in that list.

If you need to extend your word list, you can add to the list using the words from WordNet using nltk.corpus.wordnet.words().

Most probably, all you need is a large enough corpus of text, e.g. Wikipedia dump and then tokenize it and extract all unique words.


问:
How do you do Design by Contract in Perl?
I'm investigating using DbC in our Perl projects, and I'm trying to find the best way to verify contracts in the source (e.g. checking pre/post conditions, invariants, etc.)

Class::Contract was written by Damian Conway and is now maintained by C. Garret Goebel, but it looks like it hasn't been touched in over 8 years.

It looks like what I want to use is Moose, as it seems as though it might offer functionality that could be used for DbC, but I was wondering if anyone had any resources (articles, etc.) on how to go about this, or if there are any helpful modules out there that I haven't been able to find.

Is anyone doing DbC with Perl?  Should I just "jump in" to Moose and see what I can get it to do for me?

答:
I would also recommend using Moose.

However as an "alternative" take a look at Sub::Contract.

To quote the author....

Sub::Contract offers a pragmatic way to implement parts of the programming by contract paradigm in Perl.

Sub::Contract is not a design-by-contract framework.

Sub::Contract aims at making it very easy to constrain subroutines input arguments and return values in order to emulate strong typing at runtime.

OwnerDisplayName: Adam Bellaire

LastEditorDisplayName: brian d foy

OwnerDisplayName: draegtun


答:
Thread safety becomes a concern if there is at least a single entry point which can be accessed by multiple threads.

If a piece of code is accessed by multiple threads and is calling other method/class/etc., then all this code tree becomes vulnerable.

From "Java concurrency in practice":
The ﬁrst step in organizing a program around task execution is identifying sensible task boundaries. Ideally, tasks are independent activities: work that doesn’t
depend on the state, result, or side effects of other tasks. Independence facilitates concurrency, as independent tasks can be executed in parallel if there are
adequate processing resources.

For example, if you are writing an isolated servlet, which is guaranteed to be executed by a single thread, you don't have to worry. But if you write a static utility which is used by different servlets, then it has to be made to handle multi-threaded access.

Title: When do you have to worry about thread safety?

Body:
What are some situations where you need to worry about whether a static method is thread safe?

For example, if I have static utility function that doesn't touch any static class level variables, is that method already thread safe? If I have a static method that does touch static class variables, is that method potentially not thread safe?

Thanks in advance.


问:
ZF2: Class 'Payum\Sofort\Payment\SofortUeberWeisung' not found
Here is my controller that is using the class from Payum Module in vendor.

```<code><?php
    namespace Orders\Controller;
    use Payum\Sofort;
    use Payum\Sofort\Payment\SofortUeberWeisung;

    class PaymentController extends AbstractActionController
     {

    protected $entityManager;

    public function sofortAction()
    {
      $Sofortueberweisung = new SofortUeberWeisung($configkey);

        $Sofortueberweisung->setAmount(10.21);
        $Sofortueberweisung->setCurrencyCode('EUR');
        //$Sofortueberweisung->setSenderSepaAccount('88888888', '12345678', 'Max Mustermann');
        $Sofortueberweisung->setSenderCountryCode('DE');
        $Sofortueberweisung->setReason('Testueberweisung', 'Verwendungszweck');
        $Sofortueberweisung->setSuccessUrl('http://www.google.de', true);
        $Sofortueberweisung->setAbortUrl('http://www.google.de');
        // $Sofortueberweisung->setNotificationUrl('http://www.google.de', 'loss,pending');
        // $Sofortueberweisung->setNotificationUrl('http://www.yahoo.com', 'loss');
        // $Sofortueberweisung->setNotificationUrl('http://www.bing.com', 'pending');
        // $Sofortueberweisung->setNotificationUrl('http://www.sofort.com', 'received');
        // $Sofortueberweisung->setNotificationUrl('http://www.youtube.com', 'refunded');
        // $Sofortueberweisung->setNotificationUrl('http://www.youtube.com', 'untraceable');
        $Sofortueberweisung->setNotificationUrl('http://www.twitter.com');
        $Sofortueberweisung->setCustomerprotection(true);

             $Sofortueberweisung->sendRequest();

            if($Sofortueberweisung->isError()) {
                //SOFORT-API didn't accept the data
                echo $Sofortueberweisung->getError();
            } else {
                //buyer must be redirected to $paymentUrl else payment cannot be successfully completed!
                $paymentUrl = $Sofortueberweisung->getPaymentUrl();
                header('Location: '.$paymentUrl);
            }
        }

    }
</code>```

And The class is here in the Payum\Sofort\Payment folder

```<code><?php

   namespace Sofort\Payment;
   use Payum\Sofort\Core\SofortLibMultipay;

   class SofortUeberWeisung extends SofortLibMultipay {

    public function __construct($configKey) {
    parent::__construct($configKey);
    $this->_parameters['su'] = array();
   }
  }
</code>```

Why it is still showing the class is not found in Controller But i can see it is going to the class when i go to the definition of the new Class in my controller. Like the image attached.

Is there anything wrong i am doing please correct me,

答:
You are importing SofortUeberWeisung class in your controller which is spcified under this Sofort\Payment namespace, but not under this Payum\Sofort\Payment. So that should be in your controller

```<code>use Sofort\Payment\SofortUeberWeisung;
</code>```

Body:
Here is my controller that is using the class from Payum Module in vendor.

<?php
    namespace Orders\Controller;
    use Payum\Sofort;
    use Payum\Sofort\Payment\SofortUeberWeisung;

    class PaymentController extends AbstractActionController
     {

    protected $entityManager;

    public function sofortAction()
    {
      $Sofortueberweisung = new SofortUeberWeisung($configkey);

        $Sofortueberweisung->setAmount(10.21);
        $Sofortueberweisung->setCurrencyCode('EUR');
        //$Sofortueberweisung->setSenderSepaAccount('88888888', '12345678', 'Max Mustermann');
        $Sofortueberweisung->setSenderCountryCode('DE');
        $Sofortueberweisung->setReason('Testueberweisung', 'Verwendungszweck');
        $Sofortueberweisung->setSuccessUrl('http://www.google.de', true);
        $Sofortueberweisung->setAbortUrl('http://www.google.de');
        // $Sofortueberweisung->setNotificationUrl('http://www.google.de', 'loss,pending');
        // $Sofortueberweisung->setNotificationUrl('http://www.yahoo.com', 'loss');
        // $Sofortueberweisung->setNotificationUrl('http://www.bing.com', 'pending');
        // $Sofortueberweisung->setNotificationUrl('http://www.sofort.com', 'received');
        // $Sofortueberweisung->setNotificationUrl('http://www.youtube.com', 'refunded');
        // $Sofortueberweisung->setNotificationUrl('http://www.youtube.com', 'untraceable');
        $Sofortueberweisung->setNotificationUrl('http://www.twitter.com');
        $Sofortueberweisung->setCustomerprotection(true);

             $Sofortueberweisung->sendRequest();

            if($Sofortueberweisung->isError()) {
                //SOFORT-API didn't accept the data
                echo $Sofortueberweisung->getError();
            } else {
                //buyer must be redirected to $paymentUrl else payment cannot be successfully completed!
                $paymentUrl = $Sofortueberweisung->getPaymentUrl();
                header('Location: '.$paymentUrl);
            }
        }

    }

And The class is here in the Payum\Sofort\Payment folder

<?php

   namespace Sofort\Payment;
   use Payum\Sofort\Core\SofortLibMultipay;

   class SofortUeberWeisung extends SofortLibMultipay {

    public function __construct($configKey) {
    parent::__construct($configKey);
    $this->_parameters['su'] = array();
   }
  }

Why it is still showing the class is not found in Controller But i can see it is going to the class when i go to the definition of the new Class in my controller. Like the image attached.

Is there anything wrong i am doing please correct me,

Body:
You are importing SofortUeberWeisung class in your controller which is spcified under this Sofort\Payment namespace, but not under this Payum\Sofort\Payment. So that should be in your controller

use Sofort\Payment\SofortUeberWeisung;


问:
error while building the apk in android
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}
</code>```

答:
```<code>com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
</code>```

The underlying problem is imposed by the current set of Dalvik instructions. Specifically, any of the invoke-* methods. These expect a 16-bit argument, representing the target method's reference index. Being limited to 16-bits, valid values are between 0 and 65536. This means, that if you end up calling more than 65,536 defined methods, you are going to exceed this limit.

Solutions：
  MultiDex allows you to use multiple DEX files contained within one APK. With a few steps, your classes will split automatically into several DEX files (classes.dex, classes2.dex, classes3.dex, etc) in case you reach the method index limit.

Get more infomation : https://www.contentful.com/blog/2014/10/30/android-and-the-dex-64k-methods-limit/

Title: error while building the apk in android

Body:
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}

Body:
com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

The underlying problem is imposed by the current set of Dalvik instructions. Specifically, any of the invoke-* methods. These expect a 16-bit argument, representing the target method's reference index. Being limited to 16-bits, valid values are between 0 and 65536. This means, that if you end up calling more than 65,536 defined methods, you are going to exceed this limit.

Solutions：
  MultiDex allows you to use multiple DEX files contained within one APK. With a few steps, your classes will split automatically into several DEX files (classes.dex, classes2.dex, classes3.dex, etc) in case you reach the method index limit.

Get more infomation : https://www.contentful.com/blog/2014/10/30/android-and-the-dex-64k-methods-limit/


问:
How to swap two string variables in Java without using a third variable
How do I swap two string variables in Java without using a third variable, i.e. the temp variable?

```<code>String a = "one"
String b = "two"
String temp = null;
temp = a;
a = b;
b = temp;
</code>```

But here there is a third variable. We need to eliminate the use of the third variable.

答:
For String
Method 1:

```<code>public class SwapWithoutThirdVar{
public static void main (String args[]){
 String s1 ="one";
 String s2 ="two";
 s1= s1+s2;
 s2 = s1.substring(0,(s1.length()-s2.length()));
 s1 = s1.substring(s2.length());
 System.out.println("s1 == "+ s1);
 System.out.println("s2 == "+ s2);

}
}
</code>```

Method 2:

```<code>public class SwapWithoutThirdVar
{
public static void main (String[] args) throws java.lang.Exception
 {
 String s1 = "one";
 String s2 ="two";
 s1=s2+s1;
 s2=s1.replace(s2,"");
 s1=s1.replace(s2,"");
 System.out.println("S1 : "+s1);
 System.out.println("S2 : "+s2);
  }
}
</code>```

For Integers

public class SwapWithoutThirdVar {

```<code>public static void main(String a[]){
    int x = 10;
    int y = 20;
    x = x+y;
    y=x-y;
    x=x-y;
    System.out.println("After swap:");
    System.out.println("x value: "+x);
    System.out.println("y value: "+y);
}
}
</code>```

Body:
How do I swap two string variables in Java without using a third variable, i.e. the temp variable?

String a = "one"
String b = "two"
String temp = null;
temp = a;
a = b;
b = temp;

But here there is a third variable. We need to eliminate the use of the third variable.

Body:
For String
Method 1:

public class SwapWithoutThirdVar{
public static void main (String args[]){
 String s1 ="one";
 String s2 ="two";
 s1= s1+s2;
 s2 = s1.substring(0,(s1.length()-s2.length()));
 s1 = s1.substring(s2.length());
 System.out.println("s1 == "+ s1);
 System.out.println("s2 == "+ s2);

}
}

Method 2:

public class SwapWithoutThirdVar
{
public static void main (String[] args) throws java.lang.Exception
 {
 String s1 = "one";
 String s2 ="two";
 s1=s2+s1;
 s2=s1.replace(s2,"");
 s1=s1.replace(s2,"");
 System.out.println("S1 : "+s1);
 System.out.println("S2 : "+s2);
  }
}

For Integers

public class SwapWithoutThirdVar {

public static void main(String a[]){
    int x = 10;
    int y = 20;
    x = x+y;
    y=x-y;
    x=x-y;
    System.out.println("After swap:");
    System.out.println("x value: "+x);
    System.out.println("y value: "+y);
}
}


问:
Is n ≠ Θ(logn)?
Question is asked with an intent to get/let understand how to verify Asymptotic Θ notation. A Homework question. I am to show that n ≠ Θ(logn)

Solution: Yes, n ≠ Θ(logn).

```<code>c1logn ≤ n ≤ c2logn => c2≥n/logn, Ɐ n≥n0 - Impossible
</code>```

Why c2≥n/logn is not possible?

答: Think about it, c2 is a constant if your n gets large to what value will n/log(n) converge?</p>

Title: Is n ≠ Θ(logn)?

Body:
Question is asked with an intent to get/let understand how to verify Asymptotic Θ notation. A Homework question. I am to show that n ≠ Θ(logn)

Solution: Yes, n ≠ Θ(logn).

c1logn ≤ n ≤ c2logn => c2≥n/logn, Ɐ n≥n0 - Impossible

Why c2≥n/logn is not possible?


答:
I suggest you add media query in your css.

A media query consists of an optional media type and zero or more expressions that limit the style sheets' scope by using media features, such as width, height, and color. Media queries, added in CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself.

Syntax:

```<code>@media (max-width: 600px) {
   .facet_sidebar {
   display: none;
   }
}
</code>```

You can learn it more in this site:

https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Title: Unable to center content using margin auto

Body:
When the screen size is less than 768px, the 3 boxes are aligned to the left. I'm having a hard time trying to make them appear center.

I managed to center it by setting margin-left to some value however, it isn't responsive afterwards.

Here's the code:

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

2015/16

The Best FIFA Men's Player 2016

FIFA Club World Cup

France Football Ballon D'Or 2016

UEFA Best Player in Europe

UEFA Euro 2016 (Portugal)

UEFA Champions League (Real Madrid)

2014/15

Pichichi Award

European Golden Boot 2015

FIFA Ballon D'Or 2014

Globe Soccer Best Player of the Year

Globe Soccer Fan's Favourite Player Award

IFFHS Trophy for Best Striker  on the planet

2013/14

Club World Cup

BBC Overseas Sports  Personality Award

World's Top  Goalscorer 2013

Pichichi Award

Best Player, Best Forward in La Liga

UEFA Best Player in Europe

CSS:

 .bg_color {
    background: #ECFEAA;
}

.stats_box {
    margin: 20px;
    padding: 20px 40px 40px;
    max-width: 400px;
    text-align: left;
    background: #fff;
    border-bottom: 4px solid #ccc;
    border-radius: 6px;

}

@media only screen and (max-width: 768px) {
  .stats_box {
    width: 100%;
    margin-left: 200px;
  }
}

Any possible solution for this? And why isn't margin:0 auto not working here?

Link to the code: CodePen

Body:
I suggest you add media query in your css.

A media query consists of an optional media type and zero or more expressions that limit the style sheets' scope by using media features, such as width, height, and color. Media queries, added in CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself.

Syntax:

@media (max-width: 600px) {
   .facet_sidebar {
   display: none;
   }
}

You can learn it more in this site:

https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries


问:
How to get JSON output as NSString
Working in Objective-C where I need to parse JSON. So after parsing successfully.

Below is my code :

```<code>-(instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {

        if ([dict isKindOfClass:[NSDictionary class]]) {
            self.allKeysArray = [dict allKeys];

 if ([self.allKeysArray containsObject:@"nDetail"]) {

                if ([dict valueForKey:@"nDetail"]) {

 _tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
         }
     }
 }

NSLog(@"N Array : @%@", _tempNutrientArray);

}
</code>```

I need to convert this in string format each an every value.

My output :

```<code>N Array : @(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)
</code>```

Required Output :

```<code> N Array : @("ENER-","FAT","FASAT","CHOAVL","SUGAR-","PRO-","NACL")
</code>```

So how should I convert it to string format. Please help me.

答:
Converting Array to String

```<code>NSString * myString = [_tempNutrientArray componentsJoinedByString:@""];
</code>```

If you want any Character between the string give it in componentsJoinedByString:@"GIVE_IT_HERE"

Title: How to get JSON output as NSString

Body:
Working in Objective-C where I need to parse JSON. So after parsing successfully.

Below is my code :

-(instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {

        if ([dict isKindOfClass:[NSDictionary class]]) {
            self.allKeysArray = [dict allKeys];

 if ([self.allKeysArray containsObject:@"nDetail"]) {

                if ([dict valueForKey:@"nDetail"]) {

 _tempNutrientArray = [[[dict valueForKey:@"nDetail"] valueForKey:@"nTypeCode"] valueForKey:@"value"];
         }
     }
 }

NSLog(@"N Array : @%@", _tempNutrientArray);

}

I need to convert this in string format each an every value.

My output :

N Array : @(
    "ENER-",
    FAT,
    FASAT,
    CHOAVL,
    "SUGAR-",
    "PRO-",
    NACL
)

Required Output :

 N Array : @("ENER-","FAT","FASAT","CHOAVL","SUGAR-","PRO-","NACL")

So how should I convert it to string format. Please help me.

Body:
Converting Array to String

NSString * myString = [_tempNutrientArray componentsJoinedByString:@""];

If you want any Character between the string give it in componentsJoinedByString:@"GIVE_IT_HERE"


问:
jquery: duplicate and paste html
hmm ok heres the shortened code

```<code> <div id="SideCategoryList">
        <div class="BlockContent">
           <ul>
              <li><a href="#">Link A</a></li>
              <li><a href="#">Link B</a></li>
          </ul>
       </div>
     </div>
    <div id="navcont">
    <ul class="menu" id="menu">
      <li id="hov"><a href="#">Top Link</a></li>
      <li><a href="#">Bottom Link</a></li>
    </ul>
   </div>
</code>```

i want to use jquery to duplicate whats in the first ul into the first li in the #menu so it looks like this

```<code><div id="SideCategoryList">
        <div class="BlockContent">
           <ul>
              <li><a href="#">Link A</a></li>
              <li><a href="#">Link B</a></li>
          </ul>
       </div>
     </div>
    <div id="navcont">
      <ul class="menu" id="menu">
         <li id="hov"><a href="#">Top Link</a>
            <ul>
               <li><a href="#">Link A</a></li>
               <li><a href="#">Link B</a></li>
            </ul>
        </li>
        <li><a href="#">Bottom Link</a></li>
      </ul>
   </div>
</code>```

so the finished product will be a 2 level list... let me know if this is makin sense lol

答:
```<code>var content = $('#BlockContent').html();

$('#hov').append(content);
</code>```

will append the content at the end of all the innerhtml of $('#hov').

ie after the Top Link.

hope that helps :)

Title: jquery: duplicate and paste html

Body:
hmm ok heres the shortened code

Link A

Link B

Top Link

Bottom Link

i want to use jquery to duplicate whats in the first ul into the first li in the #menu so it looks like this

Link A

Link B

Top Link

Link A

Link B

Bottom Link

so the finished product will be a 2 level list... let me know if this is makin sense lol

Body:
var content = $('#BlockContent').html();

$('#hov').append(content);

will append the content at the end of all the innerhtml of $('#hov').

ie after the <a href="#">Top Link</a>.

hope that helps :)


问:
Wrong text entered by sendkeys
I am trying to automate a webpage where i have to enter credit card details.
During manually entering CVV of the credit card I am able to move forward, but while entering value using sendkeys it throws an error.

```<code>driver.findElement(By.name("password_ccCvv")).click();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");
</code>```

I tried clicking on the textbox and then entered value. This also didn't work.

While entering value through send keys, i cant see what value is being sent because its encrypted.

答:
If on text box already text is there first clear it using following:

```<code>driver.findElement(By.name("password_ccCvv")).clear();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");
</code>```

Or try only this

```<code>driver.findElement(By.name("password_ccCvv")).sendKeys("999");
</code>```

Title: Wrong text entered by sendkeys

Body:
I am trying to automate a webpage where i have to enter credit card details.
During manually entering CVV of the credit card I am able to move forward, but while entering value using sendkeys it throws an error.

driver.findElement(By.name("password_ccCvv")).click();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");

I tried clicking on the textbox and then entered value. This also didn't work.

While entering value through send keys, i cant see what value is being sent because its encrypted.

Body:
If on text box already text is there first clear it using following:

driver.findElement(By.name("password_ccCvv")).clear();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");

Or try only this

driver.findElement(By.name("password_ccCvv")).sendKeys("999");


问:
Duplicate Record display in Table
I'm working on software everything work perfectly, but when I print its record from multiple table is show duplicate entry for each row

I have no idea why this thing happened.

Here is my Query which gets data from table and display using PHP

```<code>Select item_id,item_name,rci.item_shape,
remaing_quantity,rci.child_date from rads_childrenitem rci ,
add_itemchildren aic where aic.id = rci.item_id group by
rci.id,item_name,rci.item_shape, remaing_quantity order by rci.id desc
</code>```

Image attached for better understanding.

答: It is because you have those multiple records in your database. "Stock-Out Date to Dhoku-Hassu" is different values 500 and 200. Your GROUP BY does not group them, because it is different values</p>

Title: Duplicate Record display in Table

Body:
I'm working on software everything work perfectly, but when I print its record from multiple table is show duplicate entry for each row

I have no idea why this thing happened.

Here is my Query which gets data from table and display using PHP

Select item_id,item_name,rci.item_shape,
remaing_quantity,rci.child_date from rads_childrenitem rci ,
add_itemchildren aic where aic.id = rci.item_id group by
rci.id,item_name,rci.item_shape, remaing_quantity order by rci.id desc

Image attached for better understanding.


问:
How to avoid Generics in this case?
```<code>class Attribute<T>{
   private T attr;
   public Attribute(T attr){
      this.attr = attr;
   }
}

Class Matrix<T>{
   private String name;
   List<Attribute<T>> list;

   public Matrix(String name, T t){
     this.name = name;
     list = new ArrayList<>();
     list.add(new Attribute<T>(t));
  }
}

 interface Extractor<T> {
    public List<Matrix<T>> extract();
}

InfoExtractor implements Extractor<String>{

    public List<Matrix<String>> extract(){
       List<Matrix<String>> matrixList = new ArrayList<>();

        // The problem is here!!!!
        matrixList.add(new Matrix<String>("abc"));
    }
 }

 Document<T>{
      Map<String, List<Matrix<T>>> matrixMap;

        public void process(){
        ...
         Extractor<T> extractor = (Extractor<T>) new StringExtractor(sent);
        List<Matrix<T>> matrix = extractor.extract(...);
   }
</code>```

My question is, is there a way to avoid defining Matrix as a generic type ? The reason I want to avoid is that the "List<Attribute<T>> " is used in multiple other classes, either as private member variables, or method return types. Due to Attribute, it seems I have to define some other related classes as generic types too, which causes my problem.

In this case, is there a way to not define Matrix as generic, but keep the  "list" variable as a generic type?

答:
Your problem lies not in the generic implementation, but in its usage:

```<code>class InfoExtractor implements Extractor{

    // The problem is actually here
    public <T> List<Matrix<T>> extract(){
       List<Matrix<T>> matrixList = new ArrayList<>(); //and here

        // "The problem is here!!!!"
        matrixList.add(new Matrix<String>("abc"));
    }
}
</code>```

The <T> indicates that you are binding a new generic type relative to the method invocation. In short, a new T type just for this method's execution. You also make a List<Matrix<T>> but then attempt to add a new Matrix<String> back. If you know the list is going to be of the type Matrix<String>, then you can specify that in InfoExtractor:

```<code>//If you cannot generify the interface for some reason
interface Extractor {
    public List<? extends Matrix<?>> extract(); //explained at bottom
}

//IDEALLY, then implement Extractor<String> instead
interface Extractor<T> {
    public List<Matrix<T>> extract();
}

class InfoExtractor implements Extractor { //or Extractor<String>

    public List<Matrix<String>> extract() {
        List<Matrix<String>> matrixList = new ArrayList<>();
        matrixList.add(new Matrix<>("abc"));
        return matrixList;
    }
}
</code>```

Of course, you can see the method signature for Extractor changed. Due to using a nested generic on the return type, things will get a bit messy for type matching at compile-time. The <?> for the Matrix is fairly self-explanatory, we're returning multiple and possibly unknown types inside of the Matrix.

By specifying ? extends Matrix on Extractor, we're specifying the proper variance. Concrete generics are invariant, thus a List<Toyota> isn't a List<Car>, even if Toyota is a subclass of Car. If we want the Matrix to be covariant, then we need the bounding on Matrix as well unfortunately. This means in effect, ignoring Liskov's substitution principal, we'd essentially be referencing the concrete subclasses for the extractors (InfoExtractor ex vs Extractor ex), especially from a usability standpoint (as the concrete classes can return proper type safety whereas the interface cannot).

This of course, is handled much more sanely/cleanly when you specify the <T> for the matrices in the list as a class-level generic type.

Title: How to avoid Generics in this case?

Body:
class Attribute<T>{
   private T attr;
   public Attribute(T attr){
      this.attr = attr;
   }
}

Class Matrix<T>{
   private String name;
   List<Attribute<T>> list;

   public Matrix(String name, T t){
     this.name = name;
     list = new ArrayList<>();
     list.add(new Attribute<T>(t));
  }
}

 interface Extractor<T> {
    public List<Matrix<T>> extract();
}

InfoExtractor implements Extractor<String>{

    public List<Matrix<String>> extract(){
       List<Matrix<String>> matrixList = new ArrayList<>();

        // The problem is here!!!!
        matrixList.add(new Matrix<String>("abc"));
    }
 }

 Document<T>{
      Map<String, List<Matrix<T>>> matrixMap;

        public void process(){
        ...
         Extractor<T> extractor = (Extractor<T>) new StringExtractor(sent);
        List<Matrix<T>> matrix = extractor.extract(...);
   }

My question is, is there a way to avoid defining Matrix as a generic type ? The reason I want to avoid is that the "List<Attribute<T>> " is used in multiple other classes, either as private member variables, or method return types. Due to Attribute, it seems I have to define some other related classes as generic types too, which causes my problem.

In this case, is there a way to not define Matrix as generic, but keep the  "list" variable as a generic type?

Body:
Your problem lies not in the generic implementation, but in its usage:

class InfoExtractor implements Extractor{

    // The problem is actually here
    public <T> List<Matrix<T>> extract(){
       List<Matrix<T>> matrixList = new ArrayList<>(); //and here

        // "The problem is here!!!!"
        matrixList.add(new Matrix<String>("abc"));
    }
}

The <T> indicates that you are binding a new generic type relative to the method invocation. In short, a new T type just for this method's execution. You also make a List<Matrix<T>> but then attempt to add a new Matrix<String> back. If you know the list is going to be of the type Matrix<String>, then you can specify that in InfoExtractor:

//If you cannot generify the interface for some reason
interface Extractor {
    public List<? extends Matrix<?>> extract(); //explained at bottom
}

//IDEALLY, then implement Extractor<String> instead
interface Extractor<T> {
    public List<Matrix<T>> extract();
}

class InfoExtractor implements Extractor { //or Extractor<String>

    public List<Matrix<String>> extract() {
        List<Matrix<String>> matrixList = new ArrayList<>();
        matrixList.add(new Matrix<>("abc"));
        return matrixList;
    }
}

Of course, you can see the method signature for Extractor changed. Due to using a nested generic on the return type, things will get a bit messy for type matching at compile-time. The <?> for the Matrix is fairly self-explanatory, we're returning multiple and possibly unknown types inside of the Matrix.

By specifying ? extends Matrix on Extractor, we're specifying the proper variance. Concrete generics are invariant, thus a List<Toyota> isn't a List<Car>, even if Toyota is a subclass of Car. If we want the Matrix to be covariant, then we need the bounding on Matrix as well unfortunately. This means in effect, ignoring Liskov's substitution principal, we'd essentially be referencing the concrete subclasses for the extractors (InfoExtractor ex vs Extractor ex), especially from a usability standpoint (as the concrete classes can return proper type safety whereas the interface cannot).

This of course, is handled much more sanely/cleanly when you specify the <T> for the matrices in the list as a class-level generic type.


问:
Angularjs routing ejs static files in "views" folder from "public" folder of express.js
Here is my project structure.

I am trying to call the ejs file (app > views > list.ejs) which is in "views" folder from the angular routing file (app > public > main.js) which is in "public" folder. But the list.ejs is not loading.

/************main.js****************/
var fsApp=angular.module('chart-app');
fsApp.config(function($routeProvider) {
 $routeProvider
 .when('/', {
 templateUrl: 'list.ejs',
 controller: 'listCtrl'
})

/*In my server.js server file I am calling the files in public folder this way: */
app.use('/static',express.static(__dirname + '/public'));
app.get('/',function(req,res){
  res.render('index.ejs');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--In index.ejs (where my <ng-view></ng-view> is) I am including the link for static files:-->

<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<script src="/static/angular-route.js"></script>
<script src="/static/main.js"></script>
</head>
<body ng-app="chart-app" class="container-fluid">
<div ng-controller="fairshareCtrl">
 <div class="row" ng-view></div>
</div>
</body></code>```

Is there anything more I have to do on the server file? What am I missing?

答:
public folder can not access the files that outside that folder, i.e. other folders like node_modules, views routes etc. That is why you are not able to load list.ejs from your angular main.js or angular-route.js file.

Views are used by express to render the view template(ejs) based on the request sent to the backend. They cant be used for frontend routing. They can only be accessed by the exprss app, but not the public folder.

For frontend routing, you will need to store all the templates in your public folder only.

I will suggest that you create a templates folder in your public folder, and use that address in your angular routing.

```<code>public
  --templates
     --list.html
  --angular-route.js
  --main.css
  --main.js
</code>```

use it like this in your angular routing.

```<code>fsApp.config(function($routeProvider) {
 $routeProvider
 .when('/', {
    templateUrl: 'templates/list.html',
    controller: 'listCtrl'
})
</code>```

I think you might need to include ejs.js in your view file, to support ejs templating in frontend. Read ejs getting started doc for more information on how to do it.

I hope this helps you.

Body:
Here is my project structure.

I am trying to call the ejs file (app > views > list.ejs) which is in "views" folder from the angular routing file (app > public > main.js) which is in "public" folder. But the list.ejs is not loading.

/************main.js****************/
var fsApp=angular.module('chart-app');
fsApp.config(function($routeProvider) {
 $routeProvider
 .when('/', {
 templateUrl: 'list.ejs',
 controller: 'listCtrl'
})

/*In my server.js server file I am calling the files in public folder this way: */
app.use('/static',express.static(__dirname + '/public'));
app.get('/',function(req,res){
  res.render('index.ejs');
});

Is there anything more I have to do on the server file? What am I missing?

Body:
public folder can not access the files that outside that folder, i.e. other folders like node_modules, views routes etc. That is why you are not able to load list.ejs from your angular main.js or angular-route.js file.

Views are used by express to render the view template(ejs) based on the request sent to the backend. They cant be used for frontend routing. They can only be accessed by the exprss app, but not the public folder.

For frontend routing, you will need to store all the templates in your public folder only.

I will suggest that you create a templates folder in your public folder, and use that address in your angular routing.

public
  --templates
     --list.html
  --angular-route.js
  --main.css
  --main.js

use it like this in your angular routing.

fsApp.config(function($routeProvider) {
 $routeProvider
 .when('/', {
    templateUrl: 'templates/list.html',
    controller: 'listCtrl'
})

I think you might need to include ejs.js in your view file, to support ejs templating in frontend. Read ejs getting started doc for more information on how to do it.

I hope this helps you.


问:
PHP-SYMFONY3 add a formbuilder in a formbuilder
I'm creating a form for an entity (sample) that contains a known number of form of an other entity (Result).

Sample has a collection of Result. (and also a collection of Parameter)

In my controller the code look like this

```<code>$em = $this->getDoctrine()->getManager();
$sample = $em->getRepository('ReceptionBundle:Sample')->find($id);
$formBuilder = $this->createFormBuilder();

$i = 0;
foreach ($sample->getParameter() as $param){

    $fb = $this->get('form.factory')->createNamedBuilder($i, FormType::Class, $sample);
    if ($param->getCriteria()===false){
        $fb->add('result', Result1Type::class, array('data_class'=>null));
    }
    else {
        $fb->add('result', Result2Type::class, array('data_class'=>null));
    }
    $formBuilder->add($fb);
    $i++;

}
$formBuilder->add('save',      SubmitType::class);
$form = $formBuilder->getForm();
</code>```

When I try with this I have an error before to see the form :

The form's view data is expected to be an instance of class ReceptionBundle\Entity\Result, but is an instance of class Doctrine\ORM\PersistentCollection. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms an instance of class Doctrine\ORM\PersistentCollection to an instance of ReceptionBundle\Entity\Result.

So, when I try to set the "data_class" option to null, I can display the form, but I can't submit it :

Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "ReceptionBundle\Entity\Sample#$result", got "boolean" instead.

I don't know why is receiving a boolean.

答:
Finaly, I didn,t use the Result1Type::class, it was not necessary.
I use the collection type, the thing is that you can create directly the new results in the controller this way

```<code>foreach ($sample->getParameter() as $param){

$result = new Result();
$sample->addResult($result);
}
 $form = $this->createForm(AnalyseType::class, $sample);
</code>```

The result is directly syncronised with the form.

Body:
I'm creating a form for an entity (sample) that contains a known number of form of an other entity (Result).

Sample has a collection of Result. (and also a collection of Parameter)

In my controller the code look like this

$em = $this->getDoctrine()->getManager();
$sample = $em->getRepository('ReceptionBundle:Sample')->find($id);
$formBuilder = $this->createFormBuilder();

$i = 0;
foreach ($sample->getParameter() as $param){

    $fb = $this->get('form.factory')->createNamedBuilder($i, FormType::Class, $sample);
    if ($param->getCriteria()===false){
        $fb->add('result', Result1Type::class, array('data_class'=>null));
    }
    else {
        $fb->add('result', Result2Type::class, array('data_class'=>null));
    }
    $formBuilder->add($fb);
    $i++;

}
$formBuilder->add('save',      SubmitType::class);
$form = $formBuilder->getForm();

When I try with this I have an error before to see the form :

The form's view data is expected to be an instance of class ReceptionBundle\Entity\Result, but is an instance of class Doctrine\ORM\PersistentCollection. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms an instance of class Doctrine\ORM\PersistentCollection to an instance of ReceptionBundle\Entity\Result.

So, when I try to set the "data_class" option to null, I can display the form, but I can't submit it :

Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "ReceptionBundle\Entity\Sample#$result", got "boolean" instead.

I don't know why is receiving a boolean.

Body:
Finaly, I didn,t use the Result1Type::class, it was not necessary.
I use the collection type, the thing is that you can create directly the new results in the controller this way

foreach ($sample->getParameter() as $param){

$result = new Result();
$sample->addResult($result);
}
 $form = $this->createForm(AnalyseType::class, $sample);

The result is directly syncronised with the form.