问:
How to calculate number of occurrence of a character at beginning in a List of String using Scala
I am new to Scala and I want to calculate number of occurrences of a character in which start with a particular alphabet in a list of Strings.

For example-

```<code>val test1 : List[String] = List("zero","zebra","zenith","tiger","mosquito")
</code>```

I have defined above List of Strings and I want to calculate count of all strings which start with "z".

I tried with below code-

```<code>scala> test2.count(s=> s.charAt(0) == "z")
res7: Int = 0
</code>```

It is giving me result as 0. I am not sure what I am doing wrong. Please suggest.

答:
Character values are delimited by single quotes. Double quotes are reserved for strings:</p>

```<code>val test : List[String] = List("zero","zebra","zenith","tiger","mosquito")
test.count(_.charAt(0) == 'z') // 3: Int
</code>```

Body:
I am new to Scala and I want to calculate number of occurrences of a character in which start with a particular alphabet in a list of Strings.

For example-

val test1 : List[String] = List("zero","zebra","zenith","tiger","mosquito")

I have defined above List of Strings and I want to calculate count of all strings which start with "z".

I tried with below code-

scala> test2.count(s=> s.charAt(0) == "z")
res7: Int = 0

It is giving me result as 0. I am not sure what I am doing wrong. Please suggest.

Body:
Character values are delimited by single quotes. Double quotes are reserved for strings:

val test : List[String] = List("zero","zebra","zenith","tiger","mosquito")
test.count(_.charAt(0) == 'z') // 3: Int


来源: stackexchange

问:
How to install a Debian package's Build-Depends and Depends
If I have a debian/control file with Build-Depends and Depends entries.

How do I install both sets of dependencies?

At the moment I'm using the following command to create a stub package that depends on the Build-Depends but not the Depends.

```<code>$ mk-build-deps --build-dep \
&& dpkg -i *.deb \
|| apt-get update && apt-get install --fix-broken --yes \
</code>```

答:
Assuming this is a standard package in your apt repositories, you should be able to simply run

apt-get build-dep PACKAGE [PACKAGE…]
```

<p>Generally speaking, the best solution is to find a package with the same dependencies (better yet, an identical yet different version of the same package) and just <code>build-dep</code> it.  This solves 99+% of these issues in my experience.</p>

<hr>

<p>I don't know <code>mk-build-deps</code> at all, but you can run this to see what dependencies are called out in the <code>debian/control</code> file in package "PACKAGE":</p>

<pre class="lang-sh prettyprint-override"><code>echo $(awk '
  /^(Build-)?Depends:/ || /^ / && deps {
    sub(/^[^ ]+: /, "")
    deps = 1
    dep_str = dep_str ", " $0
    next
  }
  { deps=0 }
  END {
    split(dep_str, dep_array, /, */)
    for (d in dep_array) {
      dep = dep_array[d]
      gsub(/[^a-z0-9_.-].*$/, "", dep)
      if (dep && !seen[dep]++) print dep
    }
  }' PACKAGE/debian/control)
</code>```

(This examines the Debian control file for Build-Depends and Depends lines and presents just the dependencies that are listed, excluding any variables (which I believe are already included in other hits from the file).

AWK code walkthrough:  If it is a Build-Depends or Depends line, or it's a whitespace-indended line following such a line, remove the line label, note we're in a dependency line (dep = 1), and save it into dep_str.  On other lines, remove the marker saying we're continuing a dependency line.  After parsing the input, split the dependency string dep_str into an array delimited by commas and optional trailing whitespace, then iterate through that array.  Scrub invalid characters from the end of the dependency name (these are version info) and if anything remains and hasn't been seen (here) before, print it on its own line.

Replace echo with apt-get install if you like, but you might need to prune out the items you're looking to customize and/or manually install first.

After that, you should have an easier time with dpkg -i *.deb.  Feel free to try apt-get  install --fix-broken at any time if you're stuck.

ContentLicense: CC BY-SA 3.0

Body:
If I have a debian/control file with Build-Depends and Depends entries.

How do I install both sets of dependencies?

At the moment I'm using the following command to create a stub package that depends on the Build-Depends but not the Depends.

$ mk-build-deps --build-dep \
&& dpkg -i *.deb \
|| apt-get update && apt-get install --fix-broken --yes \

Body:
Assuming this is a standard package in your apt repositories, you should be able to simply run

apt-get build-dep PACKAGE [PACKAGE…]

Generally speaking, the best solution is to find a package with the same dependencies (better yet, an identical yet different version of the same package) and just build-dep it.  This solves 99+% of these issues in my experience.

I don't know mk-build-deps at all, but you can run this to see what dependencies are called out in the debian/control file in package "PACKAGE":

echo $(awk '
  /^(Build-)?Depends:/ || /^ / && deps {
    sub(/^[^ ]+: /, "")
    deps = 1
    dep_str = dep_str ", " $0
    next
  }
  { deps=0 }
  END {
    split(dep_str, dep_array, /, */)
    for (d in dep_array) {
      dep = dep_array[d]
      gsub(/[^a-z0-9_.-].*$/, "", dep)
      if (dep && !seen[dep]++) print dep
    }
  }' PACKAGE/debian/control)

(This examines the Debian control file for Build-Depends and Depends lines and presents just the dependencies that are listed, excluding any variables (which I believe are already included in other hits from the file).

AWK code walkthrough:  If it is a Build-Depends or Depends line, or it's a whitespace-indended line following such a line, remove the line label, note we're in a dependency line (dep = 1), and save it into dep_str.  On other lines, remove the marker saying we're continuing a dependency line.  After parsing the input, split the dependency string dep_str into an array delimited by commas and optional trailing whitespace, then iterate through that array.  Scrub invalid characters from the end of the dependency name (these are version info) and if anything remains and hasn't been seen (here) before, print it on its own line.

Replace echo with apt-get install if you like, but you might need to prune out the items you're looking to customize and/or manually install first.

After that, you should have an easier time with dpkg -i *.deb.  Feel free to try apt-get  install --fix-broken at any time if you're stuck.

ContentLicense: CC BY-SA 4.0


问:
How can I programmatically center UITextview across all devices?
My current code is below

```<code>    class SetupScene: SKScene{
        let myTextField: UITextField = UITextField(frame: CGRect(x: 208, y: 175, width: 230.00, height: 33.00));

    override func didMove(to view: SKView) {
        let background = SKSpriteNode(imageNamed: "pixelBackground")
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.size = self.size
        background.zPosition = -10
        self.addChild(background)

        self.view?.addSubview(myTextField)

        myTextField.backgroundColor = UIColor.white
        myTextField.text = "Enter your name:"
        myTextField.borderStyle = UITextBorderStyle.line
        myTextField.textAlignment = .center
        myTextField.font = UIFont(name: "04b_25", size: 25)

    }
}
</code>```

With the code above myTextField is at the top left of my screen(my screens in landscape orientation). I can manually move it where I want by inputing numbers into the x and y values but then it moves to different places depending on the device. And when I try to do:

```<code>    myTextField = UITextField(frame: CGRect(x: self.size.width/2, y: self.size.height/2, width: 230.00, height: 33.00))
</code>```

myTextField is missing from the screen. How can I center across all devices like I would in SpriteKit with: (x: self.size.width/2, y: self.size.height/2)

*Note I want to do this programmatically not with Storyboards

答:
Don't use frames. Use AutoLayout.

Set translatesAutoresizingMaskIntoConstraints on the view (text field) to false, and then use an X axis NSLayoutAnchor and a Y axis NSLayoutAnchor to make the center of your view be equal to the center of it's superview.

Body:
My current code is below

    class SetupScene: SKScene{
        let myTextField: UITextField = UITextField(frame: CGRect(x: 208, y: 175, width: 230.00, height: 33.00));

    override func didMove(to view: SKView) {
        let background = SKSpriteNode(imageNamed: "pixelBackground")
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.size = self.size
        background.zPosition = -10
        self.addChild(background)

        self.view?.addSubview(myTextField)

        myTextField.backgroundColor = UIColor.white
        myTextField.text = "Enter your name:"
        myTextField.borderStyle = UITextBorderStyle.line
        myTextField.textAlignment = .center
        myTextField.font = UIFont(name: "04b_25", size: 25)

    }
}

With the code above myTextField is at the top left of my screen(my screens in landscape orientation). I can manually move it where I want by inputing numbers into the x and y values but then it moves to different places depending on the device. And when I try to do:

    myTextField = UITextField(frame: CGRect(x: self.size.width/2, y: self.size.height/2, width: 230.00, height: 33.00))

myTextField is missing from the screen. How can I center across all devices like I would in SpriteKit with: (x: self.size.width/2, y: self.size.height/2)

*Note I want to do this programmatically not with Storyboards


问:
Apache Beam: DoFn vs PTransform
Both DoFn and PTransform is a means to define operation for PCollection. How do we know which to use when?

答:
A simple way to understand it is by analogy with map(f) for lists:

The higher-order function map applies a function to each element of a list, returning a new list of the results. You might call it a computational pattern.

The function f is the logic applied to each element.

Now, switching to talk about Beam specifics, I think you are asking about ParDo.of(fn), which is a PTransform.

A PTransform is an operation that takes PCollections as input and yields PCollections as output. Beam has just five primitive types of PTransform, encapsulating embarrassingly parallel computational patterns.

ParDo is the computational pattern of per-element computation. It has some variations, but you don't need to worry about that for this question.

The DoFn, here I called it fn, is the logic that is applied to each element.

It may also help to think of the fact that you write a DoFn to say what to do on each element, and the Beam runner provides the ParDo to apply your logic.

Title: Apache Beam: DoFn vs PTransform


问:
How to upgrade scikit-learn package in anaconda
I am trying to upgrade package of scikit-learn from 0.16 to 0.17. For that I am trying to use binaries from this website: http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn. I have Windows 7 x64 bit. I downloaded the relevant package locally and gave following commands and got Requirement already up-to-date:

```<code>C:\Users\skumar>pip install --upgrade --use-wheel --no-index --find-links=../../
SOURCE/APPS scikit-learn
Ignoring indexes: https://pypi.python.org/simple
Requirement already up-to-date: scikit-learn in c:\anaconda3\lib\site-packages
</code>```

Then I tried to upgrade it from remote site and got similar result:

```<code>C:\Users\skumar>pip install --upgrade --use-wheel --no-index --trusted-host www.
lfd.uci.edu --find-links=http://www.lfd.uci.edu/~gohlke/pythonlibs/ scikit-learn

Ignoring indexes: https://pypi.python.org/simple
Requirement already up-to-date: scikit-learn in c:\anaconda3\lib\site-packages
</code>```

On Remote site there are two versions i.e., 0.16 & 0.17. Is there a way to specify version in command? Or how do you install/upgrade wheel file?

答:
So to upgrade scikit-learn package, you have to follow below process

Step-1: Open your terminal(Ctrl+Alt+t)

Step-2: Now for checking currently installed packages along with the
             versions installed on your
        conda environment by typing conda list

Step-3: Now for upgrade type below command

```<code>conda update scikit-learn
</code>```

Hope it helps!!

Body:
I am trying to upgrade package of scikit-learn from 0.16 to 0.17. For that I am trying to use binaries from this website: http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn. I have Windows 7 x64 bit. I downloaded the relevant package locally and gave following commands and got Requirement already up-to-date:

C:\Users\skumar>pip install --upgrade --use-wheel --no-index --find-links=../../
SOURCE/APPS scikit-learn
Ignoring indexes: https://pypi.python.org/simple
Requirement already up-to-date: scikit-learn in c:\anaconda3\lib\site-packages

Then I tried to upgrade it from remote site and got similar result:

C:\Users\skumar>pip install --upgrade --use-wheel --no-index --trusted-host www.
lfd.uci.edu --find-links=http://www.lfd.uci.edu/~gohlke/pythonlibs/ scikit-learn

Ignoring indexes: https://pypi.python.org/simple
Requirement already up-to-date: scikit-learn in c:\anaconda3\lib\site-packages

On Remote site there are two versions i.e., 0.16 & 0.17. Is there a way to specify version in command? Or how do you install/upgrade wheel file?

Body:
So to upgrade scikit-learn package, you have to follow below process

Step-1: Open your terminal(Ctrl+Alt+t)

Step-2: Now for checking currently installed packages along with the
             versions installed on your
        conda environment by typing conda list

Step-3: Now for upgrade type below command

conda update scikit-learn

Hope it helps!!


答:
you can simply use filter and find the length of the list

```<code>println(test1.filter(_.startsWith("z")).length)
</code>```

If you want to ignore the cases (uppercase or lowercase) you can add .toLowerCase as

```<code>println(test1.filter(_.toLowerCase.startsWith("z")).length)
</code>```

I hope the answer is helpful

Title: How to calculate number of occurrence of a character at beginning in a List of String using Scala

Body:
you can simply use filter and find the length of the list

println(test1.filter(_.startsWith("z")).length)

If you want to ignore the cases (uppercase or lowercase) you can add .toLowerCase as

println(test1.filter(_.toLowerCase.startsWith("z")).length)

I hope the answer is helpful


问:
Qt Designer button image change while keeping windows style?
I can change the image or any other style of a QPushButton in the designer by changing the stylesheet, but any change in the style sheet changes all the other properties.

For instance, when I change the border image everything else is changed and it does not inherit the rest of the properties from the parent (or windows style).

How can I keep the windows style while changing only the image?

答:
From How can I set Styles to a QTabwidget without overwriting existing styles in QT ?:

A style sheet is all or nothing. so if u all apply style sheet, it
  might sort of reset the look for some widgets and to fix that, you
  must supply a full stylesheet.

The key parts are:

A style sheet is all or nothing.

you must supply a full stylesheet.

You can set an image for the QPushButton from the code or by using QtDesigner like this:

Select the button

In the properties window set the image and the
size (properties icon and iconSize).


问:
How do I pass a context inside a loop into a TTask.IFuture in Delphi?
I have a set of tasks to perform they are in an array. I want to loop through the array and launch a task for each.

The following example is trivial (calculating squares) to demonstrate the issue.

```<code>program FutureSquares;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Threading,
  System.Classes;
const
  nums: array[0..9] of Integer = (1,2,3,4,5,6,7,8,9,10);
var
  i, contextIndex: Integer;
  f: array[0..9] of ITask;
  answer, futureAnswer: Integer;
  matchDisplay: string;
  futureFunc: TFunc<Integer>;
begin

  try
    for i := Low(f) to High(f) do
    begin
      contextIndex := i;

      futureFunc := function: Integer
        begin
          Sleep(Random(1000));
          Result := nums[contextIndex]*nums[contextIndex]; // trying  because a reference to it is captured. How to capture the actual value?
        end;

      f[i] := TTask.Future<Integer>(futureFunc);
      f[i].Start;
    end;

    //verify results in sequential manner
    for i := Low(f) to High(f) do
    begin
      answer := nums[i]*nums[i];
      futureAnswer := IFuture<Integer>(f[i]).Value;
      if futureAnswer = answer then
        matchDisplay := 'match'
      else
        matchDisplay := 'MISMATCH';
      writeln(Format('%d * %d = %d. Future<Integer> = %d - %s', [nums[i],nums[i],answer, futureAnswer, matchDisplay]));
    end;

    readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
</code>```

The output from the program is as follows:

```<code>1 * 1 = 1. Future<Integer> = 16 - MISMATCH
2 * 2 = 4. Future<Integer> = 100 - MISMATCH
3 * 3 = 9. Future<Integer> = 100 - MISMATCH
4 * 4 = 16. Future<Integer> = 100 - MISMATCH
5 * 5 = 25. Future<Integer> = 100 - MISMATCH
6 * 6 = 36. Future<Integer> = 100 - MISMATCH
7 * 7 = 49. Future<Integer> = 100 - MISMATCH
8 * 8 = 64. Future<Integer> = 100 - MISMATCH
9 * 9 = 81. Future<Integer> = 100 - MISMATCH
10 * 10 = 100. Future<Integer> = 100 - match
</code>```

How can I achieve my goal?

I note that TTask.Future does not allow me to pass a context to it which would be useful.

答:
You need to capture the value and not the variable in your anonymous method. The easiest way to do this is to put the anonymous method in a standalone function and pass in index that you would like captured. That way, the value will be captured instead of the variable.

```<code>function CaptureFuture(const aTheIndex: Integer): TFunc<Integer>;
begin
  Result := function: Integer
    begin
      Sleep(Random(1000));
      Result := nums[aTheIndex]*nums[aTheIndex]; // trying  because a reference to it is captured. How to capture the actual value?
    end;
end;
</code>```

And then, when you do the assignment of futureFunc, your code would look like this:

```<code>for i := Low(f) to High(f) do
begin
  futureFunc := CaptureFuture(i);

  f[i] := TTask.Future<Integer>(futureFunc);
  f[i].Start;
end;
</code>```

This will give you the desired results:

```<code>1 * 1 = 1. Future<Integer> = 1 - match
2 * 2 = 4. Future<Integer> = 4 - match
3 * 3 = 9. Future<Integer> = 9 - match
4 * 4 = 16. Future<Integer> = 16 - match
5 * 5 = 25. Future<Integer> = 25 - match
6 * 6 = 36. Future<Integer> = 36 - match
7 * 7 = 49. Future<Integer> = 49 - match
8 * 8 = 64. Future<Integer> = 64 - match
9 * 9 = 81. Future<Integer> = 81 - match
10 * 10 = 100. Future<Integer> = 100 - match
</code>```

See this question for more information on variable vs value capturing:
Anonymous methods - variable capture versus value capture

Body:
I have a set of tasks to perform they are in an array. I want to loop through the array and launch a task for each.

The following example is trivial (calculating squares) to demonstrate the issue.

program FutureSquares;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Threading,
  System.Classes;
const
  nums: array[0..9] of Integer = (1,2,3,4,5,6,7,8,9,10);
var
  i, contextIndex: Integer;
  f: array[0..9] of ITask;
  answer, futureAnswer: Integer;
  matchDisplay: string;
  futureFunc: TFunc<Integer>;
begin

  try
    for i := Low(f) to High(f) do
    begin
      contextIndex := i;

      futureFunc := function: Integer
        begin
          Sleep(Random(1000));
          Result := nums[contextIndex]*nums[contextIndex]; // trying  because a reference to it is captured. How to capture the actual value?
        end;

      f[i] := TTask.Future<Integer>(futureFunc);
      f[i].Start;
    end;

    //verify results in sequential manner
    for i := Low(f) to High(f) do
    begin
      answer := nums[i]*nums[i];
      futureAnswer := IFuture<Integer>(f[i]).Value;
      if futureAnswer = answer then
        matchDisplay := 'match'
      else
        matchDisplay := 'MISMATCH';
      writeln(Format('%d * %d = %d. Future<Integer> = %d - %s', [nums[i],nums[i],answer, futureAnswer, matchDisplay]));
    end;

    readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

The output from the program is as follows:

1 * 1 = 1. Future<Integer> = 16 - MISMATCH
2 * 2 = 4. Future<Integer> = 100 - MISMATCH
3 * 3 = 9. Future<Integer> = 100 - MISMATCH
4 * 4 = 16. Future<Integer> = 100 - MISMATCH
5 * 5 = 25. Future<Integer> = 100 - MISMATCH
6 * 6 = 36. Future<Integer> = 100 - MISMATCH
7 * 7 = 49. Future<Integer> = 100 - MISMATCH
8 * 8 = 64. Future<Integer> = 100 - MISMATCH
9 * 9 = 81. Future<Integer> = 100 - MISMATCH
10 * 10 = 100. Future<Integer> = 100 - match

How can I achieve my goal?

I note that TTask.Future does not allow me to pass a context to it which would be useful.

Body:
You need to capture the value and not the variable in your anonymous method. The easiest way to do this is to put the anonymous method in a standalone function and pass in index that you would like captured. That way, the value will be captured instead of the variable.

function CaptureFuture(const aTheIndex: Integer): TFunc<Integer>;
begin
  Result := function: Integer
    begin
      Sleep(Random(1000));
      Result := nums[aTheIndex]*nums[aTheIndex]; // trying  because a reference to it is captured. How to capture the actual value?
    end;
end;

And then, when you do the assignment of futureFunc, your code would look like this:

for i := Low(f) to High(f) do
begin
  futureFunc := CaptureFuture(i);

  f[i] := TTask.Future<Integer>(futureFunc);
  f[i].Start;
end;

This will give you the desired results:

1 * 1 = 1. Future<Integer> = 1 - match
2 * 2 = 4. Future<Integer> = 4 - match
3 * 3 = 9. Future<Integer> = 9 - match
4 * 4 = 16. Future<Integer> = 16 - match
5 * 5 = 25. Future<Integer> = 25 - match
6 * 6 = 36. Future<Integer> = 36 - match
7 * 7 = 49. Future<Integer> = 49 - match
8 * 8 = 64. Future<Integer> = 64 - match
9 * 9 = 81. Future<Integer> = 81 - match
10 * 10 = 100. Future<Integer> = 100 - match

See this question for more information on variable vs value capturing:
Anonymous methods - variable capture versus value capture


问:
app engine chaining deferred transactional tasks
When I call a deferred transactional task from a transactional function, f, f can commit while the deferred task fails.

HOWEVER, if I call f via a deferred call, the calling function fails.

To repro, I did the following:

```<code>@ndb.transactional()
def f():
  # modify datastore entity X
  ...
  x.put()

class X(ndb.Model):
  ...
  def _post_put_hook(self, future)
    deferred.defer(y,
                   _transactional=ndb.in_transaction())
def y():
  raise Exception()
</code>```

When I call f, the deferred task fails, but x.put() commits.

HOWEVER, if I call deferred.f, x.put() fails.

答:
I think you misunderstood what the _transactional optional argument in deferred.defer(y, _transactional=ndb.in_transaction()) does. It doesn't mean that the deferred y execution will happen in the same transaction in which deferred.defer() was called, it only means that enqueuing the deferred task will happen if the transaction succeeds.

From google.appengine.ext.deferred.deferred module:

google.appengine.ext.deferred.deferred.defer(obj, *args, **kwargs)

[...]

obj – The callable to execute. See module docstring for restrictions. _countdown, _eta, _headers, _name, _target,
  _transactional, _url, _retry_options, _queue: Passed through to the task queue - see the task queue documentation for details.

And from google.appengine.api.taskqueue.taskqueue module:

add(task, transactional=False)

[...]

transactional – If True, transactional tasks will be added to the queue but cannot be run or leased until after the transaction
  succeeds. If the transaction fails then the tasks will be removed from
  the queue (and therefore will never run). If False, the added tasks
  are available to run immediately; any enclosing transaction’s success
  or failure is ignored.

The actual execution of the deferred task is done on another request, always in a different transaction context than the one where deferred.defer() was called. Which is why your deferred task may fail even if your original transaction is successful.

Body:
When I call a deferred transactional task from a transactional function, f, f can commit while the deferred task fails.

HOWEVER, if I call f via a deferred call, the calling function fails.

To repro, I did the following:

@ndb.transactional()
def f():
  # modify datastore entity X
  ...
  x.put()

class X(ndb.Model):
  ...
  def _post_put_hook(self, future)
    deferred.defer(y,
                   _transactional=ndb.in_transaction())
def y():
  raise Exception()

When I call f, the deferred task fails, but x.put() commits.

HOWEVER, if I call deferred.f, x.put() fails.


问:
Spark: Initial job has not accepted any resources
I've installed a Spark cluster on 4 different machines.  Each machine has 7.7gb of memory with an 8-core i7 processor.  I'm using Pyspark and trying to load 5 numpy arrays (2.9gb each) into the cluster.  They are all part of a bigger 14gb numpy array that I generated on a separate machine.  I'm trying to run a simple count function on the first rdd to make sure my cluster is running properly.  I get the following warning upon execution:

```<code>>>> import numpy as np
>>> gen1 = sc.parallelize(np.load('/home/hduser/gen1.npy'),512)
>>> gen1.count()
[Stage 0:>                                                        (0 + 0) / 512]
17/01/28 13:07:07 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
17/01/28 13:07:22 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
17/01/28 13:07:37 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
[Stage 0:>                                                        (0 + 0) / 512]
17/01/28 13:07:52 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
^C
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/spark/python/pyspark/rdd.py", line 1008, in count
    return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
  File "/opt/spark/python/pyspark/rdd.py", line 999, in sum
    return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
  File "/opt/spark/python/pyspark/rdd.py", line 873, in fold
    vals = self.mapPartitions(func).collect()
  File "/opt/spark/python/pyspark/rdd.py", line 776, in collect
    port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
  File "/opt/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 931, in __call__
  File "/opt/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 695, in send_command
  File "/opt/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 828, in send_command
  File "/home/hduser/anaconda2/lib/python2.7/socket.py", line 451, in readline
    data = self._sock.recv(self._rbufsize)
  File "/opt/spark/python/pyspark/context.py", line 223, in signal_handler
    raise KeyboardInterrupt()
KeyboardInterrupt
</code>```

When I check my cluster UI, it says there are 3 functioning workers, but only 1 executor (the driver, associated with my master IP).  I'm assuming this is a configuration issue.

My settings in spark-env.sh (master):

```<code>export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export SPARK_MASTER_IP=192.168.1.2
</code>```

These settings are identical on each of the worker machines.

My settings in spark-defaults.conf (master):

```<code>spark.master    spark://lebron:7077
spark.serializer    org.apache.spark.serializer.KryoSerializer
spark.driver.memory 5g
spark.dynamicAllocation.enabled true
spark.shuffle.service.enabled   true
spark.kryoserializer.buffer.max 128m
</code>```

Each worker has only spark.master and spark.serializer configuration options set as above.

I also need to figure out how to tune my memory management, since before this issue came up I was having Java heap space OOM exceptions thrown left and right when I should have had plenty of memory.  But maybe I'll save that for a different question.

Please help!

答:
If you can find spark slaves in the web UI but they are not accepting jobs, there is a high chance that the firewall is blocking the communication.

You can do a test as in my other answer: Apache Spark on Mesos: Initial job has not accepted any resources

Body:
I've installed a Spark cluster on 4 different machines.  Each machine has 7.7gb of memory with an 8-core i7 processor.  I'm using Pyspark and trying to load 5 numpy arrays (2.9gb each) into the cluster.  They are all part of a bigger 14gb numpy array that I generated on a separate machine.  I'm trying to run a simple count function on the first rdd to make sure my cluster is running properly.  I get the following warning upon execution:

>>> import numpy as np
>>> gen1 = sc.parallelize(np.load('/home/hduser/gen1.npy'),512)
>>> gen1.count()
[Stage 0:>                                                        (0 + 0) / 512]
17/01/28 13:07:07 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
17/01/28 13:07:22 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
17/01/28 13:07:37 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
[Stage 0:>                                                        (0 + 0) / 512]
17/01/28 13:07:52 WARN scheduler.TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
^C
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/spark/python/pyspark/rdd.py", line 1008, in count
    return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
  File "/opt/spark/python/pyspark/rdd.py", line 999, in sum
    return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
  File "/opt/spark/python/pyspark/rdd.py", line 873, in fold
    vals = self.mapPartitions(func).collect()
  File "/opt/spark/python/pyspark/rdd.py", line 776, in collect
    port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
  File "/opt/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 931, in __call__
  File "/opt/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 695, in send_command
  File "/opt/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 828, in send_command
  File "/home/hduser/anaconda2/lib/python2.7/socket.py", line 451, in readline
    data = self._sock.recv(self._rbufsize)
  File "/opt/spark/python/pyspark/context.py", line 223, in signal_handler
    raise KeyboardInterrupt()
KeyboardInterrupt

When I check my cluster UI, it says there are 3 functioning workers, but only 1 executor (the driver, associated with my master IP).  I'm assuming this is a configuration issue.

My settings in spark-env.sh (master):

export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export SPARK_MASTER_IP=192.168.1.2

These settings are identical on each of the worker machines.

My settings in spark-defaults.conf (master):

spark.master    spark://lebron:7077
spark.serializer    org.apache.spark.serializer.KryoSerializer
spark.driver.memory 5g
spark.dynamicAllocation.enabled true
spark.shuffle.service.enabled   true
spark.kryoserializer.buffer.max 128m

Each worker has only spark.master and spark.serializer configuration options set as above.

I also need to figure out how to tune my memory management, since before this issue came up I was having Java heap space OOM exceptions thrown left and right when I should have had plenty of memory.  But maybe I'll save that for a different question.

Please help!


问:
Use pods in an embedded framework
Like a previous question - although that recommended link_with 'MyCustomFramework and that is depreciated - I have (my own) framework. The App and the framework are at different locations on my disk.

Both the framework and main App need Alamofire. It would make sense that I would install Alamofire as a Pod for my main App.

Inevitably my framework has the error "no such module"

I tried to add to my podfile

```<code>   target 'userAuthNoAlamo' do
   pod 'Alamofire'
 end
</code>```

But, as with dragging the frameworks and podfiles into various options for Build Phases I've had no luck. I haven't been able to point my add framework search paths to the podfile as it is in a different location to the App.

Any ideas?

答: So the only way that I got this to work is through creating private pods.</p>

Title: Use pods in an embedded framework

Body:
Like a previous question - although that recommended link_with 'MyCustomFramework and that is depreciated - I have (my own) framework. The App and the framework are at different locations on my disk.

Both the framework and main App need Alamofire. It would make sense that I would install Alamofire as a Pod for my main App.

Inevitably my framework has the error "no such module"

I tried to add to my podfile

   target 'userAuthNoAlamo' do
   pod 'Alamofire'
 end

But, as with dragging the frameworks and podfiles into various options for Build Phases I've had no luck. I haven't been able to point my add framework search paths to the podfile as it is in a different location to the App.

Any ideas?


问:
Visual Studio Code for .NET Framework
I am having difficulty figuring out if and how I can use Visual Studio Code to develop and debug command-line/console/libraries of C# .NET programs which can not run on .NET Core, i.e. they require .NET Framework.
I need to access Oracle which do not have a .NET Core provider but it does have a Managed .NET Framework provider.
I use VS 2015/2017 for this task but would like to switch to VS Code if I could code, build and debug .NET Framework target C# programs.
I have tried Google search and could not find anything.

答:
https://code.visualstudio.com/docs/languages/csharp

Quote:

Note: VS Code does not support debugging applications running on the Desktop .NET Framework.

It looks like Visual Studio 'full-fat' IDE remains a requirement for .Net Framework. Major pity.

Title: Visual Studio Code for .NET Framework


问:
Issue with changing date format inline with PHP
I am pulling a date from a database and it is in the format 2017-12-07.  That is how I was displaying the date, however, I would like to display is like Dec 7, 17.

What I tried.

```<code>echo "<td>" . date_format($row['returndate'],'M d, y') . "</td>";
</code>```

My results end up empty.  I have successfully changed the date format with in the MYSQLI line, however, I was wanting to do it with PHP.

UPDATE

I apologize, it seems I over looked something simple.  Below fixed it.

```<code>date('M d, y', strtotime($row['returndate']))
</code>```

I guess you have to do strtotime before date.

答:
date_format requires an DateTime object. In your case, you can simply use (without class DateTime):

```<code>print date('M d, y', strtotime('2017-12-07'));
Dec 07, 17
</code>```

Or if you would like to use DateTime exactly, you can try:

```<code>php > $d = new DateTime('2017-12-07');
php > print $d->format('M d, y');
Dec 07, 17
</code>```

Body:
I am pulling a date from a database and it is in the format 2017-12-07.  That is how I was displaying the date, however, I would like to display is like Dec 7, 17.

What I tried.

echo "" . date_format($row['returndate'],'M d, y') . "	";

My results end up empty.  I have successfully changed the date format with in the MYSQLI line, however, I was wanting to do it with PHP.

UPDATE

I apologize, it seems I over looked something simple.  Below fixed it.

date('M d, y', strtotime($row['returndate']))

I guess you have to do strtotime before date.

Body:
date_format requires an DateTime object. In your case, you can simply use (without class DateTime):

print date('M d, y', strtotime('2017-12-07'));
Dec 07, 17

Or if you would like to use DateTime exactly, you can try:

php > $d = new DateTime('2017-12-07');
php > print $d->format('M d, y');
Dec 07, 17


问:
Converting hex into a string using 'sprintf'
I am trying to convert an array into hex and then put it into a string variable. In the following loop the printf works fine, but I can not use sprintf properly. How can I stuff the hex values into the array as ASCII?</p>

```<code>static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i], "%02x", digest[i]);  <--- DOES NOT WORK!
}
</code>```

答:
A char stored as numeric is not the same as a string:</p>

```<code>unsigned char i = 255;
unsigned char* str = "FF";
unsigned char arr1[] = { 'F', 'F', '\0' };
unsigned char arr2[] = { 70, 70, 0 };
</code>```

Body:
I am trying to convert an array into hex and then put it into a string variable. In the following loop the printf works fine, but I can not use sprintf properly. How can I stuff the hex values into the array as ASCII?

static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i], "%02x", digest[i]);  <--- DOES NOT WORK!
}

Body:
A char stored as numeric is not the same as a string:

unsigned char i = 255;
unsigned char* str = "FF";
unsigned char arr1[] = { 'F', 'F', '\0' };
unsigned char arr2[] = { 70, 70, 0 };

ContentLicense: CC BY-SA 2.5


问:
What is the best way to avoid keyError when using python dictionary?
```<code>    for target, source ,in zip(self.tCorpus, self.fCorpus):
        #print(target, source)
        self.pairLength[len(target), len(source)] += 1
</code>```

It's obvious that this will give me a key error since I did not initialize the key len(target), len(source) before using this. I know I could use default dict to avoid this kind of error, but I am not sure how to avoid it in this particular case. Is there a way to prevent keyerror and increment values for len(target), len(source) ?

答:
Normally, I would recommend the setdefault method; it takes the key and a default value as arguments. If the key is not found it is assigned the default value and that value is also returned. If the key does exist, the default value is ignored and normal lookup takes place:

```<code>a = {}
a.setdefault(7, []).append(1)
a
# {7: [1]}
a.setdefault(7, []).append(2)
a
# {7: [1, 2]}
</code>```

In your case that doesn't work because we are not changing the value but reassigning it. Therefore

```<code>a[key] = a.get(key, 0) + 1
</code>```

The difference between get and setdefault is that get does not assign the default value in case of key miss. It always leaves the dict unchanged. But since we have to explicitly reassign anyway - numbers being immutable - that is appropriate here.

Body:
    for target, source ,in zip(self.tCorpus, self.fCorpus):
        #print(target, source)
        self.pairLength[len(target), len(source)] += 1

It's obvious that this will give me a key error since I did not initialize the key len(target), len(source) before using this. I know I could use default dict to avoid this kind of error, but I am not sure how to avoid it in this particular case. Is there a way to prevent keyerror and increment values for len(target), len(source) ?

Body:
Normally, I would recommend the setdefault method; it takes the key and a default value as arguments. If the key is not found it is assigned the default value and that value is also returned. If the key does exist, the default value is ignored and normal lookup takes place:

a = {}
a.setdefault(7, []).append(1)
a
# {7: [1]}
a.setdefault(7, []).append(2)
a
# {7: [1, 2]}

In your case that doesn't work because we are not changing the value but reassigning it. Therefore

a[key] = a.get(key, 0) + 1

The difference between get and setdefault is that get does not assign the default value in case of key miss. It always leaves the dict unchanged. But since we have to explicitly reassign anyway - numbers being immutable - that is appropriate here.


问:
Translate Elasticsearch DSL to gopkg.in/olivere/elastic.v5

I've got json that I want to translate into an Elasticsearch query using https://godoc.org/gopkg.in/olivere/elastic.v5

json =

```<code>{
  "query": {
    "bool": {
      "filter": [
        {
          "exists": {
            "field": "Videos.en"
          }
        }
      ]
    }
  }
}
</code>```

Pretty simple!  What I've got so far - which clearly isn't working - is:

```<code>enVidsQuery, err := elastic.NewBoolQuery().
        Filter(elastic.Exists("field", "Videos.en"))
</code>```

Where elastic references "gopkg.in/olivere/elastic.v5" in my imports.

Can anyone provide me with the correct syntax?  I figure it's a trivial solution for anyone familiar with the library.

答:
Correct query will be:</p>

```<code>elastic.NewBoolQuery().Filter(elastic.NewExistsQuery("Videos.en"))
</code>```

Body:
I've got json that I want to translate into an Elasticsearch query using https://godoc.org/gopkg.in/olivere/elastic.v5

json =

{
  "query": {
    "bool": {
      "filter": [
        {
          "exists": {
            "field": "Videos.en"
          }
        }
      ]
    }
  }
}

Pretty simple!  What I've got so far - which clearly isn't working - is:

enVidsQuery, err := elastic.NewBoolQuery().
        Filter(elastic.Exists("field", "Videos.en"))

Where elastic references "gopkg.in/olivere/elastic.v5" in my imports.

Can anyone provide me with the correct syntax?  I figure it's a trivial solution for anyone familiar with the library.

Body:
Correct query will be:

elastic.NewBoolQuery().Filter(elastic.NewExistsQuery("Videos.en"))


问:
Can I Implement a Casting Feature for Google Home Customized for My Needs?
I want to add a custom casting feature to my Google Home. What I've done so far was the tutorial using Dialogflow from this page: https://developers.google.com/actions/dialogflow/first-app

Then I found a repo about casting videos to Chromecast, only from PC and not from Google Home: https://github.com/googlecast/CastHelloVideo-chrome/blob/master/helloVideos.js

Then I tried combining the two. I've only tried to connect to my Chromecast so far, but I get this error every time:

```<code>API Version 2: Failed to parse JSON response string with 'INVALID_ARGUMENT' error: ": Cannot find field.".
</code>```

I made the tutorial work, so I didn't change anything on Dialogflow, only the index.js file.

This is my file:

```<code> 'use strict';

process.env.DEBUG = 'actions-on-google:*';
const App = require('actions-on-google').DialogflowApp;
const functions = require('firebase-functions');

// a. the action name from the make_name Dialogflow intent
const NAME_ACTION = 'game_cast';
// b. the parameters that are parsed from the make_name intent
const COLOR_ARGUMENT = 'color';
const NUMBER_ARGUMENT = 'number';

exports.gameCast = functions.https.onRequest((request, response) => {
  const app = new App({request, response});
  console.log('Request headers: ' + JSON.stringify(request.headers));
  console.log('Request body: ' + JSON.stringify(request.body));

// c. The function that generates the silly name
  function gameCast (app) {
    let number = app.getArgument(NUMBER_ARGUMENT);
    let color = app.getArgument(COLOR_ARGUMENT);
//    app.tell('Alright, your silly name is ' +
//      color + ' ' + number +
//      '! I hope you like it. See you next time.');
    launchApp();
  }

  // d. build an action map, which maps intent names to functions
  let actionMap = new Map();
  actionMap.set(NAME_ACTION, gameCast);

app.handleRequest(actionMap);
});
</code>```

The launchApp() function call in the gameCast function would connect to my Chromecast. Additionally I added the whole content of helloVideos.js, so there wouldn't be any missing functions that launchApp() may uses. (I didn't include my original file here, as the file helloVideos.js has 617 lines of code.)

Any suggestions would be greatly appreciated! Thanks!

答:
" Cannot find field" comes when your google action intent name is different from gamecast on the api.ai console.

You can goto google cloud back end https://console.cloud.google.com and check the logging error.

Body:
I want to add a custom casting feature to my Google Home. What I've done so far was the tutorial using Dialogflow from this page: https://developers.google.com/actions/dialogflow/first-app

Then I found a repo about casting videos to Chromecast, only from PC and not from Google Home: https://github.com/googlecast/CastHelloVideo-chrome/blob/master/helloVideos.js

Then I tried combining the two. I've only tried to connect to my Chromecast so far, but I get this error every time:

API Version 2: Failed to parse JSON response string with 'INVALID_ARGUMENT' error: ": Cannot find field.".

I made the tutorial work, so I didn't change anything on Dialogflow, only the index.js file.

This is my file:

 'use strict';

process.env.DEBUG = 'actions-on-google:*';
const App = require('actions-on-google').DialogflowApp;
const functions = require('firebase-functions');

// a. the action name from the make_name Dialogflow intent
const NAME_ACTION = 'game_cast';
// b. the parameters that are parsed from the make_name intent
const COLOR_ARGUMENT = 'color';
const NUMBER_ARGUMENT = 'number';

exports.gameCast = functions.https.onRequest((request, response) => {
  const app = new App({request, response});
  console.log('Request headers: ' + JSON.stringify(request.headers));
  console.log('Request body: ' + JSON.stringify(request.body));

// c. The function that generates the silly name
  function gameCast (app) {
    let number = app.getArgument(NUMBER_ARGUMENT);
    let color = app.getArgument(COLOR_ARGUMENT);
//    app.tell('Alright, your silly name is ' +
//      color + ' ' + number +
//      '! I hope you like it. See you next time.');
    launchApp();
  }

  // d. build an action map, which maps intent names to functions
  let actionMap = new Map();
  actionMap.set(NAME_ACTION, gameCast);

app.handleRequest(actionMap);
});

The launchApp() function call in the gameCast function would connect to my Chromecast. Additionally I added the whole content of helloVideos.js, so there wouldn't be any missing functions that launchApp() may uses. (I didn't include my original file here, as the file helloVideos.js has 617 lines of code.)

Any suggestions would be greatly appreciated! Thanks!


问:
CSS transparent colour overlay fade not working on iOS
I have made a grid of images and when you hover over them a semi-transparent overlay fades in and out and some text appears

I wanted this to work similarly on mobile devices, only instead of it fading in when you hover, it fades in when you tap

I have managed to get this working on android but not on mobiles.

I will show my code and a few examples of solutions I have tried. I have tried so many but I am rather new to javascript (I have some functioning javascript working on my site though!) and nothing is working on iOS devices.

Js fiddle:

https://jsfiddle.net/49h450g9/

I am using bootstrap and less. My grid HTML code:

```<code><div class="col-sm-5 col-xs-5"><div class="image-wrap">

<img src="assets/images/image1.jpg">
<div class="overlay purple2">
<br>
    <h3>image 1</h3>
    <hr>
      <p>description</p>
      <br>
      <a href="#" class="btn btn-white btn-lg">View Website</a>
    </div>
</div>
</div>
<div class="col-sm-3 col-xs-3"><div class="image-wrap">
<img src="assets/images/image2.jpg">

    <div class="overlay blue">
    <h3>image 2</h3>
    <hr>
      <p>description</p>
      <br>
      <a href="#" class="btn btn-white btn-lg">View Website</a>
    </div>

</div>
</div>
<div class="col-sm-4 col-xs-4"><div class="image-wrap">
<img src="assets/images/image4.jpg">
<div class="overlay purple1">
    <h3>image 3</h3>
    <hr>
      <p>description</p>
      <br>
      <a href="#" class="btn btn-white btn-lg">View Website</a>
    </div>

</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-7 col-xs-7"><div class="image-wrap">
<img src="assets/images/image5.jpg">
<div class="overlay blue">
    <h3>image 5</h3>
    <hr>
      <p><strong>description</p>
      <br>
      <a href="#" class="btn btn-white btn-lg">View Website</a>
    </div>

</div>
</div>
<div class="col-sm-5 col-xs-5"><div class="image-wrap">
<img src="assets/images/image6.jpg">
<div class="overlay purple2">
    <h3>Image 6</h3>
    <hr>
      <p>description</p>
      <br>
      <a href="about-us.php" class="btn btn-white btn-lg">View Website</a>
    </div>
    </a>
</div>

    </div>
   </div>
</div>
</code>```

CSS:

```<code>.image-wrap {
display: inline-block;
position: relative;
}
.overlay {
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
color:white;
opacity: 0;
transition:opacity .5s ease-out;
text-align: center;
hr {
border: 1px solid #fff;
width: 10%;
 }

}

.image-wrap:hover .overlay {
opacity: 1;
}

.red {
background: rgba(102,67,154,0.7);
}

.blue {
background: rgba(23,56,179,0.7);
}
.purple1 {
background: rgba(140,23,179,0.7);
}

.purple2 {
background: rgba(71,13,142,0.7);
}
</code>```

Solutions I have tried include:

adding

onclick=""

to the image wrap div element

2 adding the JS line to my js file:

```<code>$('body').bind('touchstart', function() {});
</code>```

Adding the following js to my js file:

2 adding the JS line to my js file:

```<code>$(document).ready(function(){

$(".overlay").hover(function(){
//On Hover - Works on ios
$("p").hide();
}, function(){
//Hover Off - Hover off doesn't seem to work on iOS
$("p").show();
})
});
</code>```

However, on iOS none of my solutions are working, when I tap no text or semi-transparent overlay fades in

I have been working on this for nearly a week and have looked at many questions on here but I cannot find a solution that works for me

Any help would be massively appreciated :)

Thanks!

答:
use :active pseudo class instead of :hover. In touch mobile devices, once an hover is triggered, it will not get removed once you take your finger off. It need you to tap on somewhere else on the screen.

similarly in jquery you can use mousedown() and mouseup() for the same purpose. on mousedown() you may show the overlay and mouseup() you may hide it.

Body:
I have made a grid of images and when you hover over them a semi-transparent overlay fades in and out and some text appears

I wanted this to work similarly on mobile devices, only instead of it fading in when you hover, it fades in when you tap

I have managed to get this working on android but not on mobiles.

I will show my code and a few examples of solutions I have tried. I have tried so many but I am rather new to javascript (I have some functioning javascript working on my site though!) and nothing is working on iOS devices.

Js fiddle:

https://jsfiddle.net/49h450g9/

I am using bootstrap and less. My grid HTML code:

image 1

description

      View Website

image 2

description

      View Website

image 3

description

      View Website

image 5

description

      View Website

Image 6

description

      View Website

CSS:

.image-wrap {
display: inline-block;
position: relative;
}
.overlay {
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
color:white;
opacity: 0;
transition:opacity .5s ease-out;
text-align: center;
hr {
border: 1px solid #fff;
width: 10%;
 }

}

.image-wrap:hover .overlay {
opacity: 1;
}

.red {
background: rgba(102,67,154,0.7);
}

.blue {
background: rgba(23,56,179,0.7);
}
.purple1 {
background: rgba(140,23,179,0.7);
}

.purple2 {
background: rgba(71,13,142,0.7);
}

Solutions I have tried include:

adding

onclick=""

to the image wrap div element

2 adding the JS line to my js file:

$('body').bind('touchstart', function() {});

Adding the following js to my js file:

2 adding the JS line to my js file:

$(document).ready(function(){

$(".overlay").hover(function(){
//On Hover - Works on ios
$("p").hide();
}, function(){
//Hover Off - Hover off doesn't seem to work on iOS
$("p").show();
})
});

However, on iOS none of my solutions are working, when I tap no text or semi-transparent overlay fades in

I have been working on this for nearly a week and have looked at many questions on here but I cannot find a solution that works for me

Any help would be massively appreciated :)

Thanks!


答:
You should use the php DateTime class:

```<code>$date = new DateTime($row['returndate']);
echo $date->format('M d, y');
</code>```

Title: Issue with changing date format inline with PHP

Body:
You should use the php DateTime class:

$date = new DateTime($row['returndate']);
echo $date->format('M d, y');


问:
Reading project parameters in Script Task
This is what I'm trying to do in a script task:

```<code>long lngMaxRowsToPull = Convert.ToInt64(Dts.Variables["Project::MaxRowsPerPull"].Value);
</code>```

I get an error message that the variable does not exist.

Yet Its defined as a ReadOnlyVariable to the script and it does exist as a project parameter.

答:
You need to add $ to your parameter fetch name as per syntax. </p>

```<code>long lngMaxRowsToPull = Convert.ToInt64(Dts.Variables["$Project::MaxRowsPerPull"].Value);
</code>```

Body:
This is what I'm trying to do in a script task:

long lngMaxRowsToPull = Convert.ToInt64(Dts.Variables["Project::MaxRowsPerPull"].Value);

I get an error message that the variable does not exist.

Yet Its defined as a ReadOnlyVariable to the script and it does exist as a project parameter.

Body:
You need to add $ to your parameter fetch name as per syntax.

long lngMaxRowsToPull = Convert.ToInt64(Dts.Variables["$Project::MaxRowsPerPull"].Value);


问:
How do I get rid of the concurrency issue with update statements with an auto-incrementing key?
I have run into the following error message at run-time with my novice's Sql / Visual C# database program:

Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.

I have done some searching around about this issue and have seen several threads about it, but they aren't enough for me to resolve the issue.  I noticed people talking about how it can often occur when you're using an auto-incrementing primary key.  That is the case in this program.  Also there is no multithreading or anything else like that that I am coding into this program.  Therefore I think the auto-increment is possibly the only problem.

That being said, how do I get the update command to work, despite the auto-increment?  I can hardly stand on two feet when it comes to database programming, so please be detailed, if you don't mind.  Also the command I'm using is via a SqlCommandBuilder object.  I have set that object to new SqlCommandBuilder(DataAdapter), and I have not done anything special with it.

Thanks.

This edit is the second one.  The first one is below.

Due to my inexperience with database programming, I am unable to say this for sure.  However I have good reason to believe that the problem I am experiencing has to do with new rows not getting added to the database completely until the program terminates.  I do not understand why they are waiting until program termination to do that, or if they are waiting until then, just what exactly what about the program's termination causes them to suddenly get saved completely.  However I have forgotten to mention that this error only occurs on rows that I have added during that specific execution of the program.  If the row was already added on a previous execution or through pre-existing table data, everything's fine.  I am getting the same error with the delete method, and it also only occurs with new rows.

How do I get these rows to be fully saved to everything so that this doesn't happen?  What about the program's termination is causing these rows to get fully saved?  Thanks!

Due to a request, I have left here two code snippets.  The first one will be the method in which the the problem occurs.  The next one will include the entire class.  There are only two classes in the entire program, and the other class doesn't seem important to me in this particular issue.

```<code>    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }
</code>```

Next snippet:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Dakota
{
public partial class Form1 : Form
{
    SqlConnection con;
    DataSet dataset;
    SqlDataAdapter dAdapter;
    DataRow currentRow;
    string primaryKey;
    SqlCommandBuilder cmdBuilder;
    bool recordShown = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dataset = new DataSet();
        con = new SqlConnection();

        con.ConnectionString = "Data Source=.\\SQLEXPRESS;" +
            "AttachDbFilename=C:\\Users\\Sterling\\Documents\\Contacts.mdf;" +
            "Integrated Security=True;Connect Timeout=30;User Instance=True";

        con.Open();

        string getData = "SELECT * FROM tblContacts";
        dAdapter = new SqlDataAdapter(getData, con);
        dAdapter.Fill(dataset, "Contacts");
        cmdBuilder = new SqlCommandBuilder(dAdapter);
        cmdBuilder.ConflictOption = ConflictOption.OverwriteChanges;

        con.Close();
    }

    private void clearTextBoxes()
    {
        tbFirstName.Clear();
        tbMiddleName.Clear();
        tbLastName.Clear();
        tbSuffix.Clear();
        tbHomePhone.Clear();
        tbCellPhone.Clear();
        tbOtherPhone.Clear();
        tbStreetAddress.Clear();
        tbCityAndState.Clear();
        tbCountry.Clear();
        tbEmail.Clear();
    }

    private void fillTextBoxes(int row)
    {
        DataRow dr = dataset.Tables["Contacts"].Rows[row];
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void fillTextBoxes(DataRow dr)
    {
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        string searchFor = tbSearchFor.Text;
        string column;
        if (rbFirstName.Checked)
        {
            column = "firstName";
        }
        else
        {
            column = "lastName";
        }

        DataRow[] rows = dataset.Tables["Contacts"].Select(column + "='" + searchFor + "'");
        int number = rows.Length;

        if (number == 0)
        {
            MessageBox.Show("No such records were found.");
        }
        else if (number > 1)
        {
            string[] strings = new string[rows.Length];
            for (int i = 0; i < strings.Length; i++)
            {
                bool hasFirst = false;
                bool hasMiddle = false;

                strings[i] = "";
                if (rows[i].ItemArray.GetValue(1).ToString() != "")
                {
                    hasFirst = true;
                    strings[i] += rows[i].ItemArray.GetValue(1).ToString();
                }
                if (rows[i].ItemArray.GetValue(2).ToString() != "")
                {
                    hasMiddle = true;
                    if (hasFirst)
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(2).ToString();
                }
                if (rows[i].ItemArray.GetValue(3).ToString() != "")
                {
                    if ((hasFirst && !hasMiddle) || (hasMiddle))
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(3).ToString();
                }
                if (rows[i].ItemArray.GetValue(4).ToString() != "")
                {
                    strings[i] += " " + rows[i].ItemArray.GetValue(4).ToString();
                }
            }

           // int choice;
            Form2 form2 = new Form2(strings);
            if (form2.ShowDialog(this) == DialogResult.OK)
            {
                primaryKey = rows[form2.choice].ItemArray.GetValue(0).ToString();
               // choice = form2.choice;
                fillTextBoxes(rows[form2.choice]);
                currentRow = rows[form2.choice];
                recordShown = true;
            }
        }
        else
        {
            primaryKey = rows[0].ItemArray.GetValue(0).ToString();
            currentRow = rows[0];
            fillTextBoxes(rows[0]);
            recordShown = true;
        }
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        con.Open();

        DataRow row = dataset.Tables["Contacts"].NewRow();
        row[1] = tbFirstName.Text;
        row[2] = tbMiddleName.Text;
        row[3] = tbLastName.Text;
        row[4] = tbSuffix.Text;
        row[5] = tbHomePhone.Text;
        row[6] = tbCellPhone.Text;
        row[7] = tbOtherPhone.Text;
        row[8] = tbStreetAddress.Text;
        row[9] = tbCityAndState.Text;
        row[10] = tbCountry.Text;
        row[11] = tbEmail.Text;
        currentRow = row;

        dataset.Tables["Contacts"].Rows.Add(row);
        dAdapter.Update(dataset, "Contacts");
        recordShown = true;

        con.Close();
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        con.Open();

        currentRow.Delete();
        dAdapter.Update(dataset, "Contacts");
        clearTextBoxes();
        recordShown = false;

        con.Close();
    }
}
}
</code>```

Thanks!

答:
Here is one explanation but I am not sure if it is exactly what you are seeing:

http://blogs.msdn.com/b/spike/archive/2010/04/07/concurrency-violation-the-updatecommand-affected-0-of-the-expected-1-records.aspx

This might be more on track and if so points to some missing lines that should come after you declare cmdBuilder:

```<code>dAdapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
dAdapter.InsertCommand = cmdBuilder.GetInsertCommand();
dAdapter.DeleteCommand = cmdBuilder.GetDeleteCommand();
</code>```

http://www.codeguru.com/forum/archive/index.php/t-337168.html

Also, you might need to call:

```<code>dAdapter.Fill(dataset, "Contacts");
</code>```

before the con.Close() for all three operations (Insert, Update, and Delete).

On an unrelated note, you could reduce duplicate code by changing the "fillTextBoxes(int row)" method to be just:

```<code>private void fillTextBoxes(int row)
{
  DataRow dr = dataset.Tables["Contacts"].Rows[row];
  fillTextBoxes(dr);
}
</code>```

Body:
I have run into the following error message at run-time with my novice's Sql / Visual C# database program:

Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.

I have done some searching around about this issue and have seen several threads about it, but they aren't enough for me to resolve the issue.  I noticed people talking about how it can often occur when you're using an auto-incrementing primary key.  That is the case in this program.  Also there is no multithreading or anything else like that that I am coding into this program.  Therefore I think the auto-increment is possibly the only problem.

That being said, how do I get the update command to work, despite the auto-increment?  I can hardly stand on two feet when it comes to database programming, so please be detailed, if you don't mind.  Also the command I'm using is via a SqlCommandBuilder object.  I have set that object to new SqlCommandBuilder(DataAdapter), and I have not done anything special with it.

Thanks.

This edit is the second one.  The first one is below.

Due to my inexperience with database programming, I am unable to say this for sure.  However I have good reason to believe that the problem I am experiencing has to do with new rows not getting added to the database completely until the program terminates.  I do not understand why they are waiting until program termination to do that, or if they are waiting until then, just what exactly what about the program's termination causes them to suddenly get saved completely.  However I have forgotten to mention that this error only occurs on rows that I have added during that specific execution of the program.  If the row was already added on a previous execution or through pre-existing table data, everything's fine.  I am getting the same error with the delete method, and it also only occurs with new rows.

How do I get these rows to be fully saved to everything so that this doesn't happen?  What about the program's termination is causing these rows to get fully saved?  Thanks!

Due to a request, I have left here two code snippets.  The first one will be the method in which the the problem occurs.  The next one will include the entire class.  There are only two classes in the entire program, and the other class doesn't seem important to me in this particular issue.

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }

Next snippet:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Dakota
{
public partial class Form1 : Form
{
    SqlConnection con;
    DataSet dataset;
    SqlDataAdapter dAdapter;
    DataRow currentRow;
    string primaryKey;
    SqlCommandBuilder cmdBuilder;
    bool recordShown = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dataset = new DataSet();
        con = new SqlConnection();

        con.ConnectionString = "Data Source=.\\SQLEXPRESS;" +
            "AttachDbFilename=C:\\Users\\Sterling\\Documents\\Contacts.mdf;" +
            "Integrated Security=True;Connect Timeout=30;User Instance=True";

        con.Open();

        string getData = "SELECT * FROM tblContacts";
        dAdapter = new SqlDataAdapter(getData, con);
        dAdapter.Fill(dataset, "Contacts");
        cmdBuilder = new SqlCommandBuilder(dAdapter);
        cmdBuilder.ConflictOption = ConflictOption.OverwriteChanges;

        con.Close();
    }

    private void clearTextBoxes()
    {
        tbFirstName.Clear();
        tbMiddleName.Clear();
        tbLastName.Clear();
        tbSuffix.Clear();
        tbHomePhone.Clear();
        tbCellPhone.Clear();
        tbOtherPhone.Clear();
        tbStreetAddress.Clear();
        tbCityAndState.Clear();
        tbCountry.Clear();
        tbEmail.Clear();
    }

    private void fillTextBoxes(int row)
    {
        DataRow dr = dataset.Tables["Contacts"].Rows[row];
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void fillTextBoxes(DataRow dr)
    {
        tbFirstName.Text = dr.ItemArray.GetValue(1).ToString();
        tbMiddleName.Text = dr.ItemArray.GetValue(2).ToString();
        tbLastName.Text = dr.ItemArray.GetValue(3).ToString();
        tbSuffix.Text = dr.ItemArray.GetValue(4).ToString();
        tbHomePhone.Text = dr.ItemArray.GetValue(5).ToString();
        tbCellPhone.Text = dr.ItemArray.GetValue(6).ToString();
        tbOtherPhone.Text = dr.ItemArray.GetValue(7).ToString();
        tbStreetAddress.Text = dr.ItemArray.GetValue(8).ToString();
        tbCityAndState.Text = dr.ItemArray.GetValue(9).ToString();
        tbCountry.Text = dr.ItemArray.GetValue(10).ToString();
        tbEmail.Text = dr.ItemArray.GetValue(11).ToString();
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        string searchFor = tbSearchFor.Text;
        string column;
        if (rbFirstName.Checked)
        {
            column = "firstName";
        }
        else
        {
            column = "lastName";
        }

        DataRow[] rows = dataset.Tables["Contacts"].Select(column + "='" + searchFor + "'");
        int number = rows.Length;

        if (number == 0)
        {
            MessageBox.Show("No such records were found.");
        }
        else if (number > 1)
        {
            string[] strings = new string[rows.Length];
            for (int i = 0; i < strings.Length; i++)
            {
                bool hasFirst = false;
                bool hasMiddle = false;

                strings[i] = "";
                if (rows[i].ItemArray.GetValue(1).ToString() != "")
                {
                    hasFirst = true;
                    strings[i] += rows[i].ItemArray.GetValue(1).ToString();
                }
                if (rows[i].ItemArray.GetValue(2).ToString() != "")
                {
                    hasMiddle = true;
                    if (hasFirst)
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(2).ToString();
                }
                if (rows[i].ItemArray.GetValue(3).ToString() != "")
                {
                    if ((hasFirst && !hasMiddle) || (hasMiddle))
                    {
                        strings[i] += " ";
                    }
                    strings[i] += rows[i].ItemArray.GetValue(3).ToString();
                }
                if (rows[i].ItemArray.GetValue(4).ToString() != "")
                {
                    strings[i] += " " + rows[i].ItemArray.GetValue(4).ToString();
                }
            }

           // int choice;
            Form2 form2 = new Form2(strings);
            if (form2.ShowDialog(this) == DialogResult.OK)
            {
                primaryKey = rows[form2.choice].ItemArray.GetValue(0).ToString();
               // choice = form2.choice;
                fillTextBoxes(rows[form2.choice]);
                currentRow = rows[form2.choice];
                recordShown = true;
            }
        }
        else
        {
            primaryKey = rows[0].ItemArray.GetValue(0).ToString();
            currentRow = rows[0];
            fillTextBoxes(rows[0]);
            recordShown = true;
        }
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        con.Open();

        DataRow row = dataset.Tables["Contacts"].NewRow();
        row[1] = tbFirstName.Text;
        row[2] = tbMiddleName.Text;
        row[3] = tbLastName.Text;
        row[4] = tbSuffix.Text;
        row[5] = tbHomePhone.Text;
        row[6] = tbCellPhone.Text;
        row[7] = tbOtherPhone.Text;
        row[8] = tbStreetAddress.Text;
        row[9] = tbCityAndState.Text;
        row[10] = tbCountry.Text;
        row[11] = tbEmail.Text;
        currentRow = row;

        dataset.Tables["Contacts"].Rows.Add(row);
        dAdapter.Update(dataset, "Contacts");
        recordShown = true;

        con.Close();
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        if (recordShown)
        {
            con.Open();

            currentRow[1] = tbFirstName.Text;
            currentRow[2] = tbMiddleName.Text;
            currentRow[3] = tbLastName.Text;
            currentRow[4] = tbSuffix.Text;
            currentRow[5] = tbHomePhone.Text;
            currentRow[6] = tbCellPhone.Text;
            currentRow[7] = tbOtherPhone.Text;
            currentRow[8] = tbStreetAddress.Text;
            currentRow[9] = tbCityAndState.Text;
            currentRow[10] = tbCountry.Text;
            currentRow[11] = tbEmail.Text;

            dAdapter.Update(dataset, "Contacts");

            con.Close();
        }
        else
        {
            MessageBox.Show("Please locate/add a record first.");
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        con.Open();

        currentRow.Delete();
        dAdapter.Update(dataset, "Contacts");
        clearTextBoxes();
        recordShown = false;

        con.Close();
    }
}
}

Thanks!

Body:
Here is one explanation but I am not sure if it is exactly what you are seeing:

http://blogs.msdn.com/b/spike/archive/2010/04/07/concurrency-violation-the-updatecommand-affected-0-of-the-expected-1-records.aspx

This might be more on track and if so points to some missing lines that should come after you declare cmdBuilder:

dAdapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
dAdapter.InsertCommand = cmdBuilder.GetInsertCommand();
dAdapter.DeleteCommand = cmdBuilder.GetDeleteCommand();

http://www.codeguru.com/forum/archive/index.php/t-337168.html

Also, you might need to call:

dAdapter.Fill(dataset, "Contacts");

before the con.Close() for all three operations (Insert, Update, and Delete).

On an unrelated note, you could reduce duplicate code by changing the "fillTextBoxes(int row)" method to be just:

private void fillTextBoxes(int row)
{
  DataRow dr = dataset.Tables["Contacts"].Rows[row];
  fillTextBoxes(dr);
}


问:
Applying restart, close, and adjustment functions to specific options for JOptionPane
I created a option pane that displays when my game ends. I am using Java swing.

How would I make a function that "quits" the game, another one that "restarts" the game, and one that adjusts a timer speed? Im not sure how to implement with Object[] options array.

```<code>Object[] options = { "Restart Game", "Change Game Difficulty",
                    "Exit Game" };

            int n = JOptionPane.showOptionDialog(gamePanel,
                    "GAME OVER - Your Hit Yourself and Died! ",
                    "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[2]);
</code>```

答:
From the Java Docs for JOptionPane.showOptionDialog(..) (which I suggest you bookmark, and read carefully before asking questions on SO).

Returns:

an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog

Other notes:

```<code>int n = JOptionPane.showOptionDialog(gamePanel,
        "GAME OVER - Your Hit Yourself and Died! ",
        "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
        JOptionPane.WARNING_MESSAGE, null, options, options[2]);
</code>```

JOptionPane.YES_NO_CANCEL_OPTION best to stick with the simpler OK_CANCEL_OPTION.

JOptionPane.WARNING_MESSAGE How is this a warning? Use JOptionPane.QUESTION_MESSAGE instead.

Body:
I created a option pane that displays when my game ends. I am using Java swing.

How would I make a function that "quits" the game, another one that "restarts" the game, and one that adjusts a timer speed? Im not sure how to implement with Object[] options array.

Object[] options = { "Restart Game", "Change Game Difficulty",
                    "Exit Game" };

            int n = JOptionPane.showOptionDialog(gamePanel,
                    "GAME OVER - Your Hit Yourself and Died! ",
                    "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[2]);

Body:
From the Java Docs for JOptionPane.showOptionDialog(..) (which I suggest you bookmark, and read carefully before asking questions on SO).

Returns:

an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog

Other notes:

int n = JOptionPane.showOptionDialog(gamePanel,
        "GAME OVER - Your Hit Yourself and Died! ",
        "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
        JOptionPane.WARNING_MESSAGE, null, options, options[2]);

JOptionPane.YES_NO_CANCEL_OPTION best to stick with the simpler OK_CANCEL_OPTION.

JOptionPane.WARNING_MESSAGE How is this a warning? Use JOptionPane.QUESTION_MESSAGE instead.


问:
When is std::weak_ptr useful?
I started studying smart pointers of C++11 and I don't see any useful use of std::weak_ptr. Can someone tell me when std::weak_ptr is useful/necessary?

答:
When using pointers it's important to understand the different types of pointers available and when it makes sense to use each one. There are four types of pointers in two categories as follows:

Raw pointers:

Raw Pointer [ i.e. SomeClass* ptrToSomeClass = new SomeClass(); ]

Smart pointers:

Unique Pointers [ i.e.
 std::unique_ptr<SomeClass> uniquePtrToSomeClass ( new SomeClass() );
]

Shared Pointers [ i.e.
 std::shared_ptr<SomeClass> sharedPtrToSomeClass ( new SomeClass() );
 ]

Weak Pointers [ i.e.
 std::weak_ptr<SomeClass> weakPtrToSomeWeakOrSharedPtr ( weakOrSharedPtr );
 ]

Raw pointers (sometimes referred to as "legacy pointers", or "C pointers") provide 'bare-bones' pointer behavior and are a common source of bugs and memory leaks. Raw pointers provide no means for keeping track of ownership of the resource and developers must call 'delete' manually to ensure they are not creating a memory leak. This becomes difficult if the resource is shared as it can be challenging to know whether any objects are still pointing to the resource. For these reasons, raw pointers should generally be avoided and only used in performance-critical sections of the code with limited scope.

Unique pointers are a basic smart pointer that 'owns' the underlying raw pointer to the resource and is responsible for calling delete and freeing the allocated memory once the object that 'owns' the unique pointer goes out of scope. The name 'unique' refers to the fact that only one object may 'own' the unique pointer at a given point in time. Ownership may be transferred to another object via the move command, but a unique pointer can never be copied or shared. For these reasons, unique pointers are a good alternative to raw pointers in the case that only one object needs the pointer at a given time, and this alleviates the developer from the need to free memory at the end of the owning object's lifecycle.

Shared pointers are another type of smart pointer that are similar to unique pointers, but allow for many objects to have ownership over the shared pointer. Like unique pointer, shared pointers are responsible for freeing the allocated memory once all objects are done pointing to the resource. It accomplishes this with a technique called reference counting. Each time a new object takes ownership of the shared pointer the reference count is incremented by one. Similarly, when an object goes out of scope or stops pointing to the resource, the reference count is decremented by one. When the reference count reaches zero, the allocated memory is freed. For these reasons, shared pointers are a very powerful type of smart pointer that should be used anytime multiple objects need to point to the same resource.

Finally, weak pointers are another type of smart pointer that, rather than pointing to a resource directly, they point to another pointer (weak or shared). Weak pointers can't access an object directly, but they can tell whether the object still exists or if it has expired. A weak pointer can be temporarily converted to a shared pointer to access the pointed-to object (provided it still exists). To illustrate, consider the following example:

You are busy and have overlapping meetings: Meeting A and Meeting B

You decide to go to Meeting A and your co-worker goes to Meeting B

You tell your co-worker that if Meeting B is still going after Meeting A ends, you will join

The following two scenarios could play out:

Meeting A ends and Meeting B is still going, so you join

Meeting A ends and Meeting B has also ended, so you can't join

In the example, you have a weak pointer to Meeting B. You are not an "owner" in Meeting B so it can end without you, and you do not know whether it ended or not unless you check. If it hasn't ended, you can join and participate, otherwise, you cannot. This is different than having a shared pointer to Meeting B because you would then be an "owner" in both Meeting A and Meeting B (participating in both at the same time).

The example illustrates how a weak pointer works and is useful when an object needs to be an outside observer, but does not want the responsibility of sharing ownership. This is particularly useful in the scenario that two objects need to point to each other (a.k.a. a circular reference). With shared pointers, neither object can be released because they are still 'strongly' pointed to by the other object. When one of the pointers is a weak pointer, the object holding the weak pointer can still access the other object when needed, provided it still exists.

Title: When is std::weak_ptr useful?


问:
Find same element in two array
I am trying to find the same element in two arrays, where the elements must have a maximum distance between them equal to k.

My two arrays (of different size and not sorted) A and B, k max distance.

This is what I have done, but I don't know where there is an error...

for (int i = 0; i<A.length; i++){
    for(int j = i; j < k || j < B.length; j++)
        if(A[i] == B[j]){
            //Print on console
            System.out.println(B[i]);
            j = k;
        }
    }
}
```

<p>For example:</p>

```A[3,7,5,9,10,15,16,1,6,2]
B[4,8,5,13,1,17,2,11]
k=6
```

The output should be 5 1 2, but I don't know why, my program give me only 5 . Can anyone help me understand why?

答:
```<code>def getSameItems(aList, bList):
    a_max = aList[0]
    b_max = bList[0]
    for item in aList:
        if item > a_max: a_max = item
    for item in bList:
        if item > b_max: b_max = item
    aList_counting = [0] * (a_max + 1)
    bList_counting = [0] * (b_max + 1)

    for item in aList: aList_counting[item] += 1
    for item in bList: bList_counting[item] += 1
    min_item = a_max if a_max < b_max else b_max
    sameList = []
    for i in range(min_item + 1):
        if aList_counting[i] > 0 and bList_counting[i] > 0:
            sameList.append(i)
    return sameList
aList = [1, 7, 2, 2, 8]
bList = [1, 2, 3, 7, 7, 9, 2, 8]
print getSameItems(aList, bList)
[1, 2, 7, 8]
</code>```

The above code is used in the python language,I am Chinese,so my english is poor，and cannot provide rich code annotations,sorry..I suggest that you can use counting sorting ideas,I hope it will help you!

Title: Find same element in two array

Body:
I am trying to find the same element in two arrays, where the elements must have a maximum distance between them equal to k.

My two arrays (of different size and not sorted) A and B, k max distance.

This is what I have done, but I don't know where there is an error...

for (int i = 0; i<A.length; i++){
    for(int j = i; j < k || j < B.length; j++)
        if(A[i] == B[j]){
            //Print on console
            System.out.println(B[i]);
            j = k;
        }
    }
}

For example:

A[3,7,5,9,10,15,16,1,6,2]
B[4,8,5,13,1,17,2,11]
k=6

The output should be 5 1 2, but I don't know why, my program give me only 5 . Can anyone help me understand why?

Body:
def getSameItems(aList, bList):
    a_max = aList[0]
    b_max = bList[0]
    for item in aList:
        if item > a_max: a_max = item
    for item in bList:
        if item > b_max: b_max = item
    aList_counting = [0] * (a_max + 1)
    bList_counting = [0] * (b_max + 1)

    for item in aList: aList_counting[item] += 1
    for item in bList: bList_counting[item] += 1
    min_item = a_max if a_max < b_max else b_max
    sameList = []
    for i in range(min_item + 1):
        if aList_counting[i] > 0 and bList_counting[i] > 0:
            sameList.append(i)
    return sameList
aList = [1, 7, 2, 2, 8]
bList = [1, 2, 3, 7, 7, 9, 2, 8]
print getSameItems(aList, bList)
[1, 2, 7, 8]

The above code is used in the python language,I am Chinese,so my english is poor，and cannot provide rich code annotations,sorry..I suggest that you can use counting sorting ideas,I hope it will help you!


问:
the output of the array in turn in panel to labels C#
I faced with the problem. I have a panel with 20 labels. The function generator() assign each label the number of the array. Each number scrolls from 1 to needed number. But the problem is that the number is assigned out of order. For example first number assign to 1 label and the next number to 10 label, the next to 2 and the next to 11 etc.

But I need to output the numbers in rtl or ltr order.

I dont know how to fix it. Help, please.

```<code>public void generator() // присваивание текстбоксам значений
    {
        generatedArray = getUniqueRandomArray(1, 81, 20).ToArray();

       for (int i = 0; i < panel1.Controls.Count; i++)
        {
            for (int j = 1; j < generatedArray[i] + 1; j++)
            {
                panel1.Controls[i].Text = j.ToString();
                Thread.Sleep(50);
                panel1.Controls[i].Refresh();
            }
        }
    }
</code>```

I would be grateful for help :)

答:
To accomplish this, you could use some controls of your own, so that you can better define their behaviour (and do it in batch).

A custom class which derives from Label:

```<code>List<MyLabel> MyLabels = new List<MyLabel>();

public class MyLabel : Label
{
   public MyLabel()
   {
      //Define some default properties
      this.TextAlign = ContentAlignment.MiddleCenter;
      this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
      this.Font = new Font("Calibri", 9f, FontStyle.Regular);
      this.BackColor = Color.White;
      this.ForeColor = Color.Black;
      this.Size = new Size(50, 20);
   }
}
</code>```

Insert an array of custom labels inside a panel (this could be a custom control too).

```<code> int LeftMargin = 20;
 int TopMargin = 20;
 int NumberOfLabels = 20;
 int LabelsPerRow = 5;
 int LabelsDistance = 10;
 int _idx = 0;

for (int y = 0; y < (NumberOfLabels / LabelsPerRow); y++)
{
   for (int x = 0; x < LabelsPerRow; x++)
   {
      MyLabels.Add(new MyLabel() { Parent = this.panel1 });
      MyLabels[_idx].Location = new Point((LeftMargin + ((MyLabels[_idx].Width + LabelsDistance) * x)),
                                          (TopMargin + ((MyLabels[_idx].Height + LabelsDistance) * y)));
      _idx++;
   }
}
</code>```

This is the result:

if you simply change these fields:

```<code> int LeftMargin = 1;
 int TopMargin = 1;
 int NumberOfLabels = 20;
 int LabelsPerRow = 20;
 int LabelsDistance = 1;
</code>```

you get this:

Then, call your generator() method to fill the UI:

```<code>generator();

public async void generator()
{
   generatedArray = getUniqueRandomArray(1, 81, 20).ToArray();
   for (int i = 0; i < MyLabels.Count; i++)
   {
      for (int j = 1; j < generatedArray[i] + 1; j++)
      {
         await Task.Run(async () => await Task.Delay(500));

         //Set the text property of the custom labels. The order will be respected
         MyLabels[i].Text = j.ToString();
      }
}
</code>```

You could also set the labels text property through the Panel.Controls[] array.

```<code>this.panel1.Controls[i].Text = j.ToString();
</code>```

The order would be respected as well, but if the parent form closes, it causes an ArgumentOutOfRange Exception.

Body:
I faced with the problem. I have a panel with 20 labels. The function generator() assign each label the number of the array. Each number scrolls from 1 to needed number. But the problem is that the number is assigned out of order. For example first number assign to 1 label and the next number to 10 label, the next to 2 and the next to 11 etc.

But I need to output the numbers in rtl or ltr order.

I dont know how to fix it. Help, please.

public void generator() // присваивание текстбоксам значений
    {
        generatedArray = getUniqueRandomArray(1, 81, 20).ToArray();

       for (int i = 0; i < panel1.Controls.Count; i++)
        {
            for (int j = 1; j < generatedArray[i] + 1; j++)
            {
                panel1.Controls[i].Text = j.ToString();
                Thread.Sleep(50);
                panel1.Controls[i].Refresh();
            }
        }
    }

I would be grateful for help :)

Body:
To accomplish this, you could use some controls of your own, so that you can better define their behaviour (and do it in batch).

A custom class which derives from Label:

List<MyLabel> MyLabels = new List<MyLabel>();

public class MyLabel : Label
{
   public MyLabel()
   {
      //Define some default properties
      this.TextAlign = ContentAlignment.MiddleCenter;
      this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
      this.Font = new Font("Calibri", 9f, FontStyle.Regular);
      this.BackColor = Color.White;
      this.ForeColor = Color.Black;
      this.Size = new Size(50, 20);
   }
}

Insert an array of custom labels inside a panel (this could be a custom control too).

 int LeftMargin = 20;
 int TopMargin = 20;
 int NumberOfLabels = 20;
 int LabelsPerRow = 5;
 int LabelsDistance = 10;
 int _idx = 0;

for (int y = 0; y < (NumberOfLabels / LabelsPerRow); y++)
{
   for (int x = 0; x < LabelsPerRow; x++)
   {
      MyLabels.Add(new MyLabel() { Parent = this.panel1 });
      MyLabels[_idx].Location = new Point((LeftMargin + ((MyLabels[_idx].Width + LabelsDistance) * x)),
                                          (TopMargin + ((MyLabels[_idx].Height + LabelsDistance) * y)));
      _idx++;
   }
}

This is the result:

if you simply change these fields:

 int LeftMargin = 1;
 int TopMargin = 1;
 int NumberOfLabels = 20;
 int LabelsPerRow = 20;
 int LabelsDistance = 1;

you get this:

Then, call your generator() method to fill the UI:

generator();

public async void generator()
{
   generatedArray = getUniqueRandomArray(1, 81, 20).ToArray();
   for (int i = 0; i < MyLabels.Count; i++)
   {
      for (int j = 1; j < generatedArray[i] + 1; j++)
      {
         await Task.Run(async () => await Task.Delay(500));

         //Set the text property of the custom labels. The order will be respected
         MyLabels[i].Text = j.ToString();
      }
}

You could also set the labels text property through the Panel.Controls[] array.

this.panel1.Controls[i].Text = j.ToString();

The order would be respected as well, but if the parent form closes, it causes an ArgumentOutOfRange Exception.


问:
gcc -fprofile-arcs: how to output a file on custom RTOS
gcc has a bunch of options  you can use for runtime analysis that produce output during the execution of your program.

For example: gcc -fprofile-arcs

Add code so that program flow arcs are instrumented. During execution
  the program records how many times each branch and call is executed
  and how many times it is taken or returns. On targets that support
  constructors with priority support, profiling properly handles
  constructors, destructors and C++ constructors (and destructors) of
  classes which are used as a type of a global variable.

When the compiled program exits it saves this data to a file called
  auxname.gcda for each source file. The data may be used for
  profile-directed optimizations (-fbranch-probabilities), or for test
  coverage analysis (-ftest-coverage). Each object file’s auxname is
  generated from the name of the output file, if explicitly specified
  and it is not the final executable, otherwise it is the basename of
  the source file. In both cases any suffix is removed (e.g. foo.gcda
  for input file dir/foo.c, or dir/foo.gcda for output file specified as
  -o dir/foo.o).

I am running a custom C++ RTOS that does not have a filesystem so the program cannot, as the bolded words state, "save" the data using the same mechanism as on Linux/Windows/QNX.

QUESTION

How, if possible, could I make use of -fprofile-arcs (or any of the other runtime profiling options that produce a file) on my custom RTOS with no filesystem?

Is it possible to redirect the info by providing a "writer" class? If so, I could stream the data to the PC using whatever interface I have available like JTAG.

Speaking of the debugger, is it possible to use gdb and the JTAG connection to somehow solve this problem?

答:
I had to do something similar once - I was after code coverage. Luckily I was able to get my hands on a VectorCast license, which can instrument the source before compilation and do the bookkeeping in memory. Can't remember how closely I looked at  providing stubs for the instrumented gcc code.

If your focus is profiling in an RTOS embedded environment, you could have a periodic record the program counter and run long enough to collect meaningful data.


答:
You can directly pass the date ,
first create date object and then pass it  date_format
For eg:

```<code>$date = date_create($row['returndate']);
echo "<td>" . date_format($date,'M d, y') . "</td>";
</code>```

Output

```<code>Dec 07, 17
</code>```

Body:
I am pulling a date from a database and it is in the format 2017-12-07.  That is how I was displaying the date, however, I would like to display is like Dec 7, 17.

What I tried.

echo "" . date_format($row['returndate'],'M d, y') . "	";

My results end up empty.  I have successfully changed the date format with in the MYSQLI line, however, I was wanting to do it with PHP.

UPDATE

I apologize, it seems I over looked something simple.  Below fixed it.

date('M d, y', strtotime($row['returndate']))

I guess you have to do strtotime before date.

Body:
You can directly pass the date ,
first create date object and then pass it  date_format
For eg:

$date = date_create($row['returndate']);
echo "<td>" . date_format($date,'M d, y') . "</td>";

Output

Dec 07, 17