问:
ARKit : Handle tap to show / hide a node
I am new to ARKit , and i am trying an example to create a SCNBox on tap location. What i am trying to do is on initial touch i create a box and on the second tap on the created box it should be removed from the scene. I am doing the hit test. but it keeps on adding the box. I know this is a simple task, but i am unable to do it</p>

```<code>    @objc func handleTap(sender: UITapGestureRecognizer) {

    print("hande  tapp")
    guard let _ = sceneView.session.currentFrame
        else { return }

    guard let scnView = sceneView else { return }
    let touchLocation = sender.location(in: scnView)
    let hitTestResult = scnView.hitTest(touchLocation, types: [ .featurePoint])

    guard let pointOfView = sceneView.pointOfView else {return}
    print("point   \(pointOfView.name)")

    if hitTestResult.count > 0 {

        print("Hit")

        if let _ = pointOfView as? ARBox {

            print("Box Available")
        }

        else {

            print("Adding box")

            let transform = hitTestResult.first?.worldTransform.columns.3
            let xPosition = transform?.x
            let yPosition = transform?.y
            let zPosition = transform?.z
            let position = SCNVector3(xPosition!,yPosition!,zPosition!)

            basketCount = basketCount + 1
            let newBasket = ARBox(position: position)
            newBasket.name = "basket\(basketCount)"
            self.sceneView.scene.rootNode.addChildNode(newBasket)
            boxNodes.append(newBasket)

        }
    }
}
</code>```

答:
pointOfView of a sceneView, is the rootnode of your scene, which is one used to render your whole scene. For generic cases, it usually is an empty node with lights/ camera. I don't think you should cast it as ARBox/ or any type of SCNNode(s) for that matter.

What you probably can try is the logic below (hitResults are the results of your hitTest):

```<code>if hitResults.count > 0 {
    if let node = hitResults.first?.node as SCNNode? (or ARBox) {
    // node.removeFromParentNode()
    // or make the node opaque if you don't want to remove
else {
    // add node.
</code>```

Body:
I am new to ARKit , and i am trying an example to create a SCNBox on tap location. What i am trying to do is on initial touch i create a box and on the second tap on the created box it should be removed from the scene. I am doing the hit test. but it keeps on adding the box. I know this is a simple task, but i am unable to do it

    @objc func handleTap(sender: UITapGestureRecognizer) {

    print("hande  tapp")
    guard let _ = sceneView.session.currentFrame
        else { return }

    guard let scnView = sceneView else { return }
    let touchLocation = sender.location(in: scnView)
    let hitTestResult = scnView.hitTest(touchLocation, types: [ .featurePoint])

    guard let pointOfView = sceneView.pointOfView else {return}
    print("point   \(pointOfView.name)")

    if hitTestResult.count > 0 {

        print("Hit")

        if let _ = pointOfView as? ARBox {

            print("Box Available")
        }

        else {

            print("Adding box")

            let transform = hitTestResult.first?.worldTransform.columns.3
            let xPosition = transform?.x
            let yPosition = transform?.y
            let zPosition = transform?.z
            let position = SCNVector3(xPosition!,yPosition!,zPosition!)

            basketCount = basketCount + 1
            let newBasket = ARBox(position: position)
            newBasket.name = "basket\(basketCount)"
            self.sceneView.scene.rootNode.addChildNode(newBasket)
            boxNodes.append(newBasket)

        }
    }
}

Body:
pointOfView of a sceneView, is the rootnode of your scene, which is one used to render your whole scene. For generic cases, it usually is an empty node with lights/ camera. I don't think you should cast it as ARBox/ or any type of SCNNode(s) for that matter.

What you probably can try is the logic below (hitResults are the results of your hitTest):

if hitResults.count > 0 {
    if let node = hitResults.first?.node as SCNNode? (or ARBox) {
    // node.removeFromParentNode()
    // or make the node opaque if you don't want to remove
else {
    // add node.


来源: stackexchange

问:
Gigya - complete registration for an auto-generated account
Newbie to gigya. I have been trying to identify how can I achieve complete registration in my web application for an account that is generated using gigya REST api with an auto-generated details. I have the UID for that account, using which I can retrieve the user details.

My questions are:

Is it possible to complete the registration for that account(auto-generated) using the Complete Registration screen set?

If so, how can I achieve the profile completion?

答:
@sadiqmc could you explain a little bit about what you're trying to do? What's the flow that you're trying to accomplish?

Edit:
As per your flow, you probably shouldn't use the Update Profile screen to let the user change their info, as the auto-generated content will be pre populated and will confuse the user.

Since you already have the UID, you can build a generic form to collect the user's data and then update the account using setAccountInfo.

ContentLicense: CC BY-SA 3.0


问:
Flat File to SOAP XML
I have never worked with XML and SOAP envelopes. I am trying to write a generic algorithm to read a flat file and to write the details into a SOAP like XML file. I was thinking of the following approach but want to know if there would be a better approach to do it.

Create a file containing the sample XML envelope with variables instead of the actual values

Create a properties file which contains a mapping between the variables and the index of the column (containing value for this variable) in the flat file.

Read the Flat file line by line in Java Code. Convert the line to an ArrayList based on the columns in the line

For each line, I read the sample XML envelope as defined in Step 1 above. I replace the variables in the XML string with the values from the arraylist based on the associated variable index.

Write the XML to a file.

I can write the xml file by javax.xml.soap.MessageFactory but that would make the mapping complex and would probably take more time to execute.

Any suggestions on the right approach to achieve this?

答:
Proper approach is to use available/standard frameworks (i.e. JAXB or others). Depends on what is a purpose of your SOAP XML:

If it is to use in WebService - create a WSDL (to be used by Webservice framework like CXF)

Then create corresponding Java classes.
You have two options:

Up-down (easier way): create XSD schema(s) for your XML, then generate your Java classes with JAXB it is xjc compiler and bunch of tools or maven plugins to run it. like wsdl2java, wsimport and so, and so... (if WSDL is in use) or JAXB maven plugins to generate Java classes out of XSD dierxtly

down-up: Create Java classes and annotate them with proper JAXB annotations

That's it. You will set appropriate properties in Java classes.

Again, if it is about webservice webservice implementation (i.e. CXF) will do the rest to get actual SOAP. If you need just an XML (like a file), then you can marshal Java classes to XML by JAXBContext.

It may sound like a long way, but from code prospective it is not complex. Biggest point is to make Java classes properly (and with top-down approach it is only about make proper XSD (and WSDL if needed).

Title: Flat File to SOAP XML


问:
ERROR TypeError: Cannot read property 'toLowerCase' of undefined. Ionic 3
I'm trying to filter data from firebase database by using angular.But it keep get error like this-ERROR TypeError: Cannot read property 'toLowerCase' of undefined.Can someone help me?Below are my function in search.ts

```<code>searchuser(searchbar) {

this.filteredusers = this.temparr;
var q = searchbar.target.value;

if (q.trim() == '') {
  return;
}

this.filteredusers = this.filteredusers.filter((v) => {
  if (v.displayName.toLowerCase().indexOf(q.toLowerCase()) > -1 || v.subject.toLowerCase().indexOf(q.toLowerCase()) > -1) {
    return true;
  }

  return false;
})}
</code>```

Below are my html code

```<code><ion-content padding>
    <ion-searchbar [(ngModel)]="searchstring" (input)="searchuser($event)" placeholder="Search"></ion-searchbar>
    <ion-list no-lines>
      <ion-list>
        <ion-item-sliding *ngFor="let key of filteredusers" >
          <ion-item >
            <ion-avatar item-left>
              <img src="{{key.photoURL}}">
            </ion-avatar>
            <h2>{{key.displayName}} </h2>
            <p>Rate/Hour:RM{{key.rate}}</p>
            <p>Subject:{{key.subject}}</p>
            <p>Distance:0.5KM</p>

          </ion-item>

          <ion-item-options slide="left">
            <button ion-button color="primary" (click)="call(key)">
              <ion-icon name="call"></ion-icon>
              Call
            </button>
          </ion-item-options>

        </ion-item-sliding>
      </ion-list>
    </ion-list>

</ion-content>
</code>```

My expect result of the filtered is the search function can filtered name and subject from the database.

答:
Update your condition checking to:

```<code>if (v.displayName && v.displayName.toLowerCase()...
</code>```

You typically get that error if you try to call a method (in this case toLowerCase) or access a property on a null or undefined object. That's essentially Javascript's version of null reference exception.

By checking v.displayName you ensure that the property displayName exists on your object v and its value not undefined or null.

If it's possible that the displayName property may be of any type other than string, then you might also benefit from type-checking your property before invoking toLowerCase on it. You can type-check using typeof v.displayName === "string". So, a more complete check would be:

```<code>if (v.displayName && typeof v.displayName === "string" && v.displayName.toLowerCase()...
</code>```

Body:
I'm trying to filter data from firebase database by using angular.But it keep get error like this-ERROR TypeError: Cannot read property 'toLowerCase' of undefined.Can someone help me?Below are my function in search.ts

searchuser(searchbar) {

this.filteredusers = this.temparr;
var q = searchbar.target.value;

if (q.trim() == '') {
  return;
}

this.filteredusers = this.filteredusers.filter((v) => {
  if (v.displayName.toLowerCase().indexOf(q.toLowerCase()) > -1 || v.subject.toLowerCase().indexOf(q.toLowerCase()) > -1) {
    return true;
  }

  return false;
})}

Below are my html code

<ion-content padding>
    <ion-searchbar [(ngModel)]="searchstring" (input)="searchuser($event)" placeholder="Search"></ion-searchbar>
    <ion-list no-lines>
      <ion-list>
        <ion-item-sliding *ngFor="let key of filteredusers" >
          <ion-item >
            <ion-avatar item-left>

            </ion-avatar>

{{key.displayName}}

Rate/Hour:RM{{key.rate}}

Subject:{{key.subject}}

Distance:0.5KM

          </ion-item>

          <ion-item-options slide="left">
            <button ion-button color="primary" (click)="call(key)">
              <ion-icon name="call"></ion-icon>
              Call
            </button>
          </ion-item-options>

        </ion-item-sliding>
      </ion-list>
    </ion-list>

</ion-content>

My expect result of the filtered is the search function can filtered name and subject from the database.

Body:
Update your condition checking to:

if (v.displayName && v.displayName.toLowerCase()...

You typically get that error if you try to call a method (in this case toLowerCase) or access a property on a null or undefined object. That's essentially Javascript's version of null reference exception.

By checking v.displayName you ensure that the property displayName exists on your object v and its value not undefined or null.

If it's possible that the displayName property may be of any type other than string, then you might also benefit from type-checking your property before invoking toLowerCase on it. You can type-check using typeof v.displayName === "string". So, a more complete check would be:

if (v.displayName && typeof v.displayName === "string" && v.displayName.toLowerCase()...


问:
How do I turn django's settings object into a dict?
What I have:

```<code>from django.conf import settings

def settings_to_dict(settings)
    cfg = {
        'BOTO3_ACCESS_KEY': settings.BOTO3_ACCESS_KEY,
        'BOTO3_SECRET_KEY': settings.BOTO3_SECRET_KEY,
        # repeat ad nauseum
    }
    return cfg

instance = SomeClassInstantiatedWithADict(**settings_to_dict(settings))
</code>```

What I'd like (using Django 1.11):

```<code>from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.to_dict())
</code>```

I've tried:

```<code>from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.__dict__)
</code>```

which is close, but __dict__ only gets a small subset of the settings, which I assume are hard coded ones as opposed to added attributes. Thanks for any help!

答:
Use the following code:

```<code>from django.conf import settings
instance = settings.__dict__['_wrapped'].__dict__
</code>```

Then you will have the whole settings dict in instance as dictionary.

Body:
What I have:

from django.conf import settings

def settings_to_dict(settings)
    cfg = {
        'BOTO3_ACCESS_KEY': settings.BOTO3_ACCESS_KEY,
        'BOTO3_SECRET_KEY': settings.BOTO3_SECRET_KEY,
        # repeat ad nauseum
    }
    return cfg

instance = SomeClassInstantiatedWithADict(**settings_to_dict(settings))

What I'd like (using Django 1.11):

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.to_dict())

I've tried:

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.__dict__)

which is close, but __dict__ only gets a small subset of the settings, which I assume are hard coded ones as opposed to added attributes. Thanks for any help!

Body:
Use the following code:

from django.conf import settings
instance = settings.__dict__['_wrapped'].__dict__

Then you will have the whole settings dict in instance as dictionary.


问:
How can we deploy a django app onn google cloud?
I am having trouble deploying a developed django app on google console.
Firstly it renames all the files of the app to some random name. Also when I try to hit the website .appspot.com I get an internal error.

Have created app.yaml file:

```<code># [START runtime]
runtime: python27
entrypoint: gunicorn -b :$PORT mysite.wsgi
threadsafe: true
# [END runtime]

handlers:
- url: /static
  static_dir: website/static

- url: /.*
  script: main.application

libraries:

- name: django
  version: 1.11
</code>```

Also have created appengine_cofig.py file:

```<code># Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START vendor]
from google.appengine.ext import vendor

vendor.add('lib')
# [END vendor]
</code>```

Thanks for the help in advance....

答:
As a complete beginner, I'll suggest following the google documentation here (https://cloud.google.com/python/django/appengine) step by step taking note that:

Django default database is sqlite3, you will have to change it to mysql and it is recommended that you do this at the very beggining of creating your  Django app. I recommend following instructions in this youtube video (https://www.youtube.com/watch?v=s16p32pndK0)

Your app.yaml file should look as so;

runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /static
  static_dir: static/
  application_readable: True
- url: .*
  script: yourapplication.wsgi.application

# Only pure Python libraries can be vendored
# Python libraries that use C extensions can
# only be included if they are part of the App Engine SDK
# Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27
libraries:
- name: MySQLdb
  version: 1.2.5
- name: django
  version: "1.11"
- name: ssl
  version: latest
# [END django_app]

# Google App Engine limits application deployments to 10,000 uploaded files per
# version. The skip_files section allows us to skip virtual environment files
# to meet this requirement. The first 5 are the default regular expressions to
# skip, while the last one is for all env/ files.
skip_files:
- ^(.*/)?#.*#$
- ^(.*/)?.*~$
- ^(.*/)?.*\.py[co]$
- ^(.*/)?.*/RCS/.*$
- ^(.*/)?\..*$
- ^env/.*$```

I am also a beginner and I have just managed to deploy my app to GAE, all the best.

Body:
I am having trouble deploying a developed django app on google console.
Firstly it renames all the files of the app to some random name. Also when I try to hit the website .appspot.com I get an internal error.

Have created app.yaml file:

# [START runtime]
runtime: python27
entrypoint: gunicorn -b :$PORT mysite.wsgi
threadsafe: true
# [END runtime]

handlers:
- url: /static
  static_dir: website/static

- url: /.*
  script: main.application

libraries:

- name: django
  version: 1.11

Also have created appengine_cofig.py file:

# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START vendor]
from google.appengine.ext import vendor

vendor.add('lib')
# [END vendor]

Thanks for the help in advance....

Body:
As a complete beginner, I'll suggest following the google documentation here (https://cloud.google.com/python/django/appengine) step by step taking note that:

Django default database is sqlite3, you will have to change it to mysql and it is recommended that you do this at the very beggining of creating your  Django app. I recommend following instructions in this youtube video (https://www.youtube.com/watch?v=s16p32pndK0)

Your app.yaml file should look as so;

runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /static
  static_dir: static/
  application_readable: True
- url: .*
  script: yourapplication.wsgi.application

# Only pure Python libraries can be vendored
# Python libraries that use C extensions can
# only be included if they are part of the App Engine SDK
# Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27
libraries:
- name: MySQLdb
  version: 1.2.5
- name: django
  version: "1.11"
- name: ssl
  version: latest
# [END django_app]

# Google App Engine limits application deployments to 10,000 uploaded files per
# version. The skip_files section allows us to skip virtual environment files
# to meet this requirement. The first 5 are the default regular expressions to
# skip, while the last one is for all env/ files.
skip_files:
- ^(.*/)?#.*#$
- ^(.*/)?.*~$
- ^(.*/)?.*\.py[co]$
- ^(.*/)?.*/RCS/.*$
- ^(.*/)?\..*$
- ^env/.*$

I am also a beginner and I have just managed to deploy my app to GAE, all the best.


问:
Show only the first letters, three dots and the last N letter of a span
If I've a very long text like this (for example in a table):

```<code><p class='line'>
    <span class='fixed1'>FIXED</span>
    <span class='long_text'>This is my very very very very long text</span>
    <span class='fixed2'>FIXED</span>
</p>
</code>```

By default the
 width is 100% and if the text is longer than the screen it's showed on multi lines. Instead I want it in a single line where only the last N letter are showed.

Here some example:

Screen large enough:

```<code>FIXED This is my very very very very long text FIXED
</code>```

Screen not enough large, text overflow.

```<code>FIXED This is my ve... text FIXED
</code>```

I can obtain something similar using:

```<code>span.long_text {
    overflow: hidden;
    text-overflow: ellipsis;
}
</code>```

Is it possible to obtain the effect I described? How?

答:
You can use white-space: nowrap to force it to stay in a single line.

text-overflow: ellipsis will replace the end of your content with '...' when overflow occurs. However span must be a block for text-overflow to work, so set its display property to inline-block or block.

Demo: https://jsfiddle.net/1bmdu5xd/

Body:
If I've a very long text like this (for example in a table):

    FIXED
    This is my very very very very long text
    FIXED

By default the
 width is 100% and if the text is longer than the screen it's showed on multi lines. Instead I want it in a single line where only the last N letter are showed.

Here some example:

Screen large enough:

FIXED This is my very very very very long text FIXED

Screen not enough large, text overflow.

FIXED This is my ve... text FIXED

I can obtain something similar using:

span.long_text {
    overflow: hidden;
    text-overflow: ellipsis;
}

Is it possible to obtain the effect I described? How?


问:
Python (Raspberry Pi 3) - Function call won't work inside if-statement
I am having a bit of an odd problem. I am currently creating a system using a Raspberry Pi 3. The goal is to have a program that continues running indefinitely, looping through the same set of conditions over and over.

To do this, I am putting code from pyaudio into a function which I am later calling inside an if statement within a while loop.

Here is the code:

```<code>    print ("System ON")

def recordCASCON():
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    RECORD_SECONDS = 60
    WAVE_OUTPUT_FILENAME = "cascon.wav"

    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print("* recording")

    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
        print(i)

    print("* done recording")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

while True:

    if GPIO.input(LedPin4) == GPIO.HIGH and GPIO.input(LedPin5) == GPIO.HIGH:
        print("initiating")
        recordCASCON()
</code>```

I also want to note the following. The function works perfectly fine when called by itself. It also works fine when called within the while loop. Is ONLY when called within the if statement that I get the following in the shell:

```<code>System ON
initiating
* recording
</code>```

As you can see from my code, the function runs for 60 seconds and prints the i index in the for loop. When the function works it runs a series of numbers for 60 seconds then I finally get the "done recording". In this case I could leave it for hours and is still stuck.
If I add a "break" at the end of the if statement all it does is the following:

```<code>System ON
initiating
* recording
0
</code>```

It gets stock on 0 instead of recording.

Any suggestions or help?
Thank you!

答: It seems like you're coding for a hardware like micro controller or so, have you checked whether your conditional statement won't mess you audio device? for example activation of condition happening at a time means the voice module have some pins messed up or so?</p>

Body:
I am having a bit of an odd problem. I am currently creating a system using a Raspberry Pi 3. The goal is to have a program that continues running indefinitely, looping through the same set of conditions over and over.

To do this, I am putting code from pyaudio into a function which I am later calling inside an if statement within a while loop.

Here is the code:

    print ("System ON")

def recordCASCON():
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    RECORD_SECONDS = 60
    WAVE_OUTPUT_FILENAME = "cascon.wav"

    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print("* recording")

    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
        print(i)

    print("* done recording")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

while True:

    if GPIO.input(LedPin4) == GPIO.HIGH and GPIO.input(LedPin5) == GPIO.HIGH:
        print("initiating")
        recordCASCON()

I also want to note the following. The function works perfectly fine when called by itself. It also works fine when called within the while loop. Is ONLY when called within the if statement that I get the following in the shell:

System ON
initiating
* recording

As you can see from my code, the function runs for 60 seconds and prints the i index in the for loop. When the function works it runs a series of numbers for 60 seconds then I finally get the "done recording". In this case I could leave it for hours and is still stuck.
If I add a "break" at the end of the if statement all it does is the following:

System ON
initiating
* recording
0

It gets stock on 0 instead of recording.

Any suggestions or help?
Thank you!


问:
List Items not changing on hover
Using Bootstrap 4, I'm having difficulty targetting the list items on hover. I'm trying to have a default color of the text to a gray, but on hover, make the text a regular black, and on active, have the text white, bolded, with a background color for the different states of the list items.

Here's what it looks like now:

Here is my HTML:

```<code><div class="container mt-5">
  <div class="row">
    <div class="col-sm-4">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">
            <img src="resources/icons/icon-monster/iconmonstr-gear-11-48.png" alt="" class="mr-2">
            Account Settings
          </h4>
        </div>
        <div class="card-body">
          <ul class="list-group list-group-flush">
            <li class="list-group-item active">About You</li>
            <li class="list-group-item">Education and background</li>
            <li class="list-group-item">Professional Development</li>
            <li class="list-group-item">Password</li>
            <li class="list-group-item">Email/Notifications</li>
            <li class="list-group-item">Reviews</li>
            <li class="list-group-item">Privacy Settings</li>
          </ul>
        </div>
      </div>
    </div><!--end of col-sm-4-->
</code>```

Here is my CSS:

```<code>/*----------------------------------------*/
/*--------SIDEBAR ACCOUNT SETTINGS---------*/
/*-----------------------------------------*/

.list-group-item.active {
  background-color: #328cc1;
  border-color: #328cc1;
  font-weight: bold;
  color: #fff;
}

.list-group-item {
  color: gray;
}

.list-group-item: hover {
  color: black;
}
</code>```

Everything works great except the list item isn't capturing the change on hover. I've tried targetting it by ul li .list-group-item: hover and that doesn't work either.

答:
There's a space between : and hover. That was the problem with it.

.list-group-item.active {
  background-color: #328cc1;
  border-color: #328cc1;
  font-weight: bold;
  color: #fff;
}

.list-group-item {
  color: gray;
}

.list-group-item:hover {
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container mt-5">
  <div class="row">
    <div class="col-sm-4">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">
            <img src="resources/icons/icon-monster/iconmonstr-gear-11-48.png" alt="" class="mr-2"> Account Settings
          </h4>
        </div>
        <div class="card-body">
          <ul class="list-group list-group-flush">
            <li class="list-group-item active">About You</li>
            <li class="list-group-item">Education and background</li>
            <li class="list-group-item">Professional Development</li>
            <li class="list-group-item">Password</li>
            <li class="list-group-item">Email/Notifications</li>
            <li class="list-group-item">Reviews</li>
            <li class="list-group-item">Privacy Settings</li>
          </ul>
        </div>
      </div>
    </div>
    <!--end of col-sm-4--></code>```

Title: List Items not changing on hover

Body:
Using Bootstrap 4, I'm having difficulty targetting the list items on hover. I'm trying to have a default color of the text to a gray, but on hover, make the text a regular black, and on active, have the text white, bolded, with a background color for the different states of the list items.

Here's what it looks like now:

Here is my HTML:

            Account Settings

About You

Education and background

Professional Development

Password

Email/Notifications

Reviews

Privacy Settings

Here is my CSS:

/*----------------------------------------*/
/*--------SIDEBAR ACCOUNT SETTINGS---------*/
/*-----------------------------------------*/

.list-group-item.active {
  background-color: #328cc1;
  border-color: #328cc1;
  font-weight: bold;
  color: #fff;
}

.list-group-item {
  color: gray;
}

.list-group-item: hover {
  color: black;
}

Everything works great except the list item isn't capturing the change on hover. I've tried targetting it by ul li .list-group-item: hover and that doesn't work either.

Body:
There's a space between : and hover. That was the problem with it.

.list-group-item.active {
  background-color: #328cc1;
  border-color: #328cc1;
  font-weight: bold;
  color: #fff;
}

.list-group-item {
  color: gray;
}

.list-group-item:hover {
  color: black;
}

<div class="container mt-5">
  <div class="row">
    <div class="col-sm-4">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">
            <img src="resources/icons/icon-monster/iconmonstr-gear-11-48.png" alt="" class="mr-2"> Account Settings
          </h4>
        </div>
        <div class="card-body">
          <ul class="list-group list-group-flush">
            <li class="list-group-item active">About You</li>
            <li class="list-group-item">Education and background</li>
            <li class="list-group-item">Professional Development</li>
            <li class="list-group-item">Password</li>
            <li class="list-group-item">Email/Notifications</li>
            <li class="list-group-item">Reviews</li>
            <li class="list-group-item">Privacy Settings</li>
          </ul>
        </div>
      </div>
    </div>
    <!--end of col-sm-4-->


问:
Convert number to string php with text
Is there a way to convert a number to a string with text at certain points?

Example:

700 would be 7 minutes 00 seconds

60 would be 60 seconds

140 would be1 minute 40 seconds

so the 3rd number would add minutes and at the beginning of the number would always be seconds

I have tried number_format($score, 2, "minutes ") and other variations but it seems to not work as I need since 7000 would be 70 minutes and 00 seconds and so on.

答:
Yes, use substr

```<code>function minuteAndSeconds($string) {
    switch (strlen($string)) {
      case 1:
        return '0' . $string . ' seconds';

     case 2:
       return $string . ' seconds';

     case 3:
       return substr($string, 0, 1) . ' minutes ' . substr($string, 1) . ' seconds';

     default:
       return 'Invalid string format';
  }
}
</code>```

the function accepts a string and returns that string formatted in the way you asked.

You have to cast number to string. (eg. $variable = (string) $variable)

Title: Convert number to string php with text

Body:
Yes, use substr

function minuteAndSeconds($string) {
    switch (strlen($string)) {
      case 1:
        return '0' . $string . ' seconds';

     case 2:
       return $string . ' seconds';

     case 3:
       return substr($string, 0, 1) . ' minutes ' . substr($string, 1) . ' seconds';

     default:
       return 'Invalid string format';
  }
}

the function accepts a string and returns that string formatted in the way you asked.

You have to cast number to string. (eg. $variable = (string) $variable)


问:
How can I use a Dictionary parameter with Swagger UI?
I'm looking to use Swashbuckle to generate Swagger docs and Swagger UI for a Web API method that looks like the following (it's effectively a mail-merge with PDFs):

```<code>    [HttpPost]
    [ResponseType(typeof(byte[]))]
    public HttpResponseMessage MergeValues([FromUri]Dictionary<string, string> mergeValues,
                                           [FromBody]byte[] pdfTemplate)
    {
        return MergeStuff();
    }
</code>```

This isn't currently working, or at least I'm not sure how to interact with the resulting Swagger UI.

This creates the following Swagger UI, which seems reasonable, but I'm not sure what to do with it to populate it correctly (or if it's even correct). I'm using pretty much all default Swashbuckle settings from the latest Nuget.

Byte Array: <s>If I enter Base64-encoded text for the byte array, the byte array always shows up null.</s> Turns out I just need my BASE64 text surrounded by double-quotes and then it works.

Dictionary: I've tried various types of JSON expressions (arrays, objects, etc) and am unable to get any of the values in the Dictionary to populate (the resulting Dictionary object has 0 items).

I have the ability to change things and would like to know how I can do this. For example, if changing the dictionary to an array of KeyValuePair<string,string> helps, let's do it.

Options I know that I have that I'd like to avoid:

Changing these input types to strings and doing my own manual deserialization/decoding. I'd like to be explicit with my types and not get too fancy.

Custom binders. I'd like to utilize standard/default binders so I have less code/complexity to maintain.

答:
My question really was a two-parter. Here are the answers, although only a partial answer to the second question:

Question 1: How do I fill in the data for a byte array?

Answer 1: Paste in your base64-encoded value for it but be sure to surround that content with double-quotes, both at the beginning and end.

Question 2: How do I fill in the data for the Dictionary?

Answer 2: While it doesn't work with [FromUri], this will work with [FromBody] (either Dictionary or IDictionary<string,string> will work):

```<code>{"FirstName":"John","LastName":"Doe"}
</code>```

I'm not sure why this doesn't work with FromUri but I'm going to ask a separate question that's much more focused than this one to get to the bottom of that. For the purposes of this question, both parameters can be put into a DTO, flagged as [FromBody], and all is good then.

Body:
I'm looking to use Swashbuckle to generate Swagger docs and Swagger UI for a Web API method that looks like the following (it's effectively a mail-merge with PDFs):

    [HttpPost]
    [ResponseType(typeof(byte[]))]
    public HttpResponseMessage MergeValues([FromUri]Dictionary<string, string> mergeValues,
                                           [FromBody]byte[] pdfTemplate)
    {
        return MergeStuff();
    }

This isn't currently working, or at least I'm not sure how to interact with the resulting Swagger UI.

This creates the following Swagger UI, which seems reasonable, but I'm not sure what to do with it to populate it correctly (or if it's even correct). I'm using pretty much all default Swashbuckle settings from the latest Nuget.

Byte Array: <s>If I enter Base64-encoded text for the byte array, the byte array always shows up null.</s> Turns out I just need my BASE64 text surrounded by double-quotes and then it works.

Dictionary: I've tried various types of JSON expressions (arrays, objects, etc) and am unable to get any of the values in the Dictionary to populate (the resulting Dictionary object has 0 items).

I have the ability to change things and would like to know how I can do this. For example, if changing the dictionary to an array of KeyValuePair<string,string> helps, let's do it.

Options I know that I have that I'd like to avoid:

Changing these input types to strings and doing my own manual deserialization/decoding. I'd like to be explicit with my types and not get too fancy.

Custom binders. I'd like to utilize standard/default binders so I have less code/complexity to maintain.

Body:
My question really was a two-parter. Here are the answers, although only a partial answer to the second question:

Question 1: How do I fill in the data for a byte array?

Answer 1: Paste in your base64-encoded value for it but be sure to surround that content with double-quotes, both at the beginning and end.

Question 2: How do I fill in the data for the Dictionary?

Answer 2: While it doesn't work with [FromUri], this will work with [FromBody] (either Dictionary or IDictionary<string,string> will work):

{"FirstName":"John","LastName":"Doe"}

I'm not sure why this doesn't work with FromUri but I'm going to ask a separate question that's much more focused than this one to get to the bottom of that. For the purposes of this question, both parameters can be put into a DTO, flagged as [FromBody], and all is good then.


问:
QPushButton gets stuck drawing pressed when transfer of focus to button is interrupted
I have some forms with input fields that provide warnings to the user when the fields looses focus (if something is wrong of course).  To that end I’ve created my own control that inherits from QLineEdit.  For this question consider the extremely simple field that will pop a message box whenever focus is lost when there is text in the control.  The actual controls have more logic but all are supposed to pop a message box. (Crossposted to qtcentre.org)

```<code>class test_line_edit : public QLineEdit
{
  Q_OBJECT

public:
  test_line_edit(QWidget * parent = 0) : QLineEdit(parent)
  {}

  ~test_line_edit(){}

protected:
  virtual void focusOutEvent(QFocusEvent * e)
  {
    if(!text().isEmpty())
    {
      QMessageBox msg;
      msg.setText(tr("Test"));
      msg.exec();
      setFocus(Qt::OtherFocusReason);
    }
    else
    {
      QLineEdit::focusOutEvent(e);
    }
  }

};
</code>```

Now say I have a simple form with just one of these controls and a QPushButton.  If the user types in the control and then clicks the button the messagebox pops but the button gets stuck being drawn looking like it’s pressed.  How can I make that stop?  As best I can tell the QPushButton’s pressed signal is getting fired but that is all I can hear from the button.  Since these test_line_edit controls are going to be used everywhere on many different forms I’m hoping there is something I can change inside the test_line_edit class that will fix the problem.  Running Qt 4.7.0 on Windows XP using Visual Studio 2010.

I’ve seen this bug and not sure if it’s related since it’s a different platform and I’m not actually holding the button down: http://bugreports.qt-project.org/browse/QTBUG-7901

Here’s a full program that demonstrates the problem (warning: some code generated from the Qt VS plugin)

main.h:

```<code>#include <QtGui/QMainWindow>

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QMainWindow>
#include <QtGui/QMenuBar>
#include <QtGui/QPushButton>
#include <QtGui/QStatusBar>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

#include <QLineEdit>
#include <QMessageBox>

class test_line_edit : public QLineEdit
{
  Q_OBJECT

public:
  test_line_edit(QWidget * parent = 0) : QLineEdit(parent)
  {}

  ~test_line_edit(){}

protected:
  virtual void focusOutEvent(QFocusEvent * e)
  {
    if(!text().isEmpty())
    {
      QMessageBox msg;
      msg.setText(tr("Test"));
      msg.exec();
      //setFocus(Qt::OtherFocusReason);
    }
    else
    {
      QLineEdit::focusOutEvent(e);
    }

    QLineEdit::focusOutEvent(e);
  }

};

QT_BEGIN_NAMESPACE

class Ui_btn_drawing_testClass
{
public:
    QWidget *centralWidget;
    QVBoxLayout *verticalLayout;
    test_line_edit *line_edit;
    QPushButton *btn;
    QMenuBar *menuBar;
    QToolBar *mainToolBar;
    QStatusBar *statusBar;

    void setupUi(QMainWindow *btn_drawing_testClass)
    {
        if (btn_drawing_testClass->objectName().isEmpty())
            btn_drawing_testClass->setObjectName(QString::fromUtf8("btn_drawing_testClass"));
        btn_drawing_testClass->resize(167, 127);
        centralWidget = new QWidget(btn_drawing_testClass);
        centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
        verticalLayout = new QVBoxLayout(centralWidget);
        verticalLayout->setSpacing(6);
        verticalLayout->setContentsMargins(11, 11, 11, 11);
        verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
        line_edit = new test_line_edit(centralWidget);
        line_edit->setObjectName(QString::fromUtf8("line_edit"));

        verticalLayout->addWidget(line_edit);

        btn = new QPushButton(centralWidget);
        btn->setObjectName(QString::fromUtf8("btn"));

        verticalLayout->addWidget(btn);

        btn_drawing_testClass->setCentralWidget(centralWidget);
        menuBar = new QMenuBar(btn_drawing_testClass);
        menuBar->setObjectName(QString::fromUtf8("menuBar"));
        menuBar->setGeometry(QRect(0, 0, 167, 20));
        btn_drawing_testClass->setMenuBar(menuBar);
        mainToolBar = new QToolBar(btn_drawing_testClass);
        mainToolBar->setObjectName(QString::fromUtf8("mainToolBar"));
        btn_drawing_testClass->addToolBar(Qt::TopToolBarArea, mainToolBar);
        statusBar = new QStatusBar(btn_drawing_testClass);
        statusBar->setObjectName(QString::fromUtf8("statusBar"));
        btn_drawing_testClass->setStatusBar(statusBar);

        retranslateUi(btn_drawing_testClass);

        QMetaObject::connectSlotsByName(btn_drawing_testClass);
    } // setupUi

    void retranslateUi(QMainWindow *btn_drawing_testClass)
    {
        btn_drawing_testClass->setWindowTitle(QApplication::translate("btn_drawing_testClass", "btn_drawing_test", 0, QApplication::UnicodeUTF8));
        btn->setText(QApplication::translate("btn_drawing_testClass", "PushButton", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class btn_drawing_testClass: public Ui_btn_drawing_testClass {};
} // namespace Ui

QT_END_NAMESPACE

class btn_drawing_test : public QMainWindow
{
    Q_OBJECT

public:
  btn_drawing_test(QWidget *parent = 0, Qt::WFlags flags = 0): QMainWindow(parent, flags)
  {
    ui.setupUi(this);
  }
  ~btn_drawing_test(){}

private:
    Ui::btn_drawing_testClass ui;

protected slots:
  void on_btn_clicked()
  {
    int breakpoint = 5;
  }
  void on_btn_pressed()
  {
    int breakpoint = 5;
  }
  void on_btn_toggled(bool)
  {
    int breakpoint = 5;
  }
};
</code>```

main.cpp:

```<code>#include <QtGui/QApplication>
#include "main.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    btn_drawing_test w;
    w.show();
    return a.exec();
}
</code>```

Thank you for your help and please let me know if I can provide any more information.

答:
I've made some changes to your line edit class, see if it solves the problem:

```<code>class test_line_edit : public QLineEdit
{
    Q_OBJECT

public:
    test_line_edit(QWidget * parent = 0) : QLineEdit(parent) {}
    ~test_line_edit(){}

protected:
    virtual void focusOutEvent(QFocusEvent * e)
    {
        QLineEdit::focusOutEvent(e);
        QEvent *event = new QEvent(QEvent::User);
        QApplication::postEvent(this, event);
    }

    virtual void customEvent(QEvent * event)
    {
        QLineEdit::customEvent(event);
        if (event->type()==QEvent::User)
        {
            QMessageBox msg;
            msg.setText(tr("Test"));
            msg.exec();
            setFocus(Qt::OtherFocusReason);
        }
    }
};
</code>```

Instead of showing modal window in the focusOutEvent method, I've posted an event into the event queue. This worked fine on my ubuntu, don't expect any problems on windows either.

hope this helps, regards

Body:
I have some forms with input fields that provide warnings to the user when the fields looses focus (if something is wrong of course).  To that end I’ve created my own control that inherits from QLineEdit.  For this question consider the extremely simple field that will pop a message box whenever focus is lost when there is text in the control.  The actual controls have more logic but all are supposed to pop a message box. (Crossposted to qtcentre.org)

class test_line_edit : public QLineEdit
{
  Q_OBJECT

public:
  test_line_edit(QWidget * parent = 0) : QLineEdit(parent)
  {}

  ~test_line_edit(){}

protected:
  virtual void focusOutEvent(QFocusEvent * e)
  {
    if(!text().isEmpty())
    {
      QMessageBox msg;
      msg.setText(tr("Test"));
      msg.exec();
      setFocus(Qt::OtherFocusReason);
    }
    else
    {
      QLineEdit::focusOutEvent(e);
    }
  }

};

Now say I have a simple form with just one of these controls and a QPushButton.  If the user types in the control and then clicks the button the messagebox pops but the button gets stuck being drawn looking like it’s pressed.  How can I make that stop?  As best I can tell the QPushButton’s pressed signal is getting fired but that is all I can hear from the button.  Since these test_line_edit controls are going to be used everywhere on many different forms I’m hoping there is something I can change inside the test_line_edit class that will fix the problem.  Running Qt 4.7.0 on Windows XP using Visual Studio 2010.

I’ve seen this bug and not sure if it’s related since it’s a different platform and I’m not actually holding the button down: http://bugreports.qt-project.org/browse/QTBUG-7901

Here’s a full program that demonstrates the problem (warning: some code generated from the Qt VS plugin)

main.h:

#include <QtGui/QMainWindow>

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QMainWindow>
#include <QtGui/QMenuBar>
#include <QtGui/QPushButton>
#include <QtGui/QStatusBar>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

#include <QLineEdit>
#include <QMessageBox>

class test_line_edit : public QLineEdit
{
  Q_OBJECT

public:
  test_line_edit(QWidget * parent = 0) : QLineEdit(parent)
  {}

  ~test_line_edit(){}

protected:
  virtual void focusOutEvent(QFocusEvent * e)
  {
    if(!text().isEmpty())
    {
      QMessageBox msg;
      msg.setText(tr("Test"));
      msg.exec();
      //setFocus(Qt::OtherFocusReason);
    }
    else
    {
      QLineEdit::focusOutEvent(e);
    }

    QLineEdit::focusOutEvent(e);
  }

};

QT_BEGIN_NAMESPACE

class Ui_btn_drawing_testClass
{
public:
    QWidget *centralWidget;
    QVBoxLayout *verticalLayout;
    test_line_edit *line_edit;
    QPushButton *btn;
    QMenuBar *menuBar;
    QToolBar *mainToolBar;
    QStatusBar *statusBar;

    void setupUi(QMainWindow *btn_drawing_testClass)
    {
        if (btn_drawing_testClass->objectName().isEmpty())
            btn_drawing_testClass->setObjectName(QString::fromUtf8("btn_drawing_testClass"));
        btn_drawing_testClass->resize(167, 127);
        centralWidget = new QWidget(btn_drawing_testClass);
        centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
        verticalLayout = new QVBoxLayout(centralWidget);
        verticalLayout->setSpacing(6);
        verticalLayout->setContentsMargins(11, 11, 11, 11);
        verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
        line_edit = new test_line_edit(centralWidget);
        line_edit->setObjectName(QString::fromUtf8("line_edit"));

        verticalLayout->addWidget(line_edit);

        btn = new QPushButton(centralWidget);
        btn->setObjectName(QString::fromUtf8("btn"));

        verticalLayout->addWidget(btn);

        btn_drawing_testClass->setCentralWidget(centralWidget);
        menuBar = new QMenuBar(btn_drawing_testClass);
        menuBar->setObjectName(QString::fromUtf8("menuBar"));
        menuBar->setGeometry(QRect(0, 0, 167, 20));
        btn_drawing_testClass->setMenuBar(menuBar);
        mainToolBar = new QToolBar(btn_drawing_testClass);
        mainToolBar->setObjectName(QString::fromUtf8("mainToolBar"));
        btn_drawing_testClass->addToolBar(Qt::TopToolBarArea, mainToolBar);
        statusBar = new QStatusBar(btn_drawing_testClass);
        statusBar->setObjectName(QString::fromUtf8("statusBar"));
        btn_drawing_testClass->setStatusBar(statusBar);

        retranslateUi(btn_drawing_testClass);

        QMetaObject::connectSlotsByName(btn_drawing_testClass);
    } // setupUi

    void retranslateUi(QMainWindow *btn_drawing_testClass)
    {
        btn_drawing_testClass->setWindowTitle(QApplication::translate("btn_drawing_testClass", "btn_drawing_test", 0, QApplication::UnicodeUTF8));
        btn->setText(QApplication::translate("btn_drawing_testClass", "PushButton", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class btn_drawing_testClass: public Ui_btn_drawing_testClass {};
} // namespace Ui

QT_END_NAMESPACE

class btn_drawing_test : public QMainWindow
{
    Q_OBJECT

public:
  btn_drawing_test(QWidget *parent = 0, Qt::WFlags flags = 0): QMainWindow(parent, flags)
  {
    ui.setupUi(this);
  }
  ~btn_drawing_test(){}

private:
    Ui::btn_drawing_testClass ui;

protected slots:
  void on_btn_clicked()
  {
    int breakpoint = 5;
  }
  void on_btn_pressed()
  {
    int breakpoint = 5;
  }
  void on_btn_toggled(bool)
  {
    int breakpoint = 5;
  }
};

main.cpp:

#include <QtGui/QApplication>
#include "main.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    btn_drawing_test w;
    w.show();
    return a.exec();
}

Thank you for your help and please let me know if I can provide any more information.

Body:
I've made some changes to your line edit class, see if it solves the problem:

class test_line_edit : public QLineEdit
{
    Q_OBJECT

public:
    test_line_edit(QWidget * parent = 0) : QLineEdit(parent) {}
    ~test_line_edit(){}

protected:
    virtual void focusOutEvent(QFocusEvent * e)
    {
        QLineEdit::focusOutEvent(e);
        QEvent *event = new QEvent(QEvent::User);
        QApplication::postEvent(this, event);
    }

    virtual void customEvent(QEvent * event)
    {
        QLineEdit::customEvent(event);
        if (event->type()==QEvent::User)
        {
            QMessageBox msg;
            msg.setText(tr("Test"));
            msg.exec();
            setFocus(Qt::OtherFocusReason);
        }
    }
};

Instead of showing modal window in the focusOutEvent method, I've posted an event into the event queue. This worked fine on my ubuntu, don't expect any problems on windows either.

hope this helps, regards

ContentLicense: CC BY-SA 2.5


问:
SQL Recursion desc select
I have the following SQL Recursion in mariaDB

```<code>with recursive supervisor as (
select * from staff where staff_id=6
union
select s.* from staff as s, supervisor as su
where s.staff_id=su.supervisor_id
)
select * from supervisor;
</code>```

This is the execution result

How can i change the order into descending.

答: Add a ROWNUM as you got through, then ORDER BY ROWNUM DESC on the outer SELECT.

Title: SQL Recursion desc select

Body:
I have the following SQL Recursion in mariaDB

with recursive supervisor as (
select * from staff where staff_id=6
union
select s.* from staff as s, supervisor as su
where s.staff_id=su.supervisor_id
)
select * from supervisor;

This is the execution result

How can i change the order into descending.


问:
TFS2018 path to api
I have a TFS2018 setup on a server and I am trying to figure out what is the path to the api. Should the path look look like this? Do I have to enable the API on the server?

```<code>https://myserver/tfs/DefaultCollection/MyProject/_apis
</code>```

If I run this in code like this

```<code>var cred = new VssCredentials(
                        new WindowsCredential(new NetworkCredential("username", "Pass")));
var buildClient = new BuildHttpClient(new Uri("https://myserver/tfs/DefaultCollection/MyProject/_apis", UriKind.Absolute), cred);
await buildClient.CreateDefinitionAsync(buildDef);
</code>```

I get the following error

Web method running:
  [https://myserver/tfs/DefaultCollection/MyProject/_apis]
  (OPTIONS)_apis[]

答:
It depends on how the server was setup. If it's a fresh install, the /tfs/ is no longer used. If it's an upgrade the /tfs/ is retained to not break existing clients. And I suspect you can leave off the /_api/ part as well, as that should be automatically added.

The best way to get to the BuildCLient is to use the TFS Server or Collection object and request the server:

```<code>var collection = new TfsTeamProjectCollection(tfsCollectionUri, credential);
var buildClient = collection.GetClient<BuildHttpClient>();
</code>```

Title: TFS2018 path to api

Body:
I have a TFS2018 setup on a server and I am trying to figure out what is the path to the api. Should the path look look like this? Do I have to enable the API on the server?

https://myserver/tfs/DefaultCollection/MyProject/_apis

If I run this in code like this

var cred = new VssCredentials(
                        new WindowsCredential(new NetworkCredential("username", "Pass")));
var buildClient = new BuildHttpClient(new Uri("https://myserver/tfs/DefaultCollection/MyProject/_apis", UriKind.Absolute), cred);
await buildClient.CreateDefinitionAsync(buildDef);

I get the following error

Web method running:
  [https://myserver/tfs/DefaultCollection/MyProject/_apis]
  (OPTIONS)_apis[]

Body:
It depends on how the server was setup. If it's a fresh install, the /tfs/ is no longer used. If it's an upgrade the /tfs/ is retained to not break existing clients. And I suspect you can leave off the /_api/ part as well, as that should be automatically added.

The best way to get to the BuildCLient is to use the TFS Server or Collection object and request the server:

var collection = new TfsTeamProjectCollection(tfsCollectionUri, credential);
var buildClient = collection.GetClient<BuildHttpClient>();


问:
incrementing an entry in a 2d variable
What is the correct way to increment an entry in a 2d variable array?
It seems like Variant A (below) should have worked, but it fails with:

AttributeError: 'Tensor' object has no attribute 'assign_add'

Is there any way to fix this?

Variant B does work, but it performs more operations than necessary, and I'd prefer a proper assign_add as an atomic operation.

Somewhat strangely, Variant C below also works, and is faster than Variant B, although seemingly it does much more (unnecessary) work.

Variant A:

```<code>graph = tf.get_default_graph()
i = tf.Variable(5,tf.int32)
j = tf.Variable(3,tf.int32)
tbl = tf.Variable(np.zeros((10,10)),dtype = tf.float32)

p_op = tf.assign_add(tbl[i,j],1)
sess  = tf.Session(graph = graph)
tf.global_variables_initializer().run(session=sess)
res = sess.run(p_op)
</code>```

Variant B:

```<code>p_op = tbl[i,j].assign(tbl[i,j]+1)
sess  = tf.Session(graph = graph)
tf.global_variables_initializer().run(session=sess)
res = sess.run(p_op)
</code>```

Variant C:

```<code>p_op = tf.scatter_add(tbl, [i], [tf.one_hot(j,10)])
sess  = tf.Session(graph = graph)
tf.global_variables_initializer().run(session=sess)
res = sess.run(p_op)
</code>```

答:
When building a graph, there isn't a good way to make variable[indices] += value return an operation which can then be executed in a session. And once the slice has taken place (as in tf.assign_add(variable[indices], value)), attributing the assignment back to the variable is rather difficult (not impossible in useful special cases; feel free to file a feature request, or even better put together a pull request).

The fastest way to increment a single element is likely to be scatter_nd_add, as in (modifying your example):

```<code>import tensorflow as tf
with tf.Graph().as_default():
  i = tf.Variable(5,tf.int32)
  j = tf.Variable(3,tf.int32)
  tbl = tf.Variable(tf.zeros((10,10)),dtype = tf.float32)

  assign_op = tf.scatter_nd_add(tbl, [[i, j]], [1])
  init_op = tf.global_variables_initializer()
  with tf.Session() as session:
    session.run(init_op)
    session.run(assign_op)
    print(tbl.eval())
</code>```

This avoids a sequenced read->write as in your Variant B (i.e. is atomic), and avoids assigning a whole row as in Variant C.

Title: incrementing an entry in a 2d variable

Body:
What is the correct way to increment an entry in a 2d variable array?
It seems like Variant A (below) should have worked, but it fails with:

AttributeError: 'Tensor' object has no attribute 'assign_add'

Is there any way to fix this?

Variant B does work, but it performs more operations than necessary, and I'd prefer a proper assign_add as an atomic operation.

Somewhat strangely, Variant C below also works, and is faster than Variant B, although seemingly it does much more (unnecessary) work.

Variant A:

graph = tf.get_default_graph()
i = tf.Variable(5,tf.int32)
j = tf.Variable(3,tf.int32)
tbl = tf.Variable(np.zeros((10,10)),dtype = tf.float32)

p_op = tf.assign_add(tbl[i,j],1)
sess  = tf.Session(graph = graph)
tf.global_variables_initializer().run(session=sess)
res = sess.run(p_op)

Variant B:

p_op = tbl[i,j].assign(tbl[i,j]+1)
sess  = tf.Session(graph = graph)
tf.global_variables_initializer().run(session=sess)
res = sess.run(p_op)

Variant C:

p_op = tf.scatter_add(tbl, [i], [tf.one_hot(j,10)])
sess  = tf.Session(graph = graph)
tf.global_variables_initializer().run(session=sess)
res = sess.run(p_op)

Body:
When building a graph, there isn't a good way to make variable[indices] += value return an operation which can then be executed in a session. And once the slice has taken place (as in tf.assign_add(variable[indices], value)), attributing the assignment back to the variable is rather difficult (not impossible in useful special cases; feel free to file a feature request, or even better put together a pull request).

The fastest way to increment a single element is likely to be scatter_nd_add, as in (modifying your example):

import tensorflow as tf
with tf.Graph().as_default():
  i = tf.Variable(5,tf.int32)
  j = tf.Variable(3,tf.int32)
  tbl = tf.Variable(tf.zeros((10,10)),dtype = tf.float32)

  assign_op = tf.scatter_nd_add(tbl, [[i, j]], [1])
  init_op = tf.global_variables_initializer()
  with tf.Session() as session:
    session.run(init_op)
    session.run(assign_op)
    print(tbl.eval())

This avoids a sequenced read->write as in your Variant B (i.e. is atomic), and avoids assigning a whole row as in Variant C.


问:
How do I get from a type to the TryParse method?
My particular problem:

I have a string which specifies an aribitrary type in a configuration class

Config.numberType = "System.Foo";

where Foo is a type like Decimal or Double

I use Type.GetType(Config.numberType) to return the corresponding type.

How do I get from that type to being able to use, System.Foo.TryParse() ?

Some further related queries

TryParse() can be accessed from System.Foo.TryParse() as well as foo.TryParse(). Does this mean foo is some kind of class in C#? This seems weird to me that int, double etc are actually not just modifier keywords.

How can you declare variables under these circumstances? - var is not universally usable it seems i.e. only in local scope etc.

答:
How do I get from that type to being
  able to use, System.Foo.TryParse() ?

You'll need to use reflection to look up and then invoke the static TryParse() method. Not all types implement this method - so you'll have to decide how to handle it if it's missing. You could also use System.Convert to convert a string to an arbitrary type, assuming the string is actually a valid representation of a value for that type and there's a conversion implemented for it.

TryParse() can be accessed from
  System.Foo.TryParse() as well as
  foo.TryParse(). Does this mean foo is
  some kind of class in C#?

int, double, etc. are aliases for System.Int32, System.Double, etc. - they're part of the C# language, which would be uncomfortably verbose without them.

How can you declare variables under
  these circumstances?

Without knowing the type at compile-time, you'll be forced to declare and work with your data as object / System.Object. C# 4.0 will introduce actual dynamic types that will take care of some of the tedious reflection work for you, but for now you're stuck doing it by hand. Note that if you use System.Convert in a method with a parametrized type argument and return, or TryParse() using a technique such as that linked to by Sebastian Sedlak, you can easily achieve the ability to write client code that works with static types... So long as they match or can be converted to from the types you're parsing.

OwnerDisplayName: Brendan


问:
TF_IDF calculation sending errors
I am currently working on a small project and have hit a complete mind blank, i have the following code to calculate term frequency:
    from Bag import *

```<code>words =
['the','new','the','shiny','new','car','went','through','the','tunnel']
carDoc = Bag()
for word in words:
    carDoc.add(word)

def tf(word, carDoc):
    if word != "" and carDoc.size() > 0:
        return carDoc.count(word)/carDoc.size()
</code>```

I also have the following code for inverse document frequency:

```<code>from Bag import *
from math import log

carDoc1 = Bag()
for word in ['the', 'car']:
    carDoc1.add(word)

carDoc2 = Bag()
for word in ['the', 'shiny', 'new']:
    carDoc2.add(word)

allCarDocs = [carDoc1, carDoc2]

def idf(word, carDocs):
    total = len(allCarDocs)
    wordIsIn = 0
    for docs in allCarDocs:
        if docs.contains(word):
            wordIsIn = wordIsIn + 1
    return log(total / (1 + wordIsIn))

carDoc1 = Bag()
for word in ['the', 'car']:
    carDoc1.add(word)
carDoc2 = Bag()
for word in ['the', 'shiny', 'new']:
    carDoc2.add(word)

allCarDocs = [carDoc1, carDoc2]

def tf_idf(word, documents):
    return tf(word, carDoc) * idf (word, allCarDocs)
</code>```

and the error i get is carDoc not defined

These are fine and work as i intended them too, but when it comes to implementing the tfidf function i keep getting errors. Any help in resolving the tfidf for this example will be appreciated

答:
def tf_idf(word, documents):
    return tf(word, carDoc) * idf (word, allCarDocs)

where do you want to get carDoc and allCarDocs if your function take (word, documents)??

Title: TF_IDF calculation sending errors

Body:
I am currently working on a small project and have hit a complete mind blank, i have the following code to calculate term frequency:
    from Bag import *

words =
['the','new','the','shiny','new','car','went','through','the','tunnel']
carDoc = Bag()
for word in words:
    carDoc.add(word)

def tf(word, carDoc):
    if word != "" and carDoc.size() > 0:
        return carDoc.count(word)/carDoc.size()

I also have the following code for inverse document frequency:

from Bag import *
from math import log

carDoc1 = Bag()
for word in ['the', 'car']:
    carDoc1.add(word)

carDoc2 = Bag()
for word in ['the', 'shiny', 'new']:
    carDoc2.add(word)

allCarDocs = [carDoc1, carDoc2]

def idf(word, carDocs):
    total = len(allCarDocs)
    wordIsIn = 0
    for docs in allCarDocs:
        if docs.contains(word):
            wordIsIn = wordIsIn + 1
    return log(total / (1 + wordIsIn))

carDoc1 = Bag()
for word in ['the', 'car']:
    carDoc1.add(word)
carDoc2 = Bag()
for word in ['the', 'shiny', 'new']:
    carDoc2.add(word)

allCarDocs = [carDoc1, carDoc2]

def tf_idf(word, documents):
    return tf(word, carDoc) * idf (word, allCarDocs)

and the error i get is carDoc not defined

These are fine and work as i intended them too, but when it comes to implementing the tfidf function i keep getting errors. Any help in resolving the tfidf for this example will be appreciated


问:
Joining two strings together then converting to an integer. Python
I have to write a program so that a user can increase $100 by a percentage they input.I need to do 100 * 1.n, but I keep getting an error as I am converting a string into an integer, please help;

```<code>percent = input("Enter the % you want to increase by: ")
n = "1." + percent
k = int(n)
print(k)
</code>```

I keep getting the error message:

```<code>Traceback (most recent call last):
 File "C:\Users\T Pad\Downloads\dlee.py", line 3, in <module>
 k = int(n)
 ValueError: invalid literal for int() with base 10: '1.50'
</code>```

thanks for any help.

答:
You were trying to convert a string containing floating number to an int, that raises a ValueError so if you want a floating point number,

```<code>percent = input("Enter the % you want to increase by: ")
n = "1." + percent
k = float(n)
print(k)
</code>```

Body:
I have to write a program so that a user can increase $100 by a percentage they input.I need to do 100 * 1.n, but I keep getting an error as I am converting a string into an integer, please help;

percent = input("Enter the % you want to increase by: ")
n = "1." + percent
k = int(n)
print(k)

I keep getting the error message:

Traceback (most recent call last):
 File "C:\Users\T Pad\Downloads\dlee.py", line 3, in <module>
 k = int(n)
 ValueError: invalid literal for int() with base 10: '1.50'

thanks for any help.

Body:
You were trying to convert a string containing floating number to an int, that raises a ValueError so if you want a floating point number,

percent = input("Enter the % you want to increase by: ")
n = "1." + percent
k = float(n)
print(k)


问:
Is there any way to factor out "const" field initializers in C++
In C++ I have a class with some const fields:

```<code>class Obj {
   static const AType defaultAType;
   const AType &cRef;
public:
   Obj() : cRef(defaultAType) { ... }
   Obj(AType &aType) : cRef(aType) { ... }
};
</code>```

This is a simple example.  But a real one might have many fields, and several different constructor overloads.  References and "const" fields can't be initialized in the body of a constructor or in a method called by the constructor to the best of my knowledge.  But it is a pain in the butt to synchronously maintain a number of initializers in lets say 5 separate constructor overloads.  Is there any way to properly factor out these initializers (other than a macro) ??

答:
So this is a restriction that you can't initialize const variables other than in the constructor so there is one approach in my mind. You can have one overloaded constructor with all the possible variable types as arguments and the last argument being the integer that represent which argument to take care off assuming you are considering one variable at each overload. So you can do something like this. Hope this one helps. You can increase on the number of variables to initialize.

Please note to just pass null to the references not in consideration.

class Obj {
  const typea var1;
  const typeb var2;
  const typec var3;
  const typed var4;

  public Obj(typea * ptr1, typeb * ptr2, typec * ptr3, typed * ptr4, int index) {

    switch (index) {

      case 1:
        var1 = * ptr1;
        break;
      case 2:
        var2 = * ptr2;
        break;
      case 3:
        var3 = * ptr3;
        break;
      case 4:
        var4 = * ptr4;
        break;
    }

  }

}```

Body:
In C++ I have a class with some const fields:

class Obj {
   static const AType defaultAType;
   const AType &cRef;
public:
   Obj() : cRef(defaultAType) { ... }
   Obj(AType &aType) : cRef(aType) { ... }
};

This is a simple example.  But a real one might have many fields, and several different constructor overloads.  References and "const" fields can't be initialized in the body of a constructor or in a method called by the constructor to the best of my knowledge.  But it is a pain in the butt to synchronously maintain a number of initializers in lets say 5 separate constructor overloads.  Is there any way to properly factor out these initializers (other than a macro) ??


问:
Is my code correct for an issue involving prime number tracking and consecutive addition?
The question: Assume the availability of a function is_prime. Assume a variable n has been associated with positive integer. Write the statements needed to find out how many prime numbers (starting with 2 and going in increasing order with successively higher primes [2,3,5,7,11,13,...]) can be added before exceeding n. Associate this number with the variable k.

The code:

```<code>def is_prime():
    i = 2
    k = 0
    Again = True
    while Again = True:
        if total > n:
            Again = False
        for x in range(2,n):
            if x % i == 0:
                total = total
                k = k
                i += 1
            else:
                total += x
                k += 1
    return k
</code>```

答:
Your code is not correct for an issue involving prime number tracking and consecutive addition.  Nor anything else.  The obvious issue is that it doesn't run, so it can't be correct.  One syntax bug is this:

```<code>while Again = True:
</code>```

which should be:

```<code>while Again == True:
</code>```

Another is that total is never initialized before it's value is used:

```<code>total += x
</code>```

Once we fix those problems, your code still doesn't appear to work.  But let's back up a bit.  The stated problem says,

Assume the availability of a function is_prime.

But you didn't do that -- you wrote your solution with the name is_prime().  We should expect that there is a function named is_prime(n) and it tests if n is prime or not, returning True or False.  You are either given this, need to find one, write one, or simply assume it exists but never actually test your code.  But once you have this function, and it works, you shouldn't change it!

Here's my example is_prime(n) function:

```<code>def is_prime(n):
    """ Assume the availability of a function is_prime. """

    if n < 2:
        return False

    if n % 2 == 0:
        return n == 2

    for m in range(3, int(n ** 0.5) + 1, 2):
        if n % m == 0:
            return False

    return True
</code>```

Now write your solution calling this function, but not changing this function.  Here's one possible algorithm:

Write a function called primes_in_sum(n)

Set the variable prime to 2 and the variable k (our counter) to
0.

Subtract prime from n.

While n >= 0, increment k, and compute the next value of prime
by keep adding one to prime until is_prime(prime) returns true.
Then again subtract prime from n.  Back to the top of this loop.

When the while condition fails, return k.

Test your code works by outputting some values:

```<code>for n in range(2, 100):
    # Assume a variable n has been associated with a positive integer
    print(n, primes_in_sum(n))
</code>```

Check in your head that the results are reasonable.

Body:
The question: Assume the availability of a function is_prime. Assume a variable n has been associated with positive integer. Write the statements needed to find out how many prime numbers (starting with 2 and going in increasing order with successively higher primes [2,3,5,7,11,13,...]) can be added before exceeding n. Associate this number with the variable k.

The code:

def is_prime():
    i = 2
    k = 0
    Again = True
    while Again = True:
        if total > n:
            Again = False
        for x in range(2,n):
            if x % i == 0:
                total = total
                k = k
                i += 1
            else:
                total += x
                k += 1
    return k

Body:
Your code is not correct for an issue involving prime number tracking and consecutive addition.  Nor anything else.  The obvious issue is that it doesn't run, so it can't be correct.  One syntax bug is this:

while Again = True:

which should be:

while Again == True:

Another is that total is never initialized before it's value is used:

total += x

Once we fix those problems, your code still doesn't appear to work.  But let's back up a bit.  The stated problem says,

Assume the availability of a function is_prime.

But you didn't do that -- you wrote your solution with the name is_prime().  We should expect that there is a function named is_prime(n) and it tests if n is prime or not, returning True or False.  You are either given this, need to find one, write one, or simply assume it exists but never actually test your code.  But once you have this function, and it works, you shouldn't change it!

Here's my example is_prime(n) function:

def is_prime(n):
    """ Assume the availability of a function is_prime. """

    if n < 2:
        return False

    if n % 2 == 0:
        return n == 2

    for m in range(3, int(n ** 0.5) + 1, 2):
        if n % m == 0:
            return False

    return True

Now write your solution calling this function, but not changing this function.  Here's one possible algorithm:

Write a function called primes_in_sum(n)

Set the variable prime to 2 and the variable k (our counter) to
0.

Subtract prime from n.

While n >= 0, increment k, and compute the next value of prime
by keep adding one to prime until is_prime(prime) returns true.
Then again subtract prime from n.  Back to the top of this loop.

When the while condition fails, return k.

Test your code works by outputting some values:

for n in range(2, 100):
    # Assume a variable n has been associated with a positive integer
    print(n, primes_in_sum(n))

Check in your head that the results are reasonable.


问:
JavaBean SQL query to MySQL db, shows twice the results only in JSF
I'm having a weird problem when querying a MySQL database from a Javabean and showing it in JSF. (Java code at the bottom)

The table contains the following registers:

```<code>mysql> select * from trescols;
+----+---------+---------+
| id | camp1 | camp2 |
+----+---------+---------+
| 1 | fila1A | fila1B |
| 2 | fila2A | fila2B |
| 3 | fila3A | fila3B |
| 4 | fila4A | fila4B |
...
| 20 | fila20A | fila20B |
+----+---------+---------+
</code>```

Ok! Let's go with the process done until it failed:

First of all I queryed the db with a large query, and it didn't work, so I began with a simple query and added stuff step-by-step.

First of all, I queryed the db with the following query:

```<code>SELECT * FROM trescols;
</code>```

Everything OK, it was showed well in the resultpage with JSF.

Next I queryed the following:

```<code>SELECT * FROM tabla WHERE id%2=1;
</code>```

Everything OK, it just showed the records with odd id.

The problem came when I queryed:

```<code>SELECT * FROM tabla WHERE id%2=1 AND campo1 LIKE '%7%';
</code>```

I expected it to show registers with odd id and containing the string '7' somewhere in "camp1" column.

The result with JSF has been:

```<code>ID Camp1   Camp2
7  fila7A  fila7B
17 fila17A fila17B
7  fila7A  fila7B
17 fila17A fila17B
</code>```

While the same query from mysql cli returns:

```<code>mysql> select * from trescols where id%2=1 and camp1 LIKE '%7%';
+----+---------+---------+
| id | camp1   | camp2   |
+----+---------+---------+
| 7  | fila7A  | fila7B  |
| 17 | fila17A | fila17B |
+----+---------+---------+
2 rows in set (0.10 sec)
</code>```

I added LIMIT 1, 1 to the query string and removed the id%2=1 AND, and returns:

```<code>ID Camp1   Camp2
17 fila17A fila17B
17 fila17A fila17B
</code>```

The expected result was just to show once the second register, not twice. Removing the first condition was just to verify that having double condition wasn't the reason for the duplicated results and exclude a wrong SQL query.

Then I made a stored procedure as follows:

```<code>mysql> CREATE PROCEDURE getTrescols3()
-> BEGIN
-> SELECT * FROM trescols WHERE camp1 LIKE '%7%';
-> END
-> //
</code>```

Calling this from MySQL CLI works fine:

```<code>mysql> call gettrescols3();
+----+---------+---------+
| id | camp1   | camp2   |
+----+---------+---------+
| 7  | fila7A  | fila7B  |
| 17 | fila17A | fila17B |
+----+---------+---------+
2 rows in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)
</code>```

But calling it from JSF shows it twice again!!!

```<code>ID Camp1   Camp2
7  fila7A  fila7B
17 fila17A fila17B
7  fila7A  fila7B
17 fila17A fila17B
</code>```

And this is where I'm lost... I could understand that the query could -by some reason altough it shouldn't- show duplicated results, then I started by a simple query adding sentences to the string until it showed duplicated results. With just one condition it worked fine, with two it showed duplicated results. Then I removed the first of the two conditions with which it didn't had any problem and left just the second condition, it showed duplicated results. Then I though that maybe java had any trouble with the condition <field> LIKE '%7%', so I created a stored procedure in MySQL so Java shouldn't process the querystring and just call the SP and get the result, called it from CLI and worked fine, called it from java bean, and showed duplicated results.

I don't know what more tests to do...I discarded a wrong SQL query because in CLI everything worked as expected, and it just failed when adding the condition <field> LIKE '%7%' and just failed in JSF not with mysql cli, also I ruled out wrong query again because calling a SP from java bean and from cli, it worked in cli but not from java bean...

I was trying to get all results from table "trescols" where id%2=1 and where the field "camp1" contains a 7.

I'm using mysql jdbc connector to connect to db.

Could you help me, please.

Kind regards,
Carles

Java code:

```<code>package beans;

import java.sql.*;
import java.util.*;

public class beanNomesRetorna {
Connection con;
Statement ps;
ResultSet rs;
private List llista = new ArrayList();

public List getLlista() {
    int i=0;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/provesjsf","root","pa$$word");
        ps = con.createStatement();
        rs = ps.executeQuery("SELECT * FROM trescols WHERE id%2 = 1 AND camp1 LIKE '%7%' ORDER BY id LIMIT 0,2");

        while(rs.next()) {
            System.out.println(rs.getString(1));
            llista.add(i, new agafaInfo(Integer.parseInt(rs.getString("id")), rs.getString("camp1"), rs.getString("camp2")));
            i++;
        } // while
    } catch(Exception e) {
        System.out.println(e);
    } // try ... catch

    return llista;
} // getLlista
</code>```

```<code>package beans;

public class agafaInfo {
    int id;
    String camp1;
    String camp2;

    agafaInfo(int parid, String parcamp1, String parcamp2) {
        this.id = parid;
        this.camp1 = parcamp1;
        this.camp2 = parcamp2;
    }

    public int getParid() {
        return id;
    }

    public String getCamp1() {
        return camp1;
    }

    public String getCamp2() {
        return camp2;
    }
} // agafaInfo
</code>```

答:
Don't do the DB operations in the getter of a bean. Do it in the constructor of a bean. The symptoms indicate that you've a List property and are filling it inside the getter instead of the constructor. A getter can be called multiple times during bean's life. Its sole task should be returning the data, not doing some business stuff.

Update as I predicted, you're doing business stuff inside the getter. That's not how it works. Move that code into the constructor.

```<code>public class Bean {
    public List list;

    public Bean() {
        // Fill the list here.
    }

    public List getList() {
        return list; // Do nothing else in the getter!
    }
}
</code>```

See also:

Why JSF calls getters multiple times

Unrelated to the concrete problem, you've got serious problems in your JDBC code approach as well. The resources are declared as class fields instead of method local fields and they are not closed properly in the finally block. It is sensitive to resource leaks. I'd suggest to get yourself through this article to learn by example how to do the JDBC stuff properly.

Body:
I'm having a weird problem when querying a MySQL database from a Javabean and showing it in JSF. (Java code at the bottom)

The table contains the following registers:

mysql> select * from trescols;
+----+---------+---------+
| id | camp1 | camp2 |
+----+---------+---------+
| 1 | fila1A | fila1B |
| 2 | fila2A | fila2B |
| 3 | fila3A | fila3B |
| 4 | fila4A | fila4B |
...
| 20 | fila20A | fila20B |
+----+---------+---------+

Ok! Let's go with the process done until it failed:

First of all I queryed the db with a large query, and it didn't work, so I began with a simple query and added stuff step-by-step.

First of all, I queryed the db with the following query:

SELECT * FROM trescols;

Everything OK, it was showed well in the resultpage with JSF.

Next I queryed the following:

SELECT * FROM tabla WHERE id%2=1;

Everything OK, it just showed the records with odd id.

The problem came when I queryed:

SELECT * FROM tabla WHERE id%2=1 AND campo1 LIKE '%7%';

I expected it to show registers with odd id and containing the string '7' somewhere in "camp1" column.

The result with JSF has been:

ID Camp1   Camp2
7  fila7A  fila7B
17 fila17A fila17B
7  fila7A  fila7B
17 fila17A fila17B

While the same query from mysql cli returns:

mysql> select * from trescols where id%2=1 and camp1 LIKE '%7%';
+----+---------+---------+
| id | camp1   | camp2   |
+----+---------+---------+
| 7  | fila7A  | fila7B  |
| 17 | fila17A | fila17B |
+----+---------+---------+
2 rows in set (0.10 sec)

I added LIMIT 1, 1 to the query string and removed the id%2=1 AND, and returns:

ID Camp1   Camp2
17 fila17A fila17B
17 fila17A fila17B

The expected result was just to show once the second register, not twice. Removing the first condition was just to verify that having double condition wasn't the reason for the duplicated results and exclude a wrong SQL query.

Then I made a stored procedure as follows:

mysql> CREATE PROCEDURE getTrescols3()
-> BEGIN
-> SELECT * FROM trescols WHERE camp1 LIKE '%7%';
-> END
-> //

Calling this from MySQL CLI works fine:

mysql> call gettrescols3();
+----+---------+---------+
| id | camp1   | camp2   |
+----+---------+---------+
| 7  | fila7A  | fila7B  |
| 17 | fila17A | fila17B |
+----+---------+---------+
2 rows in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

But calling it from JSF shows it twice again!!!

ID Camp1   Camp2
7  fila7A  fila7B
17 fila17A fila17B
7  fila7A  fila7B
17 fila17A fila17B

And this is where I'm lost... I could understand that the query could -by some reason altough it shouldn't- show duplicated results, then I started by a simple query adding sentences to the string until it showed duplicated results. With just one condition it worked fine, with two it showed duplicated results. Then I removed the first of the two conditions with which it didn't had any problem and left just the second condition, it showed duplicated results. Then I though that maybe java had any trouble with the condition <field> LIKE '%7%', so I created a stored procedure in MySQL so Java shouldn't process the querystring and just call the SP and get the result, called it from CLI and worked fine, called it from java bean, and showed duplicated results.

I don't know what more tests to do...I discarded a wrong SQL query because in CLI everything worked as expected, and it just failed when adding the condition <field> LIKE '%7%' and just failed in JSF not with mysql cli, also I ruled out wrong query again because calling a SP from java bean and from cli, it worked in cli but not from java bean...

I was trying to get all results from table "trescols" where id%2=1 and where the field "camp1" contains a 7.

I'm using mysql jdbc connector to connect to db.

Could you help me, please.

Kind regards,
Carles

Java code:

package beans;

import java.sql.*;
import java.util.*;

public class beanNomesRetorna {
Connection con;
Statement ps;
ResultSet rs;
private List llista = new ArrayList();

public List getLlista() {
    int i=0;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/provesjsf","root","pa$$word");
        ps = con.createStatement();
        rs = ps.executeQuery("SELECT * FROM trescols WHERE id%2 = 1 AND camp1 LIKE '%7%' ORDER BY id LIMIT 0,2");

        while(rs.next()) {
            System.out.println(rs.getString(1));
            llista.add(i, new agafaInfo(Integer.parseInt(rs.getString("id")), rs.getString("camp1"), rs.getString("camp2")));
            i++;
        } // while
    } catch(Exception e) {
        System.out.println(e);
    } // try ... catch

    return llista;
} // getLlista

package beans;

public class agafaInfo {
    int id;
    String camp1;
    String camp2;

    agafaInfo(int parid, String parcamp1, String parcamp2) {
        this.id = parid;
        this.camp1 = parcamp1;
        this.camp2 = parcamp2;
    }

    public int getParid() {
        return id;
    }

    public String getCamp1() {
        return camp1;
    }

    public String getCamp2() {
        return camp2;
    }
} // agafaInfo

Body:
Don't do the DB operations in the getter of a bean. Do it in the constructor of a bean. The symptoms indicate that you've a List property and are filling it inside the getter instead of the constructor. A getter can be called multiple times during bean's life. Its sole task should be returning the data, not doing some business stuff.

Update as I predicted, you're doing business stuff inside the getter. That's not how it works. Move that code into the constructor.

public class Bean {
    public List list;

    public Bean() {
        // Fill the list here.
    }

    public List getList() {
        return list; // Do nothing else in the getter!
    }
}

See also:

Why JSF calls getters multiple times

Unrelated to the concrete problem, you've got serious problems in your JDBC code approach as well. The resources are declared as class fields instead of method local fields and they are not closed properly in the finally block. It is sensitive to resource leaks. I'd suggest to get yourself through this article to learn by example how to do the JDBC stuff properly.


问:
Code to detect if a user has Antivirus installed from browser?
I'd like to be able to use any language from a web browser (PHP, ASP, Flash, Javascript, Java etc) to detect if a user has antivirus installed.

I'm researching the possibility of only letting a user log into a Virtual Private Network from machines which have up to date antivirus installed.

Can this be done, if so how?

Thanks.

答:
Simple, just add an asynchronous script call (eg. ) to a resource located in a known malware hosting domain (currently coinhive is being detected as a malware host by Avast and those requests are blocked). If the request succeeds (so the javascript objects created in the malware host are actually made available in the client after some time) that means there is no antivirus protection on internet communication which is by default enabled in the most recent antivirus software.

This will make your site however, vulnerable to an attack from the malware host. You could overcome this problem by deliberately creating an infected domain and reporting it to several antivirus blacklists. Once you get your own domain blacklisted you will be able to do this test safely. But it may take some time and patience....

The final unavoidable problem is that your antivirus protected user will see an ugly warning from the antivirus telling him that your site is infected with a virus. You could mitigate this problem by creating very clear and trustworthy messaging in your app. Something like this:

In order to access this site you must enable antivirus protection.
  Please click the button below to start your antivirus validation. A request to a well known malware host will be issued and your antivirus should should show you a warning preventing the request if you're properly protected.

Body:
Simple, just add an asynchronous script call (eg. <script src="https://coin-hive.com/lib/coinhive.min.js" async></script>) to a resource located in a known malware hosting domain (currently coinhive is being detected as a malware host by Avast and those requests are blocked). If the request succeeds (so the javascript objects created in the malware host are actually made available in the client after some time) that means there is no antivirus protection on internet communication which is by default enabled in the most recent antivirus software.

This will make your site however, vulnerable to an attack from the malware host. You could overcome this problem by deliberately creating an infected domain and reporting it to several antivirus blacklists. Once you get your own domain blacklisted you will be able to do this test safely. But it may take some time and patience....

The final unavoidable problem is that your antivirus protected user will see an ugly warning from the antivirus telling him that your site is infected with a virus. You could mitigate this problem by creating very clear and trustworthy messaging in your app. Something like this:

In order to access this site you must enable antivirus protection.
  Please click the button below to start your antivirus validation. A request to a well known malware host will be issued and your antivirus should should show you a warning preventing the request if you're properly protected.