问:
javascript: how to make function run faster
so i have to write a function which meets the following requirements:

```<code>Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example:

For sequence = [1, 3, 2, 1], the output should be
almostIncreasingSequence(sequence) = false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
almostIncreasingSequence(sequence) = true.

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

Input/Output

[time limit] 4000ms (js)
[input] array.integer sequence

Guaranteed constraints:
2 ≤ sequence.length ≤ 105,
-105 ≤ sequence[i] ≤ 105.
</code>```

so my code works except for one problem--there are 30 tests it has to pass with the time constraint of 4000ms, but it always times out on the 30th test, every time. i have tried modifying it so that it runs faster, but each time i do so it no longer works correctly. although i technically only have to write one function, i broke it up into three separate functions. here's my code:

```<code>var greater = function(a, b) {
  if (a < b) {
    return true
  } else {
    return false
  }
}

function greaterThan(arr) {
  for (var i = 0; i < arr.length-1; i++) {
    var curr = arr[i]
    var next = arr[i + 1]
    if (greater(curr, next) === false) {
      return false
    }
  }
  return true
}

function almostIncreasingSequence(sequence) {
  for(var i = 0; i < sequence.length; i++) {
    var newArr = sequence.slice()
    newArr.splice(i, 1)
    if (greaterThan(newArr) === true) {
      return true
    }
  }
  return false
}
</code>```

so how can i make it run faster without using two for-loops/iterations to do this?

答:
Improving the algorithm may bring better results than improving the code. Here's the problem:

If the sequence is not strictly increasing at index i, such that  a[i]>=a[i+1] is true, either a[i] or  a[i+1] must be removed to possibly make the array strictly increasing - they can't both be left in place.

If the input array is to be fixable by removing only one element, and it decreases after the ith element it must become strictly increasing by removing the element with subscript i or (i+1).

Compare the efficiency of checking the original array and at most two sub arrays before returning true or false, with checking the same number of arrays as the original array's length. I'll leave re-writing the code to you - it's not my homework :-)

Body:
so i have to write a function which meets the following requirements:

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example:

For sequence = [1, 3, 2, 1], the output should be
almostIncreasingSequence(sequence) = false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
almostIncreasingSequence(sequence) = true.

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

Input/Output

[time limit] 4000ms (js)
[input] array.integer sequence

Guaranteed constraints:
2 ≤ sequence.length ≤ 105,
-105 ≤ sequence[i] ≤ 105.

so my code works except for one problem--there are 30 tests it has to pass with the time constraint of 4000ms, but it always times out on the 30th test, every time. i have tried modifying it so that it runs faster, but each time i do so it no longer works correctly. although i technically only have to write one function, i broke it up into three separate functions. here's my code:

var greater = function(a, b) {
  if (a < b) {
    return true
  } else {
    return false
  }
}

function greaterThan(arr) {
  for (var i = 0; i < arr.length-1; i++) {
    var curr = arr[i]
    var next = arr[i + 1]
    if (greater(curr, next) === false) {
      return false
    }
  }
  return true
}

function almostIncreasingSequence(sequence) {
  for(var i = 0; i < sequence.length; i++) {
    var newArr = sequence.slice()
    newArr.splice(i, 1)
    if (greaterThan(newArr) === true) {
      return true
    }
  }
  return false
}

so how can i make it run faster without using two for-loops/iterations to do this?


来源: stackexchange

问:
How do I write a unit test that verifies a subroutine is called?
```<code>Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class
</code>```

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?

答: You would need to have CallThis make some kind of outside effect that you can test on. If you code this yourself, then use a variable scoped e.g. in the class, before calling the CallThis method, set this variable to false, then inside the CallThis method, set it to true - and then thest that it has become true in the test.</p>

ContentLicense: CC BY-SA 2.5

Body:
Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?


问:
C# deserialize xml using linq
I have the following xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<Launchpad>
  <Shortcuts>
    <Shortcut Id="1">
      <Type>Folder</Type>
       <FullPath>C:\bla\bla\bla</FullPath>
       <Name>Proximity</Name>
    </Shortcut>
    <Shortcut Id="2">
      <Type>Folder</Type>
      <FullPath>C:\bla</FullPath>
      <Name>Visual Studio 2017</Name>
    </Shortcut>
  </Shortcuts>
</Launchpad>
</code>```

I am trying to deserialize to an object like this: (Tried query syntax first, didn't work either)

```<code>XDocument xd = XDocument.Load(FullPath);

// query syntax
//var shortcuts = (from s in xd.Descendants("Shortcuts")
//                 select new Shortcut()
//                 {
//                   Id = Convert.ToInt32(s.Attribute("Id")),
//                   TypeOfLink = GetTypeFromString(s.Descendants("Type")
//                                .First()
//                                .Value),
//                   FullPathToTarget = s.Descendants("FullPath")
//                                         .First()
//                                         .Value,
//                   Name = s.Descendants("Name").First().Value,
//                 }).ToList();

// method syntax
List<Shortcut> shortcuts = xd.Descendants("Shortcuts")
                             .Select(s =>
               new Shortcut()
               {
                 //Id = Convert.ToInt32(s.Attribute("Id")),
                 TypeOfLink = GetTypeFromString(s.Descendants("Type")
                                                 .First().Value),
                 FullPathToTarget = s.Descendants("FullPath")
                                                 .First().Value,
                 Name = s.Descendants("Name")
                         .First().Value,
               }).ToList();
return shortcuts;
</code>```

For some reason I only get a single shortcut object in the list. Also, for some reason, the s.Attribute("Id") is null.

If anyone has any suggestions to improve the linq query or why the attribute is not working it would be a great help

答:
I get the full list by selecting the Shortcut as a descendant of Shortcuts.

Also, ID is an XAttribute so you cant convert it to int.

You need to use Value to get the attributes value.

```<code>XDocument xd = XDocument.Load(ms);
XElement root = xd.Document.Root;
var list = root.Descendants("Shortcuts").Descendants("Shortcut").Select(x =>
    new Shortcut()
    {
        Id = Convert.ToInt32(x.Attribute("Id").Value),
        TypeOfLink = GetTypeFromString(x.Descendants("Type")
                                        .First().Value),
        FullPathToTarget = x.Descendants("FullPath")
                                        .First().Value,
        Name = x.Descendants("Name").First().Value
        }).ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# deserialize xml using linq

Body:
I have the following xml file

<?xml version="1.0" encoding="utf-8"?>
<Launchpad>
  <Shortcuts>
    <Shortcut Id="1">
      <Type>Folder</Type>
       <FullPath>C:\bla\bla\bla</FullPath>
       <Name>Proximity</Name>
    </Shortcut>
    <Shortcut Id="2">
      <Type>Folder</Type>
      <FullPath>C:\bla</FullPath>
      <Name>Visual Studio 2017</Name>
    </Shortcut>
  </Shortcuts>
</Launchpad>

I am trying to deserialize to an object like this: (Tried query syntax first, didn't work either)

XDocument xd = XDocument.Load(FullPath);

// query syntax
//var shortcuts = (from s in xd.Descendants("Shortcuts")
//                 select new Shortcut()
//                 {
//                   Id = Convert.ToInt32(s.Attribute("Id")),
//                   TypeOfLink = GetTypeFromString(s.Descendants("Type")
//                                .First()
//                                .Value),
//                   FullPathToTarget = s.Descendants("FullPath")
//                                         .First()
//                                         .Value,
//                   Name = s.Descendants("Name").First().Value,
//                 }).ToList();

// method syntax
List<Shortcut> shortcuts = xd.Descendants("Shortcuts")
                             .Select(s =>
               new Shortcut()
               {
                 //Id = Convert.ToInt32(s.Attribute("Id")),
                 TypeOfLink = GetTypeFromString(s.Descendants("Type")
                                                 .First().Value),
                 FullPathToTarget = s.Descendants("FullPath")
                                                 .First().Value,
                 Name = s.Descendants("Name")
                         .First().Value,
               }).ToList();
return shortcuts;

For some reason I only get a single shortcut object in the list. Also, for some reason, the s.Attribute("Id") is null.

If anyone has any suggestions to improve the linq query or why the attribute is not working it would be a great help

Body:
I get the full list by selecting the Shortcut as a descendant of Shortcuts.

Also, ID is an XAttribute so you cant convert it to int.

You need to use Value to get the attributes value.

XDocument xd = XDocument.Load(ms);
XElement root = xd.Document.Root;
var list = root.Descendants("Shortcuts").Descendants("Shortcut").Select(x =>
    new Shortcut()
    {
        Id = Convert.ToInt32(x.Attribute("Id").Value),
        TypeOfLink = GetTypeFromString(x.Descendants("Type")
                                        .First().Value),
        FullPathToTarget = x.Descendants("FullPath")
                                        .First().Value,
        Name = x.Descendants("Name").First().Value
        }).ToList();


问:
keyboardWillHide notification malfunction
I have:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}
</code>```

And also:

```<code>func keyboardWillShow(notification: NSNotification) {

    if (self.view.center.y == maxPointY){
        self.view.frame.origin.y -= maxPointY/2
    }
}

func keyboardWillHide(notification: NSNotification) {

    self.view.frame.origin.y += maxPointY/2
}
</code>```

The problem is that when I click on a textfield that should pop up the keyboard, keyboardWillHide gets called.

I have this as well:

```<code>func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    usernameTextField.resignFirstResponder()
    passwordTextField.resignFirstResponder()
    textField.resignFirstResponder()
    return true
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}
</code>```

答:
It was this tidbit:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
</code>```

I didn't call super.touchesBegan. I had to change it to:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
super.touchesBegan(touches , with:event)
}
</code>```

Body:
I have:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

And also:

func keyboardWillShow(notification: NSNotification) {

    if (self.view.center.y == maxPointY){
        self.view.frame.origin.y -= maxPointY/2
    }
}

func keyboardWillHide(notification: NSNotification) {

    self.view.frame.origin.y += maxPointY/2
}

The problem is that when I click on a textfield that should pop up the keyboard, keyboardWillHide gets called.

I have this as well:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    usernameTextField.resignFirstResponder()
    passwordTextField.resignFirstResponder()
    textField.resignFirstResponder()
    return true
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

Body:
It was this tidbit:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}

I didn't call super.touchesBegan. I had to change it to:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
super.touchesBegan(touches , with:event)
}


问:
Determining the Big-O of this algorithm
I'm trying to understand what the Big-O is of the code below.

What the code is supposed to do

Essentially, I am trying to select a subset (max size = selectionSize) of random nodes and any edges that exists between them. The selection of random nodes is done in the while loop. After having done that, I want to select any edges that exist between the selected nodes.

What I think it is & why

<s>I think the running time is O = n^2 where n=selectionSize. The reason is: even though I can increase the size of the elements in nodes (e.g. make it 10000), I don't believe it can affect the algorithm since I am only looping through the maximum of selectionSize. The only reason I am a bit worried that this is wrong is because of the while loop, where I select random elements from the list up until I have enough. While this can take quite long (because it is random), I don't think it affects the overall output in terms of time.</s>
Edit: ugh on second thoughts... Nevermind... The nodes size does affect it (since node.getNeighbors()can be at most the size of the nodes).. So I think that if the selectionSize is equal to the size of nodes, the running time is O=n^2 where n=size of nodes.

Any tips/hints would be appreciated.

Code

```<code>// nodes and selectionSize are my input:
int[] nodes = {1,2,3...,1000}; // 1000 elements
int selectionSize = 500; // This can be at most the size of the elements (in this case 1000)

run_algo(nodes, selectionSize);

public void run_algo(int[] nodes, int selectionSize) {
    randomNodesList = {};

    while(randomNodesList < selectionSize) {
        randomNode = selectRandomNode(nodes); // Assume O(1)

        if(!randomNodesList.exists(randomNode)) { // Assume O(1)
            randomNodesList.push_back(randomNode); // Assume O(1)
        }
    }

    foreach(node in randomNodesList) {
        foreach(neighbor in node.getNeighbors()) { // Max. nodes size (in this case 1000)
            if (!randomNodesList.exists(neighbor)) { // Assume O(1)
                AddEdge(node, neighbor); // Takes O(1) time
            }
        }
    }
}
</code>```

答:
if selectRandomNode(nodes); works with replacement (the same node can be picked twice), then the big o is not defined, since you have a probably infinite loop (you can end up picking the same node again and again).

If it works without replacement, then it's O(n^2) (in the worst case, every node may be connected to every other node).

Notes on selecting without replacement:

Consider the case when you are given an array of size n, say A and an empty array, B. All the elements in A are unique.

The task is to fill B with n elements randomly selected from A. It is desired that there should be at least k unique elements in B.

It can be shown that the probability of having more than k unique items increases with increasing n (I have added the equations after the plot).

Thus, in practice, the probability of the loop finishing in a single pass (i.e. in less than n steps) gets large as the difference in n and k increases.
It's very intuitive if you think about it, the math is just cherry on the top.

```<code>def k_numerator(n, k):
    res = 0
    sign = 1
    for i in range(k, 0, -1):
        pow_term = (i ** n)
        comb_term = comb(k, i)
        prod = pow_term * comb_term
        prod = prod * sign
        res = res + prod
        sign = sign * -1
    return res

def p_exactly_k(n, k):
    """
    Returns the probability of `B` containing exactly `k` unique elements
    (also see notes above)
    """

    return (comb(n, k) * k_numerator(n, k)) / (n ** n)
</code>```

Title: Determining the Big-O of this algorithm

Body:
I'm trying to understand what the Big-O is of the code below.

What the code is supposed to do

Essentially, I am trying to select a subset (max size = selectionSize) of random nodes and any edges that exists between them. The selection of random nodes is done in the while loop. After having done that, I want to select any edges that exist between the selected nodes.

What I think it is & why

<s>I think the running time is O = n^2 where n=selectionSize. The reason is: even though I can increase the size of the elements in nodes (e.g. make it 10000), I don't believe it can affect the algorithm since I am only looping through the maximum of selectionSize. The only reason I am a bit worried that this is wrong is because of the while loop, where I select random elements from the list up until I have enough. While this can take quite long (because it is random), I don't think it affects the overall output in terms of time.</s>
Edit: ugh on second thoughts... Nevermind... The nodes size does affect it (since node.getNeighbors()can be at most the size of the nodes).. So I think that if the selectionSize is equal to the size of nodes, the running time is O=n^2 where n=size of nodes.

Any tips/hints would be appreciated.

Code

// nodes and selectionSize are my input:
int[] nodes = {1,2,3...,1000}; // 1000 elements
int selectionSize = 500; // This can be at most the size of the elements (in this case 1000)

run_algo(nodes, selectionSize);

public void run_algo(int[] nodes, int selectionSize) {
    randomNodesList = {};

    while(randomNodesList < selectionSize) {
        randomNode = selectRandomNode(nodes); // Assume O(1)

        if(!randomNodesList.exists(randomNode)) { // Assume O(1)
            randomNodesList.push_back(randomNode); // Assume O(1)
        }
    }

    foreach(node in randomNodesList) {
        foreach(neighbor in node.getNeighbors()) { // Max. nodes size (in this case 1000)
            if (!randomNodesList.exists(neighbor)) { // Assume O(1)
                AddEdge(node, neighbor); // Takes O(1) time
            }
        }
    }
}

Body:
if selectRandomNode(nodes); works with replacement (the same node can be picked twice), then the big o is not defined, since you have a probably infinite loop (you can end up picking the same node again and again).

If it works without replacement, then it's O(n^2) (in the worst case, every node may be connected to every other node).

Notes on selecting without replacement:

Consider the case when you are given an array of size n, say A and an empty array, B. All the elements in A are unique.

The task is to fill B with n elements randomly selected from A. It is desired that there should be at least k unique elements in B.

It can be shown that the probability of having more than k unique items increases with increasing n (I have added the equations after the plot).

Thus, in practice, the probability of the loop finishing in a single pass (i.e. in less than n steps) gets large as the difference in n and k increases.
It's very intuitive if you think about it, the math is just cherry on the top.

def k_numerator(n, k):
    res = 0
    sign = 1
    for i in range(k, 0, -1):
        pow_term = (i ** n)
        comb_term = comb(k, i)
        prod = pow_term * comb_term
        prod = prod * sign
        res = res + prod
        sign = sign * -1
    return res

def p_exactly_k(n, k):
    """
    Returns the probability of `B` containing exactly `k` unique elements
    (also see notes above)
    """

    return (comb(n, k) * k_numerator(n, k)) / (n ** n)


问:
How to add dialog on WTL project
I am a newbie on C++ WTL. I want to add a new dialog on my project. I am not sure if WTL has a wizard or something. Please guide me on creating a new dialog box.

Seems my question is not clear.

I need assistance on how to add a dialog box on a WTL project. As I said, I a newbie. I'm not a C++ guy who knows how to use this WTL. I dont have a code, since what I need is a walkthrough and not a source code answer.

Any comment is appreciated, or tutorial site would be a great help.

答: Here is a tutorial on creating dialog boxes using WTL https://www.codeproject.com/Articles/3841/WTL-for-MFC-Programmers-Part-I-ATL-GUI-Classes#dialogs</p>

Title: How to add dialog on WTL project


问:
Using `self` as a context in a `with` statement
I often see code that uses self to manage a context. For example

```<code>with self:
    self.x = 4
    self.y = 6
</code>```

What's going on here? What does using self as a context allow?

答: Code that uses with self: suggests that whatever class you're using provides __enter__ and __exit__ methods.  These methods create context.  They can be convenient for setup / teardown in testing, etc.

Body:
I often see code that uses self to manage a context. For example

with self:
    self.x = 4
    self.y = 6

What's going on here? What does using self as a context allow?


问:
Batch File toggle menus
im currently writing a batch file and i would like to make a toggle menu for choices to execute instead of the common question and answer execution

is there any way to make a list of choices and toggle "run" or "off" for them and hit enter to start

I found a file that seemed to get me in the right direction but i dont know how to make it work with my batch file

the code i found is...

```<code>@echo off

set _on=0

:top
cls

if %_on%==0 (set _nlb= &set _nrb= &set _flb=[&set _frb=]) else (set _nlb=    [&set _nrb=]&set _flb= &set _frb= )

echo The '_on' flag is currently: %_nlb% On %_nrb%  %_flb% Off %_frb%
echo.
echo Press any key to toggle the '_on' flag
pause>nul

if %_on%==0 (set _on=1) else (set _on=0)
goto top
</code>```

id like it to look like

```<code>netusers [run] [off]
netuseradministrator [run] [off]
virus.exe [run] [off]
press enter to initiate selected.
</code>```

in that type of layout if that makes any sense

答:
use the Choice command. for example

```<code>echo 1] Settings
echo 2] Start
echo 3] Quit
choice /c 123 /n
if %errorlevel%==1 goto settings
if %errorlevel%==2 goto start
if %errorlevel%==3 goto quit
</code>```

there are more parameters for timeout and stuff like that. Look at choice /?

Title: Batch File toggle menus

Body:
im currently writing a batch file and i would like to make a toggle menu for choices to execute instead of the common question and answer execution

is there any way to make a list of choices and toggle "run" or "off" for them and hit enter to start

I found a file that seemed to get me in the right direction but i dont know how to make it work with my batch file

the code i found is...

@echo off

set _on=0

:top
cls

if %_on%==0 (set _nlb= &set _nrb= &set _flb=[&set _frb=]) else (set _nlb=    [&set _nrb=]&set _flb= &set _frb= )

echo The '_on' flag is currently: %_nlb% On %_nrb%  %_flb% Off %_frb%
echo.
echo Press any key to toggle the '_on' flag
pause>nul

if %_on%==0 (set _on=1) else (set _on=0)
goto top

id like it to look like

netusers [run] [off]
netuseradministrator [run] [off]
virus.exe [run] [off]
press enter to initiate selected.

in that type of layout if that makes any sense

Body:
use the Choice command. for example

echo 1] Settings
echo 2] Start
echo 3] Quit
choice /c 123 /n
if %errorlevel%==1 goto settings
if %errorlevel%==2 goto start
if %errorlevel%==3 goto quit

there are more parameters for timeout and stuff like that. Look at choice /?


问:
How to indicate "exactly equals" occurrence constraint in XSD?
I found out that it is possible to restrict the minimum and the maximum number of elements in a XML Schema.

```<code><xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="full_name" type="xs:string"/>
      <xs:element name="child_name" type="xs:string"
      maxOccurs="10" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</code>```

I want  to restrinct the number of elements to an exact number.
Is there a numberOfOccurs, or something like that?
I could make it by setting the minOccurs to a value that is equal to maxOccurs... for example..

```<code><xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="full_name" type="xs:string"/>
      <xs:element name="child_name" type="xs:string"
      maxOccurs="10" minOccurs="10"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</code>```

Is there a specific way for doing it?

答: There is no separate cardinality constraint such as exactlyOccurs -- just use minOccurs and maxOccurs set to the same value as you've anticipated.

Body:
I found out that it is possible to restrict the minimum and the maximum number of elements in a XML Schema.

<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="full_name" type="xs:string"/>
      <xs:element name="child_name" type="xs:string"
      maxOccurs="10" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

I want  to restrinct the number of elements to an exact number.
Is there a numberOfOccurs, or something like that?
I could make it by setting the minOccurs to a value that is equal to maxOccurs... for example..

<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="full_name" type="xs:string"/>
      <xs:element name="child_name" type="xs:string"
      maxOccurs="10" minOccurs="10"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Is there a specific way for doing it?


问:
Python Clustering 'purity' metric
I'm using a Gaussian Mixture Model (GMM) from sklearn.mixture to perform clustering of my data set.

I could use the function score() to compute the log probability under the model.

However, I am looking for a metric called 'purity' which is defined in this article.

How can I implement it in Python?  My current implementation looks like this:

```<code>from sklearn.mixture import GMM

# X is a 1000 x 2 array (1000 samples of 2 coordinates).
# It is actually a 2 dimensional PCA projection of data
# extracted from the MNIST dataset, but this random array
# is equivalent as far as the code is concerned.
X = np.random.rand(1000, 2)

clusterer = GMM(3, 'diag')
clusterer.fit(X)
cluster_labels = clusterer.predict(X)

# Now I can count the labels for each cluster..
count0 = list(cluster_labels).count(0)
count1 = list(cluster_labels).count(1)
count2 = list(cluster_labels).count(2)
</code>```

But I can not loop through each cluster in order to compute the confusion matrix (according this question)

答:
A very late contribution.

You can try to implement it like this, pretty much like in this gist

```<code>def purity_score(y_true, y_pred):
    """Purity score
        Args:
            y_true(np.ndarray): n*1 matrix Ground truth labels
            y_pred(np.ndarray): n*1 matrix Predicted clusters

        Returns:
            float: Purity score
    """
    # matrix which will hold the majority-voted labels
    y_voted_labels = np.zeros(y_true.shape)
    # Ordering labels
    ## Labels might be missing e.g with set like 0,2 where 1 is missing
    ## First find the unique labels, then map the labels to an ordered set
    ## 0,2 should become 0,1
    labels = np.unique(y_true)
    ordered_labels = np.arange(labels.shape[0])
    for k in range(labels.shape[0]):
        y_true[y_true==labels[k]] = ordered_labels[k]
    # Update unique labels
    labels = np.unique(y_true)
    # We set the number of bins to be n_classes+2 so that
    # we count the actual occurence of classes between two consecutive bins
    # the bigger being excluded [bin_i, bin_i+1[
    bins = np.concatenate((labels, [np.max(labels)+1]), axis=0)

    for cluster in np.unique(y_pred):
        hist, _ = np.histogram(y_true[y_pred==cluster], bins=bins)
        # Find the most present label in the cluster
        winner = np.argmax(hist)
        y_voted_labels[y_pred==cluster] = winner

    return accuracy_score(y_true, y_voted_labels)
</code>```

Title: Python Clustering 'purity' metric

Body:
I'm using a Gaussian Mixture Model (GMM) from sklearn.mixture to perform clustering of my data set.

I could use the function score() to compute the log probability under the model.

However, I am looking for a metric called 'purity' which is defined in this article.

How can I implement it in Python?  My current implementation looks like this:

from sklearn.mixture import GMM

# X is a 1000 x 2 array (1000 samples of 2 coordinates).
# It is actually a 2 dimensional PCA projection of data
# extracted from the MNIST dataset, but this random array
# is equivalent as far as the code is concerned.
X = np.random.rand(1000, 2)

clusterer = GMM(3, 'diag')
clusterer.fit(X)
cluster_labels = clusterer.predict(X)

# Now I can count the labels for each cluster..
count0 = list(cluster_labels).count(0)
count1 = list(cluster_labels).count(1)
count2 = list(cluster_labels).count(2)

But I can not loop through each cluster in order to compute the confusion matrix (according this question)

Body:
A very late contribution.

You can try to implement it like this, pretty much like in this gist

def purity_score(y_true, y_pred):
    """Purity score
        Args:
            y_true(np.ndarray): n*1 matrix Ground truth labels
            y_pred(np.ndarray): n*1 matrix Predicted clusters

        Returns:
            float: Purity score
    """
    # matrix which will hold the majority-voted labels
    y_voted_labels = np.zeros(y_true.shape)
    # Ordering labels
    ## Labels might be missing e.g with set like 0,2 where 1 is missing
    ## First find the unique labels, then map the labels to an ordered set
    ## 0,2 should become 0,1
    labels = np.unique(y_true)
    ordered_labels = np.arange(labels.shape[0])
    for k in range(labels.shape[0]):
        y_true[y_true==labels[k]] = ordered_labels[k]
    # Update unique labels
    labels = np.unique(y_true)
    # We set the number of bins to be n_classes+2 so that
    # we count the actual occurence of classes between two consecutive bins
    # the bigger being excluded [bin_i, bin_i+1[
    bins = np.concatenate((labels, [np.max(labels)+1]), axis=0)

    for cluster in np.unique(y_pred):
        hist, _ = np.histogram(y_true[y_pred==cluster], bins=bins)
        # Find the most present label in the cluster
        winner = np.argmax(hist)
        y_voted_labels[y_pred==cluster] = winner

    return accuracy_score(y_true, y_voted_labels)

ContentLicense: CC BY-SA 4.0


问:
how to match list of dictionaries to another list of dictionaries value where key is different?
I have an issue where matching two list of dictionaries. Below the code i tried to match.

```<code>listDict1= [
    '{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:16:06"}',
    '{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:17:06"}',
    '{"weightMax":0, "weightMin":0, "date":"0"}']

listDict2= [
    '{"Weight":"138.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:15:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
    '{"Weight":"138.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:16:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
    '{"Weight":"188.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:17:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}']
</code>```

I need to match listDict1['date'] value with listDict2['measurementTime']

I tried the code below, but it matches as per the list index

```<code>def matchValValues(listDict1, listDict2):
    val1 = []
    rpm = []

    for i in range(len(listDict1)):
        j = dict((k, v) for k, v in ast.literal_eval(listDict1[i]).iteritems())
        k = dict((k, v) for k, v in ast.literal_eval(listDict2[i]).iteritems())
        #for i in j.keys():
        val = j['date']
        we = k['measurementTime']
        if val in we :
            val2 = float(k['Weight'])
            max=  float(j['weightMax'])
            min = float(j['weightMin'])
            print "True"
            if val2 <= max and val2 >= min:
                print "pass"
                val1.append(str(j['weightMax'])+'|'+str(j['weightMin']))
                rpm.append(k['Weight'])
            else:
                val1.append(j.copy())
                rpm.append(k.copy())
        else:
            val1.append(j.copy())
            rpm.append(k.copy())
    print val1
    print rpm
</code>```

expected output:
if there is a match append only weight and measurementTime value in rpm
if there is a match append only weightmax, weightmin and date value in val1
else append whole unmatched dict in rpm and val1 corresponding.

current output:

```<code>[{'date': '2017-07-05 12:16:06', 'weightMax': 150, 'weightMin': 100},
 {'date': '2017-07-05 12:17:06', 'weightMax': 150, 'weightMin': 100},
 {'date': '0', 'weightMax': 0, 'weightMin': 0}]

[{'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'},
 {'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'},
 {'Weight': '188.0', 'measurementTime': '2017-07-05 12:16:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'}]
</code>```

答:
It matches per the list index, because that's exactly what you told it to do.  Computers are annoying in this respect.

Don't use the index for choosing the needed listDict2 entry.  Instead, fetch the date from listIndex1[i] and search listDict2[<all>]['measurementTime'] for that value.  If the lists are large, you might want to build a reverse dictionary of <time stamp> : index to make your work easier.

Does that get you moving?

Body:
I have an issue where matching two list of dictionaries. Below the code i tried to match.

listDict1= [
    '{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:16:06"}',
    '{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:17:06"}',
    '{"weightMax":0, "weightMin":0, "date":"0"}']

listDict2= [
    '{"Weight":"138.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:15:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
    '{"Weight":"138.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:16:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
    '{"Weight":"188.0","unit":"Kg",
      "measurementTime":"2017-07-05 12:17:06",
      "receiptTime":"2017-06-30T15:16:09.009-07:00",
      "date":1498860969000,"model":"2011",
      "manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}']

I need to match listDict1['date'] value with listDict2['measurementTime']

I tried the code below, but it matches as per the list index

def matchValValues(listDict1, listDict2):
    val1 = []
    rpm = []

    for i in range(len(listDict1)):
        j = dict((k, v) for k, v in ast.literal_eval(listDict1[i]).iteritems())
        k = dict((k, v) for k, v in ast.literal_eval(listDict2[i]).iteritems())
        #for i in j.keys():
        val = j['date']
        we = k['measurementTime']
        if val in we :
            val2 = float(k['Weight'])
            max=  float(j['weightMax'])
            min = float(j['weightMin'])
            print "True"
            if val2 <= max and val2 >= min:
                print "pass"
                val1.append(str(j['weightMax'])+'|'+str(j['weightMin']))
                rpm.append(k['Weight'])
            else:
                val1.append(j.copy())
                rpm.append(k.copy())
        else:
            val1.append(j.copy())
            rpm.append(k.copy())
    print val1
    print rpm

expected output:
if there is a match append only weight and measurementTime value in rpm
if there is a match append only weightmax, weightmin and date value in val1
else append whole unmatched dict in rpm and val1 corresponding.

current output:

[{'date': '2017-07-05 12:16:06', 'weightMax': 150, 'weightMin': 100},
 {'date': '2017-07-05 12:17:06', 'weightMax': 150, 'weightMin': 100},
 {'date': '0', 'weightMax': 0, 'weightMin': 0}]

[{'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'},
 {'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'},
 {'Weight': '188.0', 'measurementTime': '2017-07-05 12:16:06',
  'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
  'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
  'unit': 'Kg', 'manufacturer': 'CONTINUA'}]


答: If self is a context manager (i.e. has __enter__ and __exit__ methods) this will simply invoke that functionality, the same as it would if the instance were used in a with block outside the class.

Title: Using `self` as a context in a `with` statement


问:
Google Play Services and "There is no linked app associated with this client ID"
I'm trying to implement Google Play Services following Google's documentation and I'm seeing the following when I try to connect my GameClient:

```<code>E/Volley: [4953] il.a: Unexpected response code 401 for https://www.googleapis.com/games/v1/players/me
E/Volley: [4953] il.a: Unexpected response code 401 for https://www.googleapis.com/games/v1/players/me
E/SignInIntentService: There is no linked app associated with this client ID.
</code>```

I've checked that the SHA1 fingerprint of the certificate signing the APK, the SHA1 of the debug certificate, and the SHA1 given to the Google API do match up and they do. I've checked that the app id is declared in the manifest in the application item (I've taken in my case the 13 digit numerical id, not one that also includes a package). I've also checked that the test accounts I'm using are each listed in the Developer Console and they are; they're each @gmail.com too, and they include my developer address. They've each activated Google Plus.

I've tried this from an API 16 S3 device and an API 17 Google API simulator. The app's package name is correctly declared in the manifest, on the developer console and matches the API package name. The app is listed as a client of the game service, and is shown as 'ready for testing'.

In short I'm struggling to see what my mistake can be and what I've missed. I think I have everything from Google's troubleshooting addressed too. I've looked at the main questions here on StackOverflow, and they're covered. Whatever it is I'm missing is probably staring me full in the face. What can I be missing?

答: I had exactly the same problem, and in my case, I fixed it regenerating the API Key from the Google APIs Console. Go to Credentials, select your API key and then click on "Regenerate Key". You don't need to update anything in your code or link more apps, just regenerate and it starts working magically.

Body:
I'm trying to implement Google Play Services following Google's documentation and I'm seeing the following when I try to connect my GameClient:

E/Volley: [4953] il.a: Unexpected response code 401 for https://www.googleapis.com/games/v1/players/me
E/Volley: [4953] il.a: Unexpected response code 401 for https://www.googleapis.com/games/v1/players/me
E/SignInIntentService: There is no linked app associated with this client ID.

I've checked that the SHA1 fingerprint of the certificate signing the APK, the SHA1 of the debug certificate, and the SHA1 given to the Google API do match up and they do. I've checked that the app id is declared in the manifest in the application item (I've taken in my case the 13 digit numerical id, not one that also includes a package). I've also checked that the test accounts I'm using are each listed in the Developer Console and they are; they're each @gmail.com too, and they include my developer address. They've each activated Google Plus.

I've tried this from an API 16 S3 device and an API 17 Google API simulator. The app's package name is correctly declared in the manifest, on the developer console and matches the API package name. The app is listed as a client of the game service, and is shown as 'ready for testing'.

In short I'm struggling to see what my mistake can be and what I've missed. I think I have everything from Google's troubleshooting addressed too. I've looked at the main questions here on StackOverflow, and they're covered. Whatever it is I'm missing is probably staring me full in the face. What can I be missing?


答: There's nothing special happening here. self behaves the same way in a with block that anything else would. It calls __enter__ when you enter the scope and __exit__ when you leave the scope through any means. I can't imagine what using self here would accomplish, but if you can come up with some examples of where you've seen that, we might be able to provide a better answer.


问:
how to send message to kafka producer using pipelindb?
I am learning kafka and pipelinedb and I got across the following statements,
how to send message to kafka producer using pipelindb?
Do you have a example? </p>

答: Read our SQL on Kafka post for a detailed walkthrough of how to use Kafka with PipelineDB. You can also read up on our Kafka integration in our technical docs.</p>


问:
Is there a "nice" way to advance a pointer to a struct by one byte?
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

```<code>#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}
</code>```

The compiler reports an error on the "nice" part:

```<code>% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^
</code>```

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

答:
regarding the posted code:</p>

```<code>#include <stdint.h>

// for flexability, do not overlap the 'typedef' with the struct definition
// (and always use a struct tag name)
typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv ) <-- causes 2 compiler warning messages
// due to unused parameters
// suggest: int main( void )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;  <-- 17 is not a valid address for a struct.

    // ugly   <-- however, it actually works
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna; <-- don't do this,
    // use 'gna' to access the individual bytes

    // nice
    ++((uint8_t*) ps); <-- does not compile
}
</code>```

Body:
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}

The compiler reports an error on the "nice" part:

% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

Body:
regarding the posted code:

#include <stdint.h>

// for flexability, do not overlap the 'typedef' with the struct definition
// (and always use a struct tag name)
typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv ) <-- causes 2 compiler warning messages
// due to unused parameters
// suggest: int main( void )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;  <-- 17 is not a valid address for a struct.

    // ugly   <-- however, it actually works
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna; <-- don't do this,
    // use 'gna' to access the individual bytes

    // nice
    ++((uint8_t*) ps); <-- does not compile
}


问:
Horizontal scrolling menu width in jQuery
I'm trying to make a horizontal scrolling menu bar like this:

div.scrollmenu {
  background-color: #333;
  overflow: auto;
  white-space: nowrap;
}

div.scrollmenu a {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scrollmenu">
  Home
  News
  Contact
  About
  Support
  Blog
  Tools
  Base
  Custom
  More
  Logo
  Friends
  Partners
  People
  Work
</div></code>```

My question is: how can I get the full width of .scrollmenu in jQuery? I mean its shown + hidden parts. If I use $(".scrollmenu").width(); I just get the width of the visible part of that div.

答:
To access the DOM Element's  list of properties you can use jQuery's .prop() like $("selector").prop("scrollWidth")

or directly using pure JavaScript: Element.scrollWidthMDN Docs

// jQuery:
console.log( $(".scrollmenu").prop("scrollWidth") );
// JS
console.log( document.querySelector(".scrollmenu").scrollWidth );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.scrollmenu {
  background-color: #333;
  overflow: auto;
  white-space: nowrap;
}

div.scrollmenu a {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}</code>```

  Home
  News
  Contact
  About
  Support
  Blog
  Tools
  Base
  Custom
  More
  Logo
  Friends
  Partners
  People
  Work

```

Body:
I'm trying to make a horizontal scrolling menu bar like this:

div.scrollmenu {
  background-color: #333;
  overflow: auto;
  white-space: nowrap;
}

div.scrollmenu a {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}

  Home
  News
  Contact
  About
  Support
  Blog
  Tools
  Base
  Custom
  More
  Logo
  Friends
  Partners
  People
  Work

My question is: how can I get the full width of .scrollmenu in jQuery? I mean its shown + hidden parts. If I use $(".scrollmenu").width(); I just get the width of the visible part of that div.

Body:
To access the DOM Element's  list of properties you can use jQuery's .prop() like $("selector").prop("scrollWidth")

or directly using pure JavaScript: Element.scrollWidthMDN Docs

// jQuery:
console.log( $(".scrollmenu").prop("scrollWidth") );
// JS
console.log( document.querySelector(".scrollmenu").scrollWidth );

div.scrollmenu {
  background-color: #333;
  overflow: auto;
  white-space: nowrap;
}

div.scrollmenu a {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollmenu">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  <a href="#support">Support</a>
  <a href="#blog">Blog</a>
  <a href="#tools">Tools</a>
  <a href="#base">Base</a>
  <a href="#custom">Custom</a>
  <a href="#more">More</a>
  <a href="#logo">Logo</a>
  <a href="#friends">Friends</a>
  <a href="#partners">Partners</a>
  <a href="#people">People</a>
  <a href="#work">Work</a>
</div>


问:
How do you stop injection in this PHP/PDO
So I have look at so many post, web sites and video and now I am so confused!  I can't seem to get it right.
How do you stop injection in this PHP/PDO.  I have this code that works, but it allows injection.

```<code>//*THIS WORKS BUT ALLOWS INJECTION
//*

//The variable $word comes from another php file where the search is created.
public function getAllCards($word) {

    $sql = "SELECT * FROM carddbtable WHERE businessNameDB='".$word."'";

foreach ($this->conn->query($sql) as $row) {

    echo json_encode($row)."<br>"."<br>";
}

$db = null;
}
</code>```

With this new code I am trying to remove the variable  "$word"  from the   "SELECT * FROM "  statement
to stop the injection and add the  "prepare"   and the  error checking and the   "execute" statement,  but I can't get it right. How would I do this?     FYI this is a GoDaddy shared server.

```<code>//Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    // sql statement to be executed
    $sql = "SELECT * FROM carddbtable WHERE businessNameDB=':word";

    // prepare to be executed
    $statement = $this->conn->prepare($sql);

    // error occurred
    if (!$statement) {
        throw new Exception($statement->error);
    }

    // execute statement
    $statement->execute( :word => '$word' );

//run the query
foreach ($this->conn->query($statement) as $row) {

echo json_encode($row)."<br>"."<br>";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;
}
</code>```

答:
You've almost got it. PDO, like many database drivers, will be responsible for all of the escaping, so just leave the placeholder as plain as possible:

```<code>$sql = "SELECT * FROM carddbtable WHERE businessNameDB=:word";
</code>```

No ' necessary there.

Now when you execute() a PDO statement you get a result which you need to capture into a variable:

```<code>$res = $statement->execute([ 'word' => $word ]);
</code>```

As Ibu and chris85 point out the '$word' part is also incorrect. Avoid quoting single variables, it's not only pointless, it can cause trouble, like here where you're binding to literally dollar-sign word, not the value in question. This goes doubly for "$word".

Then you fetch from that. Right now you're calling query() on the statement, which is incorrect.

Another thing to note is kicking the habit of making throw-away variables like $sql as these are just junk. Instead pass the argument directly:

```<code>$statement = $this->conn->prepare("SELECT * FROM carddbtable WHERE businessNameDB=:word");
</code>```

This avoids accidentally mixing up $sql3 with $sql8 if you're juggling a bunch of these things.

Body:
So I have look at so many post, web sites and video and now I am so confused!  I can't seem to get it right.
How do you stop injection in this PHP/PDO.  I have this code that works, but it allows injection.

//*THIS WORKS BUT ALLOWS INJECTION
//*

//The variable $word comes from another php file where the search is created.
public function getAllCards($word) {

    $sql = "SELECT * FROM carddbtable WHERE businessNameDB='".$word."'";

foreach ($this->conn->query($sql) as $row) {

    echo json_encode($row)."
"."
";
}

$db = null;
}

With this new code I am trying to remove the variable  "$word"  from the   "SELECT * FROM "  statement
to stop the injection and add the  "prepare"   and the  error checking and the   "execute" statement,  but I can't get it right. How would I do this?     FYI this is a GoDaddy shared server.

//Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    // sql statement to be executed
    $sql = "SELECT * FROM carddbtable WHERE businessNameDB=':word";

    // prepare to be executed
    $statement = $this->conn->prepare($sql);

    // error occurred
    if (!$statement) {
        throw new Exception($statement->error);
    }

    // execute statement
    $statement->execute( :word => '$word' );

//run the query
foreach ($this->conn->query($statement) as $row) {

echo json_encode($row)."
"."
";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;
}

Body:
You've almost got it. PDO, like many database drivers, will be responsible for all of the escaping, so just leave the placeholder as plain as possible:

$sql = "SELECT * FROM carddbtable WHERE businessNameDB=:word";

No ' necessary there.

Now when you execute() a PDO statement you get a result which you need to capture into a variable:

$res = $statement->execute([ 'word' => $word ]);

As Ibu and chris85 point out the '$word' part is also incorrect. Avoid quoting single variables, it's not only pointless, it can cause trouble, like here where you're binding to literally dollar-sign word, not the value in question. This goes doubly for "$word".

Then you fetch from that. Right now you're calling query() on the statement, which is incorrect.

Another thing to note is kicking the habit of making throw-away variables like $sql as these are just junk. Instead pass the argument directly:

$statement = $this->conn->prepare("SELECT * FROM carddbtable WHERE businessNameDB=:word");

This avoids accidentally mixing up $sql3 with $sql8 if you're juggling a bunch of these things.


问:
Save Video to iPad Videos app
I have been trying to use the UISaveVideoAtPathToSavedPhotosAlbum to save my video (stored locally within the application). But when I try to save it, i get an error saying "Operation failed because video file is invalid and cannot be played." The file is only about a minute long and is a .mp4 file. I don't have a problem playing it with MPMoviePlayer, it just won't save. Here is the code:

```<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"videoFile" ofType:@"mp4"];
UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(status:didFinishSavingWithError:contextInfo), nil);
</code>```

Is this method not designed to work for the iPad? It says "SavedPhotosAlbum". Does that mean I will have to go through the photos app to view it, or is that just the name of the method and it will be in the Videos app? If you could help me work this out, I would greatly appreciate it.

答:
It should work as long as UIVideoAtPathIsCompatibleWithSavedPhotosAlbum() returns true. However, I've had this issue before and seemed to have better luck creating and ALAssetsLibrary object and then using the method:

```<code>- (void)writeVideoAtPathToSavedPhotosAlbum:(NSURL *)videoPathURL completionBlock:(ALAssetsLibraryWriteVideoCompletionBlock)completionBlock
</code>```

I didn't try to edit this to be generic or 100% portable. I just grabbed the code I wrote for saving videos to give you a good starting point for using ALAssetLibrary instead:

```<code>- (void) saveVideoFile:(NSString *)fullpathVideoFile completionTarget:(id)theCompletionTarget action:(SEL)theCompletionAction context:(id)theContext
    {
    writeFailed = NO;

    completionTarget = theCompletionTarget;
    completionAction = theCompletionAction;
    completionContext = theContext;

    //  ALAssetsLibraryWriteVideoCompletionBlock
    //
    void (^completionBlock)(NSURL *, NSError *) = ^(NSURL *assetURL, NSError *error)
        {
        if ( error != nil )
            {
            writeFailed = YES;
            }

        writingToLibrary = NO;

        [self notifyCompletionTarget];
        };

    // clean up from previous calls
    //
    if ( assetURL != nil )
        {
        [assetURL release];
        assetURL = nil;
        }

    if ( assetFullPathName != nil )
        {
        [assetFullPathName release];
        assetFullPathName = nil;
        }

    writingToLibrary = YES;

    // make sure we have a good file
    //
    if ( [[NSFileManager defaultManager] fileExistsAtPath:fullpathVideoFile] == NO)
        {
        writingToLibrary = NO;
        writeFailed = YES;
        [self notifyCompletionTarget];
        return;
        }

    // set assetURL for sending to the library
    //
    assetFullPathName = [[NSMutableString alloc] initWithCapacity:(NSUInteger)1024];
    [assetFullPathName setString:fullpathVideoFile];

    assetURL = [[NSURL alloc] initFileURLWithPath:assetFullPathName isDirectory:NO];

    // Use possible alternative method if this method doesn't want to work
    //
    if ( [library videoAtPathIsCompatibleWithSavedPhotosAlbum:assetURL]==NO )
        {
        if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum( assetFullPathName ) )
            {
            UISaveVideoAtPathToSavedPhotosAlbum( assetFullPathName, self, @selector(video:didFinishSavingWithError:contextInfo:), nil );
            }
        else
            {
            writingToLibrary = NO;
            writeFailed = YES;
            [self notifyCompletionTarget];
            }

        return;
        }

    // Write the video to the library
    //
    [library writeVideoAtPathToSavedPhotosAlbum:assetURL completionBlock:completionBlock];
    }
</code>```

Title: Save Video to iPad Videos app

Body:
I have been trying to use the UISaveVideoAtPathToSavedPhotosAlbum to save my video (stored locally within the application). But when I try to save it, i get an error saying "Operation failed because video file is invalid and cannot be played." The file is only about a minute long and is a .mp4 file. I don't have a problem playing it with MPMoviePlayer, it just won't save. Here is the code:

NSString *path = [[NSBundle mainBundle] pathForResource:@"videoFile" ofType:@"mp4"];
UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(status:didFinishSavingWithError:contextInfo), nil);

Is this method not designed to work for the iPad? It says "SavedPhotosAlbum". Does that mean I will have to go through the photos app to view it, or is that just the name of the method and it will be in the Videos app? If you could help me work this out, I would greatly appreciate it.

Body:
It should work as long as UIVideoAtPathIsCompatibleWithSavedPhotosAlbum() returns true. However, I've had this issue before and seemed to have better luck creating and ALAssetsLibrary object and then using the method:

- (void)writeVideoAtPathToSavedPhotosAlbum:(NSURL *)videoPathURL completionBlock:(ALAssetsLibraryWriteVideoCompletionBlock)completionBlock

I didn't try to edit this to be generic or 100% portable. I just grabbed the code I wrote for saving videos to give you a good starting point for using ALAssetLibrary instead:

- (void) saveVideoFile:(NSString *)fullpathVideoFile completionTarget:(id)theCompletionTarget action:(SEL)theCompletionAction context:(id)theContext
    {
    writeFailed = NO;

    completionTarget = theCompletionTarget;
    completionAction = theCompletionAction;
    completionContext = theContext;

    //  ALAssetsLibraryWriteVideoCompletionBlock
    //
    void (^completionBlock)(NSURL *, NSError *) = ^(NSURL *assetURL, NSError *error)
        {
        if ( error != nil )
            {
            writeFailed = YES;
            }

        writingToLibrary = NO;

        [self notifyCompletionTarget];
        };

    // clean up from previous calls
    //
    if ( assetURL != nil )
        {
        [assetURL release];
        assetURL = nil;
        }

    if ( assetFullPathName != nil )
        {
        [assetFullPathName release];
        assetFullPathName = nil;
        }

    writingToLibrary = YES;

    // make sure we have a good file
    //
    if ( [[NSFileManager defaultManager] fileExistsAtPath:fullpathVideoFile] == NO)
        {
        writingToLibrary = NO;
        writeFailed = YES;
        [self notifyCompletionTarget];
        return;
        }

    // set assetURL for sending to the library
    //
    assetFullPathName = [[NSMutableString alloc] initWithCapacity:(NSUInteger)1024];
    [assetFullPathName setString:fullpathVideoFile];

    assetURL = [[NSURL alloc] initFileURLWithPath:assetFullPathName isDirectory:NO];

    // Use possible alternative method if this method doesn't want to work
    //
    if ( [library videoAtPathIsCompatibleWithSavedPhotosAlbum:assetURL]==NO )
        {
        if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum( assetFullPathName ) )
            {
            UISaveVideoAtPathToSavedPhotosAlbum( assetFullPathName, self, @selector(video:didFinishSavingWithError:contextInfo:), nil );
            }
        else
            {
            writingToLibrary = NO;
            writeFailed = YES;
            [self notifyCompletionTarget];
            }

        return;
        }

    // Write the video to the library
    //
    [library writeVideoAtPathToSavedPhotosAlbum:assetURL completionBlock:completionBlock];
    }


问:
React: Get Object within Navigation Options
I am trying to get an object by reference string within the ReactNavigation headerRight section, however, it appears as though I am not getting the right instance of the main class as running the below code yields an "undefined is not an object."

```<code>import React from 'react';
import { View, Text } from 'react-native';
import { StackNavigator } from 'react-navigation';

export default class App extends React.Component {
  render(){
    return <PrimaryNavigator/>;
  }
}

export const PrimaryNavigator = StackNavigator({
  Primary: {
    screen: Primary,
  }
});

export default class Primary extends React.Component {
  static navigationOptions = {
    title: 'Title',
    headerRight: <Text>{this.ref1.accessible}</Text>
  };

  return (
    <View ref="ref1">
    </View>
   );
  }
}
</code>```

How should I access the object with reference "ref1" within the navigationOptions section?

Thanks.

答: The error occurs because you're trying to access an instance variable inside a static function. You'd have to rethink the way you configure your navigation options. For example, you could pass props to the PrimaryNavigator and set navigationOptions where you create the StackNavigator right after the screen.

Body:
I am trying to get an object by reference string within the ReactNavigation headerRight section, however, it appears as though I am not getting the right instance of the main class as running the below code yields an "undefined is not an object."

import React from 'react';
import { View, Text } from 'react-native';
import { StackNavigator } from 'react-navigation';

export default class App extends React.Component {
  render(){
    return <PrimaryNavigator/>;
  }
}

export const PrimaryNavigator = StackNavigator({
  Primary: {
    screen: Primary,
  }
});

export default class Primary extends React.Component {
  static navigationOptions = {
    title: 'Title',
    headerRight: <Text>{this.ref1.accessible}</Text>
  };

  return (
    <View ref="ref1">
    </View>
   );
  }
}

How should I access the object with reference "ref1" within the navigationOptions section?

Thanks.


问:
How to get transparent list view in javafx?
I have a list view. I want to make the cells background transparent. Currently, I am doing the following:

```<code>.list-cell
{
    -fx-background-color: transparent;
}
</code>```

But, the color of the cells remain white. I have tried the same with other colors. It works for other colors. But, it's not working for the transparent color. How can I get a transparent list-view?

答:
You have to make both the list-view and list-cell transparent.</p>

```<code>.list-cell {
    -fx-background-color: transparent;
}
.list-view {
    -fx-background-color: transparent;
}
</code>```

Body:
I have a list view. I want to make the cells background transparent. Currently, I am doing the following:

.list-cell
{
    -fx-background-color: transparent;
}

But, the color of the cells remain white. I have tried the same with other colors. It works for other colors. But, it's not working for the transparent color. How can I get a transparent list-view?

Body:
You have to make both the list-view and list-cell transparent.

.list-cell {
    -fx-background-color: transparent;
}
.list-view {
    -fx-background-color: transparent;
}


答:
I'd recommend wrapping your horizontal scroll menu in a div, then find the width of the parent. https://jsfiddle.net/qegufbv8/1/

```<code><div class="wrapper">
  <div class="scrollmenu">
    <a href="#home">Home</a>
    <a href="#news">News</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
    <a href="#support">Support</a>
    <a href="#blog">Blog</a>
    <a href="#tools">Tools</a>
    <a href="#base">Base</a>
    <a href="#custom">Custom</a>
    <a href="#more">More</a>
    <a href="#logo">Logo</a>
    <a href="#friends">Friends</a>
    <a href="#partners">Partners</a>
    <a href="#people">People</a>
    <a href="#work">Work</a>
  </div>
</div>
</code>```

You can then use jQuery .width() to find the width.

```<code>$( '.wrapper' ).width();
</code>```

If your scrollmenu div width is less than 100%, make sure to add display: inline-block to your wrapper.

Title: Horizontal scrolling menu width in jQuery

Body:
I'd recommend wrapping your horizontal scroll menu in a div, then find the width of the parent. https://jsfiddle.net/qegufbv8/1/

<div class="wrapper">
  <div class="scrollmenu">
    <a href="#home">Home</a>
    <a href="#news">News</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
    <a href="#support">Support</a>
    <a href="#blog">Blog</a>
    <a href="#tools">Tools</a>
    <a href="#base">Base</a>
    <a href="#custom">Custom</a>
    <a href="#more">More</a>
    <a href="#logo">Logo</a>
    <a href="#friends">Friends</a>
    <a href="#partners">Partners</a>
    <a href="#people">People</a>
    <a href="#work">Work</a>
  </div>
</div>

You can then use jQuery .width() to find the width.

$( '.wrapper' ).width();

If your scrollmenu div width is less than 100%, make sure to add display: inline-block to your wrapper.


问:
How do I create a variable length dropdown list on a ViewModel without repeating code in c#?
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

```<code>Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .
</code>```

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

```<code>[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}
</code>```

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

```<code>                      *******QUESTION EDIT***********
</code>```

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

```<code>        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }
</code>```

My Html View

```<code>        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")
</code>```

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

答:
Use LINQ and go backwards:</p>

```<code>var ans = Enumerable.Range(1, 12).Select(p => start.AddMonths(-p).ToString("MMM yy")).ToList();
</code>```

Body:
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

                      *******QUESTION EDIT***********

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }

My Html View

        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

Body:
Use LINQ and go backwards:

var ans = Enumerable.Range(1, 12).Select(p => start.AddMonths(-p).ToString("MMM yy")).ToList();


答:
You can use the scrollWidth property. It is a JavaScript property and there is no equivalent in jQuery.

function getWidth() {
  console.log($(".scrollmenu")[0].scrollWidth);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.scrollmenu {
  background-color: #333;
  coverflow: auto;
  white-space: nowrap;
}

div.scrollmenu a {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}</code>```

  Home
  News
  Contact
  About
  Support
  Blog
  Tools
  Base
  Custom
  More
  Logo
  Friends
  Partners
  People
  Work

<button type="button" onclick="getWidth()">Get width</button>```

Body:
You can use the scrollWidth property. It is a JavaScript property and there is no equivalent in jQuery.

function getWidth() {
  console.log($(".scrollmenu")[0].scrollWidth);
}

div.scrollmenu {
  background-color: #333;
  coverflow: auto;
  white-space: nowrap;
}

div.scrollmenu a {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollmenu">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  <a href="#support">Support</a>
  <a href="#blog">Blog</a>
  <a href="#tools">Tools</a>
  <a href="#base">Base</a>
  <a href="#custom">Custom</a>
  <a href="#more">More</a>
  <a href="#logo">Logo</a>
  <a href="#friends">Friends</a>
  <a href="#partners">Partners</a>
  <a href="#people">People</a>
  <a href="#work">Work</a>
</div>
<br/>
<button type="button" onclick="getWidth()">Get width</button>


问:
@Html.EditorFor required = "required" not working
I want to validate @Html.EditorFor that it is required to input, but not working in asp.net mvc

```<code><div class="form-group"> <label>First Name editor*</label>
                                    @Html.EditorFor(x => x.Requester.FirstName, new { @class = "form-control", required = "required" })
                                    @Html.ValidationMessageFor(m => m.Requester.FirstName)
                                </div>
</code>```

sorry for my simple question because it is really frustating try to fix this issue

my controller code

```<code>    [HttpPost]
    public ActionResult Index(ViewModel.Ticket m)
    {
        try
        {
            using (DatabaseManager ctx = new DatabaseManager(true))
            {
                if (string.IsNullOrEmpty(m.TicketNo))
                {
                    m.TicketNo = TicketNo.Create(User.Identity.Name, "TICKET");
                }

                Ticket obj = ViewModel.Ticket.ConvertToTicketBusiness(m);
                obj.Requester = m.Requester.Email;
                obj.TicketStatus = TicketStatus.Open.ToString();
                obj.Escalation = User.Identity.Name;
                obj.CreatedBy = User.Identity.Name;
                obj.CreatedDate = DateTime.Now;
                obj.UpdatedBy = obj.CreatedBy;
                obj.UpdatedDate = obj.CreatedDate;
                if (obj.IsValid)
                {
                    obj = obj.Save();
                }

                Customer cust = ViewModel.Ticket.ConvertToCustomerBusiness(m.Requester);

                if (string.IsNullOrEmpty(cust.CreatedBy))
                {
                    cust.CreatedBy = User.Identity.Name;
                    cust.CreatedDate = DateTime.Now;
                }

                cust.UpdatedBy = User.Identity.Name;
                cust.UpdatedDate = DateTime.Now;

                if (cust.IsValid)
                {
                    cust = cust.Save();
                }
                ctx.SaveChanges();
            }
            ViewBag.SuccessMsg = "Success";
        }
        catch (Exception ex)
        {
            ViewBag.ErrorMsg = ex.Message;
            return View(m);
        }

        return RedirectToAction("Inbox");
    }
</code>```

thank you

答: Insert @ Like: @required="required"

Body:
I want to validate @Html.EditorFor that it is required to input, but not working in asp.net mvc

 First Name editor*
                                    @Html.EditorFor(x => x.Requester.FirstName, new { @class = "form-control", required = "required" })
                                    @Html.ValidationMessageFor(m => m.Requester.FirstName)

sorry for my simple question because it is really frustating try to fix this issue

my controller code

    [HttpPost]
    public ActionResult Index(ViewModel.Ticket m)
    {
        try
        {
            using (DatabaseManager ctx = new DatabaseManager(true))
            {
                if (string.IsNullOrEmpty(m.TicketNo))
                {
                    m.TicketNo = TicketNo.Create(User.Identity.Name, "TICKET");
                }

                Ticket obj = ViewModel.Ticket.ConvertToTicketBusiness(m);
                obj.Requester = m.Requester.Email;
                obj.TicketStatus = TicketStatus.Open.ToString();
                obj.Escalation = User.Identity.Name;
                obj.CreatedBy = User.Identity.Name;
                obj.CreatedDate = DateTime.Now;
                obj.UpdatedBy = obj.CreatedBy;
                obj.UpdatedDate = obj.CreatedDate;
                if (obj.IsValid)
                {
                    obj = obj.Save();
                }

                Customer cust = ViewModel.Ticket.ConvertToCustomerBusiness(m.Requester);

                if (string.IsNullOrEmpty(cust.CreatedBy))
                {
                    cust.CreatedBy = User.Identity.Name;
                    cust.CreatedDate = DateTime.Now;
                }

                cust.UpdatedBy = User.Identity.Name;
                cust.UpdatedDate = DateTime.Now;

                if (cust.IsValid)
                {
                    cust = cust.Save();
                }
                ctx.SaveChanges();
            }
            ViewBag.SuccessMsg = "Success";
        }
        catch (Exception ex)
        {
            ViewBag.ErrorMsg = ex.Message;
            return View(m);
        }

        return RedirectToAction("Inbox");
    }

thank you

Body: Insert @ Like: @required="required"


问:
SQL give new column based on group
I have the following table:

```<code>ID | Group |  Miles
1  |    1  |   23
2  |    1  |   38
3  |    1  |   42
1  |    2  |   33
2  |    2  |   42
1  |    3  |   35
2  |    3  |   43
3  |    3  |   47
</code>```

And would like to get

```<code>id  miles1  miles2   miles3
1 | 23     | 33    | 35
2 | 38     | 42    | 43
3 | 42     | Null  | 47
</code>```

Thanks

答:
Another option is PIVOT

Example

```<code>Select [ID]
      ,Miles1 = [1]
      ,Miles2 = [2]
      ,Miles3 = [3]
 From YourTable
 Pivot (sum([Miles]) For [Group] in ([1],[2],[3]) ) p
</code>```

Returns

```<code>ID  Miles1  Miles2  Miles3
1   23      33      35
2   38      42      43
3   42      NULL    47
</code>```

Title: SQL give new column based on group

Body:
I have the following table:

ID | Group |  Miles
1  |    1  |   23
2  |    1  |   38
3  |    1  |   42
1  |    2  |   33
2  |    2  |   42
1  |    3  |   35
2  |    3  |   43
3  |    3  |   47

And would like to get

id  miles1  miles2   miles3
1 | 23     | 33    | 35
2 | 38     | 42    | 43
3 | 42     | Null  | 47

Thanks

Body:
Another option is PIVOT

Example

Select [ID]
      ,Miles1 = [1]
      ,Miles2 = [2]
      ,Miles3 = [3]
 From YourTable
 Pivot (sum([Miles]) For [Group] in ([1],[2],[3]) ) p

Returns

ID  Miles1  Miles2  Miles3
1   23      33      35
2   38      42      43
3   42      NULL    47