问:
GAME ENGINE : dynamic_cast - Object class is not a polymorphic type
First of all im trying to create a games engine with similar architecture to Unity. I have an Object class, a GameObject class which inherits from Object. Within GameObject class i am trying to make a template class that will let you add any component onto the game object, although i get a dynamic pointer cast error which i cant seem to solve.

Heres the GameObject class:

```<code>class GameObject : public Object

{

public:

template<class T>
std::shared_ptr<T> addChildComponent()
{
    std::shared_ptr<T> temp_component(new T());

    temp_component->gameObject = std::dynamic_pointer_cast<GameObject>(shared_from_this());
    m_components.push_back(temp_component);

    return temp_component;
}

template<class T>
std::shared_ptr<T> getComponent()
{
    for (int i = 0; i < m_components.size(); i++)
    {
        std::shared_ptr<T> t;
        t = m_components.at(i);

        if (t.get() != NULL)
        {
            return t;
        }
    }

    return std::shared_ptr<T>();

}
</code>```

Furthermore this is the Object Class which it inherits from:

```<code>class Object : public std::enable_shared_from_this<Object>
{

friend class GameObject;

public:
Object();
~Object();

void makeName(std::string _name);

std::string getName();

private:
std::string name;

};
</code>```

答:
The error means that whatever you are trying to cast from does not have any virtual members. A base class of a virtual inheritance chain should always have a virtual destructor at minimum and then you would no longer get this error.

As an example, the following would exhibit the error you have:

```<code>class base1
{
int a;
};
class derived1: public base1
{};
...
derived1 d1;
base1 * pb1 =&d1;
derived1 * pd1 = dynamic_cast<derived1*>(pb1);
</code>```

While  the next would not:

```<code>class base2
{
int a;
public:
virtual ~base1() {}
};
class derived2 : public base2
{};
...
derived2 d2;
base2 * pb2 = &d2;
derived2 * pd2 = dynamic_cast<derived2*>(pb2);
</code>```

Body:
First of all im trying to create a games engine with similar architecture to Unity. I have an Object class, a GameObject class which inherits from Object. Within GameObject class i am trying to make a template class that will let you add any component onto the game object, although i get a dynamic pointer cast error which i cant seem to solve.

Heres the GameObject class:

class GameObject : public Object

{

public:

template<class T>
std::shared_ptr<T> addChildComponent()
{
    std::shared_ptr<T> temp_component(new T());

    temp_component->gameObject = std::dynamic_pointer_cast<GameObject>(shared_from_this());
    m_components.push_back(temp_component);

    return temp_component;
}

template<class T>
std::shared_ptr<T> getComponent()
{
    for (int i = 0; i < m_components.size(); i++)
    {
        std::shared_ptr<T> t;
        t = m_components.at(i);

        if (t.get() != NULL)
        {
            return t;
        }
    }

    return std::shared_ptr<T>();

}

Furthermore this is the Object Class which it inherits from:

class Object : public std::enable_shared_from_this<Object>
{

friend class GameObject;

public:
Object();
~Object();

void makeName(std::string _name);

std::string getName();

private:
std::string name;

};

Body:
The error means that whatever you are trying to cast from does not have any virtual members. A base class of a virtual inheritance chain should always have a virtual destructor at minimum and then you would no longer get this error.

As an example, the following would exhibit the error you have:

class base1
{
int a;
};
class derived1: public base1
{};
...
derived1 d1;
base1 * pb1 =&d1;
derived1 * pd1 = dynamic_cast<derived1*>(pb1);

While  the next would not:

class base2
{
int a;
public:
virtual ~base1() {}
};
class derived2 : public base2
{};
...
derived2 d2;
base2 * pb2 = &d2;
derived2 * pd2 = dynamic_cast<derived2*>(pb2);


来源: stackexchange

问:
Cut String by maxLines parameter, and by number of characters
I'm writing a class with a method that takes a summary string and breaks it down into a maximum number of lines (maxLines Parameter) and maximum number of characters per line (width parameter). All lines except the first line should be indented (they should start with a space character), but the second character in an indented line should not be another space (so that second space must not be included). The program should still work if you change the maxLine parameter r width.

Also, the code should check whether some special characters are in the String, like:

```<code> \' , \" , \\ , \t , \b , \r , \f , \n
</code>```

How can I inspect is many spaces in String like below? If there are many spaces in the String, I want to trim them, but I don't know how to. (These underscores represent spaces.)

```<code>"9:00 John_____________________________Doe until 10 30 at Office"

9:00 Jo
_hn____
_______
_____Do
</code>```

With my code, I get this result:

```<code> 9:00 Jo
 _hn Doe
 _until 1
 _0 30 at
</code>```

But I want THIS this output:

```<code>9:00 Jo
_hn Doe
_until_
_10 30_
</code>```

Here is my code:

```<code>public static void main(String[] args) {

    String str = "9:00 John Doe until 10 30 at Office";
    int width = 7;
    int maxLine = 4;
    List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
    for (String part : lisT) {
        System.out.println(part);
    }
}

public static List<String> getParts(String str, int width, int maxLine) {
    List<String> parts = new LinkedList<>();
    int count = 0;
    int len = str.length();
    String indent = "";
    for (int i = 0; i < len; i += width) {
        parts.add(indent + str.substring(i, Math.min(len, i + width)).trim());
        count++;
        indent = " ";
        if (count == maxLine)
            break;
    }
    return parts;
}
</code>```

答:
I think your rows might be too long because your width = 7 includes the indent space, so your rows have a width of 8 instead of 7. I would try replacing for (int i = 0; i < len; i += width) {... with for (int i = 1; i < len; i += width - 1) {... and add a special statement right before the for loop for the 0th row, since you do not want to indent the 0th row. Something like this:

```<code>parts.add(str.substring(0, Math.min(len, i + width)).trim());
    for(...){...}
</code>```

Let me know whether that seems to be the problem. If not, I can take another look. To answer your other questions:

To remove more than one space in the middle of a string, use this to replace all whitespace with exactly one space:

```<code>String result = replaceAll("\\s","");
</code>```

You can remove the special characters with a regex like this:

```<code>String result = str.replaceAll("[\'\"\\\t\b\r\f\n]","");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a class with a method that takes a summary string and breaks it down into a maximum number of lines (maxLines Parameter) and maximum number of characters per line (width parameter). All lines except the first line should be indented (they should start with a space character), but the second character in an indented line should not be another space (so that second space must not be included). The program should still work if you change the maxLine parameter r width.

Also, the code should check whether some special characters are in the String, like:

 \' , \" , \\ , \t , \b , \r , \f , \n

How can I inspect is many spaces in String like below? If there are many spaces in the String, I want to trim them, but I don't know how to. (These underscores represent spaces.)

"9:00 John_____________________________Doe until 10 30 at Office"

9:00 Jo
_hn____
_______
_____Do

With my code, I get this result:

 9:00 Jo
 _hn Doe
 _until 1
 _0 30 at

But I want THIS this output:

9:00 Jo
_hn Doe
_until_
_10 30_

Here is my code:

public static void main(String[] args) {

    String str = "9:00 John Doe until 10 30 at Office";
    int width = 7;
    int maxLine = 4;
    List<String> lisT = new LinkedList<>(getParts(str, width, maxLine));
    for (String part : lisT) {
        System.out.println(part);
    }
}

public static List<String> getParts(String str, int width, int maxLine) {
    List<String> parts = new LinkedList<>();
    int count = 0;
    int len = str.length();
    String indent = "";
    for (int i = 0; i < len; i += width) {
        parts.add(indent + str.substring(i, Math.min(len, i + width)).trim());
        count++;
        indent = " ";
        if (count == maxLine)
            break;
    }
    return parts;
}

Body:
I think your rows might be too long because your width = 7 includes the indent space, so your rows have a width of 8 instead of 7. I would try replacing for (int i = 0; i < len; i += width) {... with for (int i = 1; i < len; i += width - 1) {... and add a special statement right before the for loop for the 0th row, since you do not want to indent the 0th row. Something like this:

parts.add(str.substring(0, Math.min(len, i + width)).trim());
    for(...){...}

Let me know whether that seems to be the problem. If not, I can take another look. To answer your other questions:

To remove more than one space in the middle of a string, use this to replace all whitespace with exactly one space:

String result = replaceAll("\\s","");

You can remove the special characters with a regex like this:

String result = str.replaceAll("[\'\"\\\t\b\r\f\n]","");

ContentLicense: CC BY-SA 3.0


问:
Azure SQL Sync Group Db Isolation Level Error
An error is given stating the database Isolation Level state is different between two databases when replicating between an Azure SQL database and an on-premise SQL database using the SQL Agent software installed on the on-premise server.

How do I fix this?

答:
Unfortunately one of the requirements for synchronizing databases using SQL Data Sync is that all hub and member databases must use snapshot isolation level. For more information about SQL Data Sync requirements please visit this documentation.

Set the isolation level of the on-premises database as shown below:

```<code>ALTER DATABASE MyDatabase
SET ALLOW_SNAPSHOT_ISOLATION ON

ALTER DATABASE MyDatabase
SET READ_COMMITTED_SNAPSHOT ON
</code>```

Body:
Unfortunately one of the requirements for synchronizing databases using SQL Data Sync is that all hub and member databases must use snapshot isolation level. For more information about SQL Data Sync requirements please visit this documentation.

Set the isolation level of the on-premises database as shown below:

ALTER DATABASE MyDatabase
SET ALLOW_SNAPSHOT_ISOLATION ON

ALTER DATABASE MyDatabase
SET READ_COMMITTED_SNAPSHOT ON


问:
jQuery checkbox disable and add class
I have a table which have list of rows and every row have two checkboxes
what I am trying to do is when someone check on check box it send request to server using ajax and reponsev with data if it pass it change the tr color to green if fail it change to red..I am done with this step

Now I want when it is success it should enable other check box which is on the same tr so now user can process with the second step.

$("#SendReview").click(function() {

  var selected = "";
  $('.ReviewForm').each(function() {
    selected = selected + "," + $(this).attr('id');
  });

  $.ajax({
    url: '@Url.Action("VerifyFormRquest", "Results")',
    type: "POST",
    data: {
      scanid: selected
    },
    success: function(data, textStatus, jqXHR) {
      alert(data.success);

      data.success.split(',').forEach(function(c) {
        if (c != "") {
          var m = $('#example tr:has(td:contains(' + c + '))').css('background-color', 'lightgreen');
        }
      });
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="example">
  <tr id="1000000107">
    <td>
      <input type="checkbox" id="J15000001" scanid="1000000103" onclick="call()" disabled="disabled" value="1000000103" class="ELOchecked">
    </td>
  </tr>
  <tr id="1000000107">
    <td>
      <input type="checkbox" id="J15000012" scanid="1000000107" disabled="disabled" value="1000000107" class="ELR">
    </td>
  </tr>
</table></code>```

答:
You can do this by using the prop method.

$("#myOtherCheckbox").prop("disabled", false);

If you want to add a class to it as well:

$("#myOtherCheckbox").prop("disabled", false).addClass("someClass");

Title: jQuery checkbox disable and add class

Body:
I have a table which have list of rows and every row have two checkboxes
what I am trying to do is when someone check on check box it send request to server using ajax and reponsev with data if it pass it change the tr color to green if fail it change to red..I am done with this step

Now I want when it is success it should enable other check box which is on the same tr so now user can process with the second step.

$("#SendReview").click(function() {

  var selected = "";
  $('.ReviewForm').each(function() {
    selected = selected + "," + $(this).attr('id');
  });

  $.ajax({
    url: '@Url.Action("VerifyFormRquest", "Results")',
    type: "POST",
    data: {
      scanid: selected
    },
    success: function(data, textStatus, jqXHR) {
      alert(data.success);

      data.success.split(',').forEach(function(c) {
        if (c != "") {
          var m = $('#example tr:has(td:contains(' + c + '))').css('background-color', 'lightgreen');
        }
      });
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });
});

      <input type="checkbox" id="J15000001" scanid="1000000103" onclick="call()" disabled="disabled" value="1000000103" class="ELOchecked">

      <input type="checkbox" id="J15000012" scanid="1000000107" disabled="disabled" value="1000000107" class="ELR">


问:
How to only pass non-empty variables as function parameters?
I have a function that will always receive 3 arguments; at least one arg will have a value, but one or more may not. After working with the arguments in this function, I need to send only the arguments with values to another function. Furthermore, the second function needs at least 2 args, so I only want to execute it if at least 2 of my args have a value. What is the best way to accomplish this?

Here is an example of my code structure:

```<code>function doSomething(arg1, arg2, arg3) {
    // Do something with args

    // Only want to send args with values to this function (min 2 args)
    return doSomethingElse(arg1, arg2, arg3);

}
</code>```

Edit: The second function, doSomethingElse(), can receive any number of args with a minimum of 2.

答:
i hope that help you.</p>

```<code>function doSomething() {
    // Do something with args
    if(arguments.length==0){
      console.error("this function should have a param");return;
    }
    var args = [];
      for (var i = 0; i < arguments.length; i++) {
          console.log("argument number " + i + " : "  + arguments[i]); args.push(arguments[i]);
    }
    // Only want to send args with values to this function (min 2 args)
    return doSomethingElse(args);

}
function doSomethingElse(){
    for (var i = 0; i < arguments.length; i++) {
          console.log("argument number " + i + " : "  + arguments[i]);
    }
}
</code>```

Body:
I have a function that will always receive 3 arguments; at least one arg will have a value, but one or more may not. After working with the arguments in this function, I need to send only the arguments with values to another function. Furthermore, the second function needs at least 2 args, so I only want to execute it if at least 2 of my args have a value. What is the best way to accomplish this?

Here is an example of my code structure:

function doSomething(arg1, arg2, arg3) {
    // Do something with args

    // Only want to send args with values to this function (min 2 args)
    return doSomethingElse(arg1, arg2, arg3);

}

Edit: The second function, doSomethingElse(), can receive any number of args with a minimum of 2.

Body:
i hope that help you.

function doSomething() {
    // Do something with args
    if(arguments.length==0){
      console.error("this function should have a param");return;
    }
    var args = [];
      for (var i = 0; i < arguments.length; i++) {
          console.log("argument number " + i + " : "  + arguments[i]); args.push(arguments[i]);
    }
    // Only want to send args with values to this function (min 2 args)
    return doSomethingElse(args);

}
function doSomethingElse(){
    for (var i = 0; i < arguments.length; i++) {
          console.log("argument number " + i + " : "  + arguments[i]);
    }
}


问:
cytoscape.js how to create a graph with weights for implement Dijkstra
I am trying to create a graph with nodes and edges from scracth. I am creating nodes and edges like in the codes below but I can not see anything on the page. Please help. Here is my html and codes in it. I want to use Dijsktra adding weights to edges but until now, I can not see anything on the browser

```<code>    <html>

    <head>
         <title>Tutorial 1: Getting Started</title>
         <script src="cytoscape.js"></script>
    </head>

   <style>
         #cy {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0px;
            left: 0px;
         }
    </style>

    <body>
         <div id="cy"></div>
         <script>
           var cy = cytoscape({
           container: document.getElementById('cy'),
            elements: [
      { data: { id: 'a' } },
      { data: { id: 'b' } },
      { data: { id: 'c' } },
      { data: { id: 'd' } },
      { data: { id: 'e' } },
      {
        data: {
          id: 'ab',
          source: 'a',
          target: 'b'
        }
        data: {
          id: 'da',
          source: 'b',
          target: 'd'
        }
        data: {
          id: 'bd',
          source: 'b',
          target: 'd'
        }
        data: {
          id: 'eb',
          source: 'e',
          target: 'b'
        }
        data: {
          id: 'ba',
          source: 'b',
          target: 'a'
        }
        data: {
          id: 'ed',
          source: 'e',
          target: 'd'
        }
        data: {
          id: 'ce',
          source: 'c',
          target: 'e'
        }
        data: {
          id: 'bc',
          source: 'b',
          target: 'c'
        }
      }]
  });
</script>
</code>```

enter code here

答:
Your body and html tags aren't closed, for one.  The Cytoscape tutorials assume basic understanding of HTML, CSS, and JS.  If you're having trouble with the basic getting started tutorial, then I suggest reviewing the Mozilla web tutorials first.

Things to keep in mind:

Make sure your tags are balanced.

Make sure your external (e.g. script) refs are correct.

You can't do proper web dev without running a web server, e.g. http-server.

It's easier to start from an example file in a tutorial verbatim, rather than trying to change things first.

The code for the demos at the top of the docs site can also be good starting points.

Body:
I am trying to create a graph with nodes and edges from scracth. I am creating nodes and edges like in the codes below but I can not see anything on the page. Please help. Here is my html and codes in it. I want to use Dijsktra adding weights to edges but until now, I can not see anything on the browser

         <title>Tutorial 1: Getting Started</title>

enter code here


问:
What's the easiest way to create an Excel table with C#?
I have some tabular data that I'd like to turn into an Excel table.

Software available:

.NET 4 (C#)

Excel 2010 (using the Excel API is OK)

I prefer not to use any 3rd party libraries

Information about the data:

A couple million rows

5 columns, all strings (very simple and regular table structure)

In my script I'm currently using a nested List data structure but I can change that

Performance of the script is not critical

Searching online gives many results, and I'm confused whether I should use OleDb, ADO RecordSets, or something else. Some of these technologies seem like overkill for my scenario, and some seem like they might be obsolete.

What is the very simplest way to do this?

Edit: this is a one-time script I intend to run from my attended desktop.

答:
I agree that a 3rd party dll would be cleaner than the com, but if you go the interop route...

Hands down the best way to populate an excel sheet is to first put the data in a 2 dimensional string array, then get an excel range object with the same dimensions and set it (range.set_value2(oarray) I think).  Using any other method is hideously slow.

Also be sure you use the appropriate cleanup code in your finally block.

ContentLicense: CC BY-SA 2.5


问:
Executing function when disconnecting bluetooth
I'm having a problem involving my android app and an arduino board. I installed an app that searches for available bluetooth devices and connects to them, now I want when the devices disconnect a notification is sent to the mobile device ... Anyone know how to do this function ???

ConnectionThread:

```<code> public class ConnectionThread extends Thread {

BluetoothSocket btSocket = null;
BluetoothServerSocket btServerSocket = null;
InputStream input = null;
OutputStream output = null;
String btDevAddress = null;
String myUUID = "00001101-0000-1000-8000-00805F9B34FB";
boolean server;
boolean running = false;

/*  Este construtor prepara o dispositivo para atuar como servidor.
 */
public ConnectionThread() {

    this.server = true;
}

/*  Este construtor prepara o dispositivo para atuar como cliente.
    Tem como argumento uma string contendo o endereço MAC do dispositivo
Bluetooth para o qual deve ser solicitada uma conexão.
 */
public ConnectionThread(String btDevAddress) {

    this.server = false;
    this.btDevAddress = btDevAddress;
}

/*  O método run() contem as instruções que serão efetivamente realizadas
em uma nova thread.
 */
public void run() {

    /*  Anuncia que a thread está sendo executada.
        Pega uma referência para o adaptador Bluetooth padrão.
     */
    this.running = true;
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    /*  Determina que ações executar dependendo se a thread está configurada
    para atuar como servidor ou cliente.
     */
    if(this.server) {

        /*  Servidor.
         */
        try {

            /*  Cria um socket de servidor Bluetooth.
                O socket servidor será usado apenas para iniciar a conexão.
                Permanece em estado de espera até que algum cliente
            estabeleça uma conexão.
             */
            btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord("AWC", UUID.fromString(myUUID));
            btSocket = btServerSocket.accept();

            /*  Se a conexão foi estabelecida corretamente, o socket
            servidor pode ser liberado.
             */
            if(btSocket != null) {

                btServerSocket.close();
            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }

    } else {

        /*  Cliente.
         */
        try {

            /*  Obtem uma representação do dispositivo Bluetooth com
            endereço btDevAddress.
                Cria um socket Bluetooth.
             */
            BluetoothDevice btDevice = btAdapter.getRemoteDevice(btDevAddress);
            btSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));

            /*  Envia ao sistema um comando para cancelar qualquer processo
            de descoberta em execução.
             */
            btAdapter.cancelDiscovery();

            /*  Solicita uma conexão ao dispositivo cujo endereço é
            btDevAddress.
                Permanece em estado de espera até que a conexão seja
            estabelecida.
             */
            if (btSocket != null)
                btSocket.connect();

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }

    }

    /*  Pronto, estamos conectados! Agora, só precisamos gerenciar a conexão.
        ...
     */

    if(btSocket != null) {

        /*  Envia um código para a Activity principal informando que a
        a conexão ocorreu com sucesso.
         */
        toMainActivity("---S".getBytes());

        try {

            /*  Obtem referências para os fluxos de entrada e saída do
            socket Bluetooth.
             */
            input = btSocket.getInputStream();
            output = btSocket.getOutputStream();

            /*  Cria um byte array para armazenar temporariamente uma
            mensagem recebida.
                O inteiro bytes representará o número de bytes lidos na
            última mensagem recebida.
             */
            byte[] buffer = new byte[1024];
            int bytes;

            /*  Permanece em estado de espera até que uma mensagem seja
            recebida.
                Armazena a mensagem recebida no buffer.
                Envia a mensagem recebida para a Activity principal, do
            primeiro ao último byte lido.
                Esta thread permanecerá em estado de escuta até que
            a variável running assuma o valor false.
             */
            while(running) {

                bytes = input.read(buffer);
                toMainActivity(Arrays.copyOfRange(buffer, 0, bytes));

            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }
    }

}

/*  Utiliza um handler para enviar um byte array à Activity principal.
    O byte array é encapsulado em um Bundle e posteriormente em uma Message
antes de ser enviado.
 */
private void toMainActivity(byte[] data) {

    Message message = new Message();
    Bundle bundle = new Bundle();
    bundle.putByteArray("data", data);
    message.setData(bundle);
    MainActivity.handler.sendMessage(message);
}

/*  Método utilizado pela Activity principal para transmitir uma mensagem ao
 outro lado da conexão.
    A mensagem deve ser representada por um byte array.
 */
public void write(byte[] data) {

    if(output != null) {
        try {

            /*  Transmite a mensagem.
             */
            output.write(data);

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {

        /*  Envia à Activity principal um código de erro durante a conexão.
         */
        toMainActivity("---N".getBytes());
    }
}

/*  Método utilizado pela Activity principal para encerrar a conexão
 */
public void cancel() {

    try {

        running = false;
        btServerSocket.close();
        btSocket.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    running = false;
}
</code>```

Main Activity:

```<code> public class MainActivity extends AppCompatActivity {

public static int ENABLE_BLUETOOTH = 1;
public static int SELECT_PAIRED_DEVICE = 2;
public static int SELECT_DISCOVERED_DEVICE = 3;

static TextView statusMessage;
static TextView textSpace;
ConnectionThread connect;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    statusMessage = (TextView) findViewById(R.id.statusMessage);
    textSpace = (TextView) findViewById(R.id.textSpace);

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter == null) {
        statusMessage.setText("Que pena! Hardware Bluetooth não está funcionando :(");
    } else {
        statusMessage.setText("Ótimo! Hardware Bluetooth está funcionando :)");
        if(!btAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH);
            statusMessage.setText("Solicitando ativação do Bluetooth...");

        } else {
            statusMessage.setText("Bluetooth já ativado :)");
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == ENABLE_BLUETOOTH) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Bluetooth ativado :D");
        }
        else {
            statusMessage.setText("Bluetooth não ativado :(");
        }
    }
    else if(requestCode == SELECT_PAIRED_DEVICE || requestCode == SELECT_DISCOVERED_DEVICE) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Você selecionou " + data.getStringExtra("btDevName") + "\n"
                    + data.getStringExtra("btDevAddress"));

            connect = new ConnectionThread(data.getStringExtra("btDevAddress"));
            connect.start();
        }
        else {
            statusMessage.setText("Nenhum dispositivo selecionado :(");
        }
    }
}

public void discoverDevices(View view) {

    Intent searchPairedDevicesIntent = new Intent(this, DiscoveredDevices.class);
    startActivityForResult(searchPairedDevicesIntent, SELECT_DISCOVERED_DEVICE);
}

public void enableVisibility(View view) {

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
    startActivity(discoverableIntent);
}

public void waitConnection(View view) {

    connect = new ConnectionThread();
    connect.start();
}

public void sendMessage(View view) {

    EditText messageBox = (EditText) findViewById(R.id.editText_MessageBox);
    String messageBoxString = messageBox.getText().toString();
    byte[] data =  messageBoxString.getBytes();
    connect.write(data);
}

@SuppressLint("HandlerLeak")
public static Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray("data");
        String dataString= new String(data);

        if(dataString.equals("---N"))
            statusMessage.setText("Ocorreu um erro durante a conexão D:");
        else if(dataString.equals("---S"))
            statusMessage.setText("Conectado :D");
        else {

           // textSpace.setText(new String(data));
        }
    }
};
 ***function I want to perform***

public void alarme(){
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setContentTitle("My notification")
                    .setContentText("Hello World!");

    Intent resultIntent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());
}

}
</code>```

答: I have solved this issue, Problem is when bluetooth connection is lost, then how you send notification ? So, solution is your android phone ping to bluetooth device everything 10 seconds or 5 seconds, bluetooth device will receive this ping and send response back to your android phone. if your phone gets response, then its working, if your phone does not get response. then you should show user that device is disconnected. </p>

Body:
I'm having a problem involving my android app and an arduino board. I installed an app that searches for available bluetooth devices and connects to them, now I want when the devices disconnect a notification is sent to the mobile device ... Anyone know how to do this function ???

ConnectionThread:

 public class ConnectionThread extends Thread {

BluetoothSocket btSocket = null;
BluetoothServerSocket btServerSocket = null;
InputStream input = null;
OutputStream output = null;
String btDevAddress = null;
String myUUID = "00001101-0000-1000-8000-00805F9B34FB";
boolean server;
boolean running = false;

/*  Este construtor prepara o dispositivo para atuar como servidor.
 */
public ConnectionThread() {

    this.server = true;
}

/*  Este construtor prepara o dispositivo para atuar como cliente.
    Tem como argumento uma string contendo o endereço MAC do dispositivo
Bluetooth para o qual deve ser solicitada uma conexão.
 */
public ConnectionThread(String btDevAddress) {

    this.server = false;
    this.btDevAddress = btDevAddress;
}

/*  O método run() contem as instruções que serão efetivamente realizadas
em uma nova thread.
 */
public void run() {

    /*  Anuncia que a thread está sendo executada.
        Pega uma referência para o adaptador Bluetooth padrão.
     */
    this.running = true;
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    /*  Determina que ações executar dependendo se a thread está configurada
    para atuar como servidor ou cliente.
     */
    if(this.server) {

        /*  Servidor.
         */
        try {

            /*  Cria um socket de servidor Bluetooth.
                O socket servidor será usado apenas para iniciar a conexão.
                Permanece em estado de espera até que algum cliente
            estabeleça uma conexão.
             */
            btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord("AWC", UUID.fromString(myUUID));
            btSocket = btServerSocket.accept();

            /*  Se a conexão foi estabelecida corretamente, o socket
            servidor pode ser liberado.
             */
            if(btSocket != null) {

                btServerSocket.close();
            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }

    } else {

        /*  Cliente.
         */
        try {

            /*  Obtem uma representação do dispositivo Bluetooth com
            endereço btDevAddress.
                Cria um socket Bluetooth.
             */
            BluetoothDevice btDevice = btAdapter.getRemoteDevice(btDevAddress);
            btSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));

            /*  Envia ao sistema um comando para cancelar qualquer processo
            de descoberta em execução.
             */
            btAdapter.cancelDiscovery();

            /*  Solicita uma conexão ao dispositivo cujo endereço é
            btDevAddress.
                Permanece em estado de espera até que a conexão seja
            estabelecida.
             */
            if (btSocket != null)
                btSocket.connect();

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }

    }

    /*  Pronto, estamos conectados! Agora, só precisamos gerenciar a conexão.
        ...
     */

    if(btSocket != null) {

        /*  Envia um código para a Activity principal informando que a
        a conexão ocorreu com sucesso.
         */
        toMainActivity("---S".getBytes());

        try {

            /*  Obtem referências para os fluxos de entrada e saída do
            socket Bluetooth.
             */
            input = btSocket.getInputStream();
            output = btSocket.getOutputStream();

            /*  Cria um byte array para armazenar temporariamente uma
            mensagem recebida.
                O inteiro bytes representará o número de bytes lidos na
            última mensagem recebida.
             */
            byte[] buffer = new byte[1024];
            int bytes;

            /*  Permanece em estado de espera até que uma mensagem seja
            recebida.
                Armazena a mensagem recebida no buffer.
                Envia a mensagem recebida para a Activity principal, do
            primeiro ao último byte lido.
                Esta thread permanecerá em estado de escuta até que
            a variável running assuma o valor false.
             */
            while(running) {

                bytes = input.read(buffer);
                toMainActivity(Arrays.copyOfRange(buffer, 0, bytes));

            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }
    }

}

/*  Utiliza um handler para enviar um byte array à Activity principal.
    O byte array é encapsulado em um Bundle e posteriormente em uma Message
antes de ser enviado.
 */
private void toMainActivity(byte[] data) {

    Message message = new Message();
    Bundle bundle = new Bundle();
    bundle.putByteArray("data", data);
    message.setData(bundle);
    MainActivity.handler.sendMessage(message);
}

/*  Método utilizado pela Activity principal para transmitir uma mensagem ao
 outro lado da conexão.
    A mensagem deve ser representada por um byte array.
 */
public void write(byte[] data) {

    if(output != null) {
        try {

            /*  Transmite a mensagem.
             */
            output.write(data);

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {

        /*  Envia à Activity principal um código de erro durante a conexão.
         */
        toMainActivity("---N".getBytes());
    }
}

/*  Método utilizado pela Activity principal para encerrar a conexão
 */
public void cancel() {

    try {

        running = false;
        btServerSocket.close();
        btSocket.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    running = false;
}

Main Activity:

 public class MainActivity extends AppCompatActivity {

public static int ENABLE_BLUETOOTH = 1;
public static int SELECT_PAIRED_DEVICE = 2;
public static int SELECT_DISCOVERED_DEVICE = 3;

static TextView statusMessage;
static TextView textSpace;
ConnectionThread connect;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    statusMessage = (TextView) findViewById(R.id.statusMessage);
    textSpace = (TextView) findViewById(R.id.textSpace);

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter == null) {
        statusMessage.setText("Que pena! Hardware Bluetooth não está funcionando :(");
    } else {
        statusMessage.setText("Ótimo! Hardware Bluetooth está funcionando :)");
        if(!btAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH);
            statusMessage.setText("Solicitando ativação do Bluetooth...");

        } else {
            statusMessage.setText("Bluetooth já ativado :)");
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == ENABLE_BLUETOOTH) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Bluetooth ativado :D");
        }
        else {
            statusMessage.setText("Bluetooth não ativado :(");
        }
    }
    else if(requestCode == SELECT_PAIRED_DEVICE || requestCode == SELECT_DISCOVERED_DEVICE) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Você selecionou " + data.getStringExtra("btDevName") + "\n"
                    + data.getStringExtra("btDevAddress"));

            connect = new ConnectionThread(data.getStringExtra("btDevAddress"));
            connect.start();
        }
        else {
            statusMessage.setText("Nenhum dispositivo selecionado :(");
        }
    }
}

public void discoverDevices(View view) {

    Intent searchPairedDevicesIntent = new Intent(this, DiscoveredDevices.class);
    startActivityForResult(searchPairedDevicesIntent, SELECT_DISCOVERED_DEVICE);
}

public void enableVisibility(View view) {

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
    startActivity(discoverableIntent);
}

public void waitConnection(View view) {

    connect = new ConnectionThread();
    connect.start();
}

public void sendMessage(View view) {

    EditText messageBox = (EditText) findViewById(R.id.editText_MessageBox);
    String messageBoxString = messageBox.getText().toString();
    byte[] data =  messageBoxString.getBytes();
    connect.write(data);
}

@SuppressLint("HandlerLeak")
public static Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray("data");
        String dataString= new String(data);

        if(dataString.equals("---N"))
            statusMessage.setText("Ocorreu um erro durante a conexão D:");
        else if(dataString.equals("---S"))
            statusMessage.setText("Conectado :D");
        else {

           // textSpace.setText(new String(data));
        }
    }
};
 ***function I want to perform***

public void alarme(){
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setContentTitle("My notification")
                    .setContentText("Hello World!");

    Intent resultIntent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());
}

}


问:
Mongoose Schema calling Itself is not getting _id
So I am trying to create a mongoose schema that is an item.  That item might have sub items underneath.  Example:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    description: { en_US: String },
    title: { en_US: String },
    subtitle: { en_US: String },
    type: String,
    value: Schema.Types.Mixed,
    items: [{type: Schema.Types.Object, ref: 'ItemSchema'}]
});

module.exports = mongoose.model('Item', ItemSchema);
</code>```

When I call the code the and pass the item object json that looks like this:

```<code>"items": [{
            "type": "photo",
            "title": {
                "en_US": "Add Photo"
            }
        },
        {
            "required": true,
            "type": "list",
            "title": {
                "en_US": "Select Type of Call"
            },
            "items": [{
                    "type": "list_option",
                    "title": {
                        "en_US": "Homework Help"
                    }
                },
                {
                    "type": "list_option",
                    "title": {
                        "en_US": "Not Available"
                    }
                }
            ]
        }]
</code>```

The photo and list Items get an _id but not the others... Here is the result:

```<code> "items": [
        {
            "type": "photo",
            "_id": "5a1d99f5ceec230014b83d81",
            "items": [],
            "title": {
                "en_US": "Add Photo"
            }
        },
        {
            "type": "list",
            "_id": "5a1d99f5ceec230014b83d80",
            "items": [
                {
                    "title": {
                        "en_US": "Homework Help"
                    },
                    "type": "list_option"
                },
                {
                    "title": {
                        "en_US": "Not Available"
                    },
                    "type": "list_option"
                }
            ]
         }]
</code>```

I will never know how many sub-items there will be or it can go as far as 10 levels deep of sub-items (ex. car-ford-compact-escort (each a different sub level)).  How can I get the items to create _ids for all the sub-items it has?

Thanks for your help.

答:
OK I found a way around this.  So first off the data was coming to the function as a single object with multiple items inside it.  What I had to do was write a function that created the looping action with a mongoose schema that included _id.  Here is how the mongoose schema looked:

```<code>var ItemSchema = new Schema({
    _id: Schema.Types.ObjectId,
    description: { en_US: String },
    title: { en_US: String },
    type: String,
    value: Schema.Types.Mixed,
    items: [{type: Schema.Types.Object, ref: 'ItemSchema'}]
});
</code>```

Now when I saved the data I could not just save the whole items object at once.  Instead I need to walk though the items and save each one separate like this:

```<code>function nextItem(item){
    var saveItem = Item({
        _id: new mongoose.Types.ObjectId,
        description: item.description,
        title: item.title,
        type: item.type,
        value: item.value
    });

    var fullItem = saveItem;

    if(item.items){
        fullItem.items = [];
        item.items.forEach(function(item){
             var tempItem = newItem(item);
             fullItem.items.push(tempItem);
        });
        return fullItem
    } else {
        return fullItem
    }
}
</code>```

this would create the correct Items object and with _ids that were unique so I could search for them later.  It even allowed me to do the same thing to items arrays inside other objects and save the parent object with the correct item _ids.  I hope this can help someone else also.

Body:
So I am trying to create a mongoose schema that is an item.  That item might have sub items underneath.  Example:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    description: { en_US: String },
    title: { en_US: String },
    subtitle: { en_US: String },
    type: String,
    value: Schema.Types.Mixed,
    items: [{type: Schema.Types.Object, ref: 'ItemSchema'}]
});

module.exports = mongoose.model('Item', ItemSchema);

When I call the code the and pass the item object json that looks like this:

"items": [{
            "type": "photo",
            "title": {
                "en_US": "Add Photo"
            }
        },
        {
            "required": true,
            "type": "list",
            "title": {
                "en_US": "Select Type of Call"
            },
            "items": [{
                    "type": "list_option",
                    "title": {
                        "en_US": "Homework Help"
                    }
                },
                {
                    "type": "list_option",
                    "title": {
                        "en_US": "Not Available"
                    }
                }
            ]
        }]

The photo and list Items get an _id but not the others... Here is the result:

 "items": [
        {
            "type": "photo",
            "_id": "5a1d99f5ceec230014b83d81",
            "items": [],
            "title": {
                "en_US": "Add Photo"
            }
        },
        {
            "type": "list",
            "_id": "5a1d99f5ceec230014b83d80",
            "items": [
                {
                    "title": {
                        "en_US": "Homework Help"
                    },
                    "type": "list_option"
                },
                {
                    "title": {
                        "en_US": "Not Available"
                    },
                    "type": "list_option"
                }
            ]
         }]

I will never know how many sub-items there will be or it can go as far as 10 levels deep of sub-items (ex. car-ford-compact-escort (each a different sub level)).  How can I get the items to create _ids for all the sub-items it has?

Thanks for your help.

Body:
OK I found a way around this.  So first off the data was coming to the function as a single object with multiple items inside it.  What I had to do was write a function that created the looping action with a mongoose schema that included _id.  Here is how the mongoose schema looked:

var ItemSchema = new Schema({
    _id: Schema.Types.ObjectId,
    description: { en_US: String },
    title: { en_US: String },
    type: String,
    value: Schema.Types.Mixed,
    items: [{type: Schema.Types.Object, ref: 'ItemSchema'}]
});

Now when I saved the data I could not just save the whole items object at once.  Instead I need to walk though the items and save each one separate like this:

function nextItem(item){
    var saveItem = Item({
        _id: new mongoose.Types.ObjectId,
        description: item.description,
        title: item.title,
        type: item.type,
        value: item.value
    });

    var fullItem = saveItem;

    if(item.items){
        fullItem.items = [];
        item.items.forEach(function(item){
             var tempItem = newItem(item);
             fullItem.items.push(tempItem);
        });
        return fullItem
    } else {
        return fullItem
    }
}

this would create the correct Items object and with _ids that were unique so I could search for them later.  It even allowed me to do the same thing to items arrays inside other objects and save the parent object with the correct item _ids.  I hope this can help someone else also.


问:
After creating separate Models and Controllers projects, I get "no suitable method found to override" on my Initialize method declaration
This is driving me insane... I am reorganizing my MVC app into a Models project and a Controllers project, and then the main application as a project.  So, everything is working good so far except...

Whenever I go to "Rebuild" my controllers project, I get this error:

Controllers.AccountController.Initialize(System.Web.Routing.RequestContext)': no suitable method found to override.

Keep in mind that AccountController.cs was automatically placed in my application by Visual Studio, and this was all working fine when the Controllers were within my main project.  I think it might have to do with the ASPNETDB.MDF file that this AccountController.cs file references to authenticate users as they log in, since this database stayed within my main project and didn't follow the Controllers project.  Thoughts on that??

Here's the Initialize method on my AccountController:

```<code>        protected override void Initialize(RequestContext requestContext)
    {
        if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
        if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

        base.Initialize(requestContext);
    }
</code>```

PLEASE HELP!!! Thanks in advance!!

答: It turns out what I was missing was a reference to System.Web.Routing.  I had using System.Web.Routing, and it wasn't marked "red" (meaning, it couldn't find it), so I just assumed it was there.  So this fixed the problem.

Body:
This is driving me insane... I am reorganizing my MVC app into a Models project and a Controllers project, and then the main application as a project.  So, everything is working good so far except...

Whenever I go to "Rebuild" my controllers project, I get this error:

Controllers.AccountController.Initialize(System.Web.Routing.RequestContext)': no suitable method found to override.

Keep in mind that AccountController.cs was automatically placed in my application by Visual Studio, and this was all working fine when the Controllers were within my main project.  I think it might have to do with the ASPNETDB.MDF file that this AccountController.cs file references to authenticate users as they log in, since this database stayed within my main project and didn't follow the Controllers project.  Thoughts on that??

Here's the Initialize method on my AccountController:

        protected override void Initialize(RequestContext requestContext)
    {
        if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
        if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

        base.Initialize(requestContext);
    }

PLEASE HELP!!! Thanks in advance!!


问:
r: Blank graph when plotting multiple lines on scatterplot
My goal is to produce a graph showing the differences between regression lines using continuous vs categorical variables.  I'm using is the "SleepStudy" dataset from Lock5Data, and I want to show the regression lines predicting GPA from ClassYear as either continuous or categorical.  The code is below:

```<code>library(Lock5Data)
data("SleepStudy")
fit2 <- lm(GPA ~ factor(ClassYear), data = SleepStudy)
fit2_line <- aggregate(fit2$fitted.values ~ SleepStudy$ClassYear, FUN = mean)
colnames(fit2_line) <- c('ClassYear','GPA')

options(repr.plot.width=5, repr.plot.height=5)
library(ggplot2)
ggplot() +
    geom_line(data=fit2_line, aes(x=ClassYear, y=GPA)) + # Fit line, ClassYear factor
    geom_smooth(data=SleepStudy, method='lm', formula=GPA~ClassYear) + # Fit line, ClassYear continuous
    geom_point(data=SleepStudy, aes(x=ClassYear, y=GPA)) # Data points as dots
</code>```

What is producing the blank graph?  What am I missing here?

答:
You have to define the data you are using for the geom_smooth in the ggplot(). This code works:

```<code>ggplot(data=SleepStudy, aes(y = GPA,x = ClassYear)) +
  geom_smooth(data=SleepStudy, method='lm', formula=y~x)+
  geom_line(data=fit2_line, aes(x=ClassYear, y=GPA)) +
  geom_point(data=SleepStudy, aes(x=ClassYear, y=GPA))
</code>```

Body:
My goal is to produce a graph showing the differences between regression lines using continuous vs categorical variables.  I'm using is the "SleepStudy" dataset from Lock5Data, and I want to show the regression lines predicting GPA from ClassYear as either continuous or categorical.  The code is below:

library(Lock5Data)
data("SleepStudy")
fit2 <- lm(GPA ~ factor(ClassYear), data = SleepStudy)
fit2_line <- aggregate(fit2$fitted.values ~ SleepStudy$ClassYear, FUN = mean)
colnames(fit2_line) <- c('ClassYear','GPA')

options(repr.plot.width=5, repr.plot.height=5)
library(ggplot2)
ggplot() +
    geom_line(data=fit2_line, aes(x=ClassYear, y=GPA)) + # Fit line, ClassYear factor
    geom_smooth(data=SleepStudy, method='lm', formula=GPA~ClassYear) + # Fit line, ClassYear continuous
    geom_point(data=SleepStudy, aes(x=ClassYear, y=GPA)) # Data points as dots

What is producing the blank graph?  What am I missing here?

Body:
You have to define the data you are using for the geom_smooth in the ggplot(). This code works:

ggplot(data=SleepStudy, aes(y = GPA,x = ClassYear)) +
  geom_smooth(data=SleepStudy, method='lm', formula=y~x)+
  geom_line(data=fit2_line, aes(x=ClassYear, y=GPA)) +
  geom_point(data=SleepStudy, aes(x=ClassYear, y=GPA))


问:
How Apple localize iOs users?
How does Apple define an iOs user localization ?

I am using IP to restict in-app view for non-available in-apps in some territories, but Apple tells me those in-apps are still sold in forbidden countries (in the monthly report).

I guess Apple is using the user store / declared country or something specific to the user, making a difference in their transactions localization en mine.

答: Actually Apple is using the users stores to geolocalize them.</p>

Title: How Apple localize iOs users?


答:
you should use

```<code>("#J15000012").prop("disabled",false);
</code>```

to check the checkbox rather than using the .removeAttr as it does not set the value to false as of jquery 3

Title: jQuery checkbox disable and add class

Body:
you should use

("#J15000012").prop("disabled",false);

to check the checkbox rather than using the .removeAttr as it does not set the value to false as of jquery 3


问:
React/Redux controlled input with validation
Lets imagine we want an input for a "product" (stored in redux) price value.

I'm struggle to come up with the best way to handle input constraints.  For simplicity, lets just focus on the constraint that product.price cannot be empty.

It seems like the 2 options are:

1: Controlled

Implementation: The input value is bound to product.price. On change dispatches the changePrice() action.

The main issue here is that if we want to prevent an empty price from entering the product store, we essentially block the user from clearing the input field.  This isn't ideal as it makes it very hard to change the first digit of the number (you have to select it and replace it)!

2: Using defaultValue

Implementation: We set the price initially using input defaultValue, that allows us to control when we want to actually dispatch changePrice() actions and we can do validation handling in the onChange handler.

This works well, unless the product.price is ever updated from somewhere other than the input change event (for example, an applyDiscount action).  Since defaultValue doesn't cause rerenders, the product.price and the input are now out of sync!

So what am I missing?

There must be a simple & elegant solution to this problem but I just can't seem to find it!

答:
So I think I've figure out a decent solution.  Basically I needed to:

Create separate component that can control the input with local state.

Pass an onChange handler into the props that I can use to dispatch my changePrice action conditionally

Use componentWillReceiveProps to keep the local value state in sync with the redux store

Code (simplified and in typescript):

```<code>interface INumberInputProps {
  value: number;
  onChange: (val: number) => void;
}

interface INumberInputState {
  value: number;
}

export class NumberInput extends React.Component<INumberInputProps, INumberInputState> {

  constructor(props) {
    super(props);
    this.state = {value: props.value};
  }

  public handleChange = (value: number) => {
    this.setState({value});
    this.props.onChange(value);
  }

  //keeps local state in sync with redux store
  public componentWillReceiveProps(props: INumberInputProps){
    if (props.value !== this.state.value) {
      this.setState({value: props.value});
    }
  }

  public render() {
    return <input value={this.state.value} onChange={this.handleChange} />
  }
}
</code>```

In my Product Component:

```<code>  ...
  //conditionally dispatch action if meets valadations
  public handlePriceChange = (price: number) => {
    if (price < this.props.product.standardPrice &&
      price > this.props.product.preferredPrice &&
      !isNaN(price) &&
      lineItem.price !== price){
        this.props.dispatch(updatePrice(this.props.product, price));
    }
  }

  public render() {
     return <NumberInput value={this.props.product.price} onChange={this.handlePriceChange} />
  }
</code>```

...

Body:
So I think I've figure out a decent solution.  Basically I needed to:

Create separate component that can control the input with local state.

Pass an onChange handler into the props that I can use to dispatch my changePrice action conditionally

Use componentWillReceiveProps to keep the local value state in sync with the redux store

Code (simplified and in typescript):

interface INumberInputProps {
  value: number;
  onChange: (val: number) => void;
}

interface INumberInputState {
  value: number;
}

export class NumberInput extends React.Component<INumberInputProps, INumberInputState> {

  constructor(props) {
    super(props);
    this.state = {value: props.value};
  }

  public handleChange = (value: number) => {
    this.setState({value});
    this.props.onChange(value);
  }

  //keeps local state in sync with redux store
  public componentWillReceiveProps(props: INumberInputProps){
    if (props.value !== this.state.value) {
      this.setState({value: props.value});
    }
  }

  public render() {
    return <input value={this.state.value} onChange={this.handleChange} />
  }
}

In my Product Component:

  ...
  //conditionally dispatch action if meets valadations
  public handlePriceChange = (price: number) => {
    if (price < this.props.product.standardPrice &&
      price > this.props.product.preferredPrice &&
      !isNaN(price) &&
      lineItem.price !== price){
        this.props.dispatch(updatePrice(this.props.product, price));
    }
  }

  public render() {
     return <NumberInput value={this.props.product.price} onChange={this.handlePriceChange} />
  }

...


问:
Searching list of words in scrabble with blank tile using Python
I have a scrabble challenge and have the following list of letters:

```<code>letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']
</code>```

And following list of words:

```<code>word = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']
</code>```

Here is the code I'm using to find the words which can be made for a given list of letters:

```<code>def valid_word(word, letters):
    available_letters = letters[:]

    candidate = True

    for letter in word:
        if letter not in available_letters:
            candidate = False
        else:
            available_letters.remove(letter)
    if candidate == True:
        return candidate
</code>```

It gives me output that two words 'yutz' and 'tux' can be made for the current list of letters.

My challenge is what if we replace one of the letter in the list of letters with blank denoted as '_' in the list. For example 't' is replaced by '_' below:

```<code>letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']
</code>```

How can code still be able to find the same words 'yutz' and 'tux' but replace the missing letter? The expected output is 'yu_z' and '_ux'.

UPDATE:

Here is the code which I tried which does not completely work but kind of give direction to where I am going:

```<code>rack_list = []
    for letter in letters:
        if letter in string.ascii_lowercase:
            rack_list.append(letter)
        else:
            blank_count = user_input.count("_")

    def valid_word(word, rack):
    available_letters = rack_list[:]
    missed_counter = 0

    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1
    if missed_counter <= blank_count:
        for i in word:
            if i in available_letters:
                word += i
            else:
                word += "_"
        return word
</code>```

答:
```<code>In [1]: def valid_word(word, rack_list):
 ...:     wrd = [w for w in word]
 ...:     for l in rack_list:
 ...:         try:
 ...:             wrd.remove(l)
 ...:         except:
 ...:             pass
 ...:     return len(wrd) <= ll.count('_')
 ...:
In [2]: valid_word('tux', ['_', 'u', 'v', 'w', 'x', 'y', 'z'])
Out[2]: True

In [3]: valid_word('apple', ['_', 'u', 'v', 'w', 'x', 'y', 'z'])
Out[3]: False
In [4]: valid_word('apple', ['_', 'u', 'v', 'w', 'x', 'y', 'l', 'z', '_', 'p', '_', 'p', 'e'])
Out[4]: True
</code>```

should work for you

Body:
I have a scrabble challenge and have the following list of letters:

letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']

And following list of words:

word = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']

Here is the code I'm using to find the words which can be made for a given list of letters:

def valid_word(word, letters):
    available_letters = letters[:]

    candidate = True

    for letter in word:
        if letter not in available_letters:
            candidate = False
        else:
            available_letters.remove(letter)
    if candidate == True:
        return candidate

It gives me output that two words 'yutz' and 'tux' can be made for the current list of letters.

My challenge is what if we replace one of the letter in the list of letters with blank denoted as '_' in the list. For example 't' is replaced by '_' below:

letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']

How can code still be able to find the same words 'yutz' and 'tux' but replace the missing letter? The expected output is 'yu_z' and '_ux'.

UPDATE:

Here is the code which I tried which does not completely work but kind of give direction to where I am going:

rack_list = []
    for letter in letters:
        if letter in string.ascii_lowercase:
            rack_list.append(letter)
        else:
            blank_count = user_input.count("_")

    def valid_word(word, rack):
    available_letters = rack_list[:]
    missed_counter = 0

    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1
    if missed_counter <= blank_count:
        for i in word:
            if i in available_letters:
                word += i
            else:
                word += "_"
        return word

Body:
In [1]: def valid_word(word, rack_list):
 ...:     wrd = [w for w in word]
 ...:     for l in rack_list:
 ...:         try:
 ...:             wrd.remove(l)
 ...:         except:
 ...:             pass
 ...:     return len(wrd) <= ll.count('_')
 ...:
In [2]: valid_word('tux', ['_', 'u', 'v', 'w', 'x', 'y', 'z'])
Out[2]: True

In [3]: valid_word('apple', ['_', 'u', 'v', 'w', 'x', 'y', 'z'])
Out[3]: False
In [4]: valid_word('apple', ['_', 'u', 'v', 'w', 'x', 'y', 'l', 'z', '_', 'p', '_', 'p', 'e'])
Out[4]: True

should work for you


问:
pytest-xdist results in AttributeError: 'dict' object has no attribute 'style'
Currently using allure-pytest-adaptor 1.7.8, pytest 3.2.1 and pytest-xdist 1.20.0

Having the issue when I use the xdist to run tests in parallel, if I ran tests all in serial, no such issue:

If there is only 1 or no failures, allure report is able to get generated

When there are more than one failures in a test run, allure report cannot be generated, stack trace and error messages:

```<code> File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/bin/py.test", line 11, in <module>
    sys.exit(main())
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/config.py", line 58, in main
    return config.hook.pytest_cmdline_main(config=config)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 745, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 339, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 334, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 614, in execute
    res = hook_impl.function(*args)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/main.py", line 139, in pytest_cmdline_main
    return wrap_session(config, _main)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/main.py", line 133, in wrap_session
    exitstatus=session.exitstatus)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 745, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 339, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 334, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 613, in execute
    return _wrapped_call(hook_impl.function(*args), self.execute)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 250, in _wrapped_call
    wrap_controller.send(call_outcome)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/terminal.py", line 406, in pytest_sessionfinish
    outcome.get_result()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 279, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 265, in __init__
    self.result = func()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 614, in execute
    res = hook_impl.function(*args)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/pytest_plugin.py", line 494, in pytest_sessionfinish
    self.impl._write_xml(f, s)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/common.py", line 254, in _write_xml
    xmlfied.toxml(),
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 129, in toxml
    manys = sum([[(m[0], v) for v in m[1]] for m in entries(Many)], [])
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 123, in entries
    for (name, rule) in items
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 124, in <listcomp>
    if isinstance(rule, clazz) and rule.check(getattr(self, name))]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 109, in value
    values = super(WrappedMany, self).value(name, what)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 103, in value
    return [self.rule.value(name, x) for x in what]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 103, in <listcomp>
    return [self.rule.value(name, x) for x in what]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 92, in value
    return what.toxml()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 128, in toxml
    nested = entries(Nested)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 123, in entries
    for (name, rule) in items
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 124, in <listcomp>
    if isinstance(rule, clazz) and rule.check(getattr(self, name))]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 92, in value
    return what.toxml()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 126, in toxml
    elements = entries(Element)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 123, in entries
    for (name, rule) in items
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 124, in <listcomp>
    if isinstance(rule, clazz) and rule.check(getattr(self, name))]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 80, in value
    return element_maker(self.name or name, self.namespace)(legalize_xml(unicodify(what)))
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/utils.py", line 126, in unicodify
    return text_type(something)  # @UndefinedVariable
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 694, in __str__
    s = self.__unicode__()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 704, in __unicode__
    self.toterminal(tw)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 735, in toterminal
    element[0].toterminal(tw)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 764, in toterminal
    if entry.style == "long":
AttributeError: 'dict' object has no attribute 'style'
</code>```

答:
I was running into the same issue using:

Python 2.7.10

allure-pytest-adaptor 1.7.9

pytest 3.0.0

pytest-xdist 1.20.0

I found this link but am not able to upgrade the plugins and my Python version at present:

https://github.com/pytest-dev/pytest/issues/2811

If the above works for you great but if you find yourself in need of a patch to the problem you are having I have one that may be of use.

The problem (I think) is the way xdist failures interact with pytest and the pytest-allure-adaptor plugin. Combined they send failure output as a dict and not a class object, which the pytest failure ReprTraceback class uses to work with failure output data.

This can be solved by storing test report attributes in an object using the __dict__ object. It turns out that the author already partially addressed this.  I simply updated the existing method within the allure pytest_plugin.py to expose all necessary report data then replaced the intended report finalizer conditionals with the updated method. I have a patch here from a forked version of the plugin:

https://github.com/weeksghost/allure-python/tree/parallel-test-results

I'm sure there are better ways to handle this but it looks like this version of the allure project is no longer supported in favor of an updated version which I feel is a pretty awesome upgrade. I will be upgrading but at my own pace hence the hack.

I hope this is helpful.

Body:
Currently using allure-pytest-adaptor 1.7.8, pytest 3.2.1 and pytest-xdist 1.20.0

Having the issue when I use the xdist to run tests in parallel, if I ran tests all in serial, no such issue:

If there is only 1 or no failures, allure report is able to get generated

When there are more than one failures in a test run, allure report cannot be generated, stack trace and error messages:

 File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/bin/py.test", line 11, in <module>
    sys.exit(main())
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/config.py", line 58, in main
    return config.hook.pytest_cmdline_main(config=config)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 745, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 339, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 334, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 614, in execute
    res = hook_impl.function(*args)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/main.py", line 139, in pytest_cmdline_main
    return wrap_session(config, _main)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/main.py", line 133, in wrap_session
    exitstatus=session.exitstatus)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 745, in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 339, in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 334, in <lambda>
    _MultiCall(methods, kwargs, hook.spec_opts).execute()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 613, in execute
    return _wrapped_call(hook_impl.function(*args), self.execute)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 250, in _wrapped_call
    wrap_controller.send(call_outcome)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/terminal.py", line 406, in pytest_sessionfinish
    outcome.get_result()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 279, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 265, in __init__
    self.result = func()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/vendored_packages/pluggy.py", line 614, in execute
    res = hook_impl.function(*args)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/pytest_plugin.py", line 494, in pytest_sessionfinish
    self.impl._write_xml(f, s)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/common.py", line 254, in _write_xml
    xmlfied.toxml(),
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 129, in toxml
    manys = sum([[(m[0], v) for v in m[1]] for m in entries(Many)], [])
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 123, in entries
    for (name, rule) in items
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 124, in <listcomp>
    if isinstance(rule, clazz) and rule.check(getattr(self, name))]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 109, in value
    values = super(WrappedMany, self).value(name, what)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 103, in value
    return [self.rule.value(name, x) for x in what]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 103, in <listcomp>
    return [self.rule.value(name, x) for x in what]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 92, in value
    return what.toxml()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 128, in toxml
    nested = entries(Nested)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 123, in entries
    for (name, rule) in items
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 124, in <listcomp>
    if isinstance(rule, clazz) and rule.check(getattr(self, name))]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 92, in value
    return what.toxml()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 126, in toxml
    elements = entries(Element)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 123, in entries
    for (name, rule) in items
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 124, in <listcomp>
    if isinstance(rule, clazz) and rule.check(getattr(self, name))]
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/rules.py", line 80, in value
    return element_maker(self.name or name, self.namespace)(legalize_xml(unicodify(what)))
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/allure/utils.py", line 126, in unicodify
    return text_type(something)  # @UndefinedVariable
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 694, in __str__
    s = self.__unicode__()
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 704, in __unicode__
    self.toterminal(tw)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 735, in toterminal
    element[0].toterminal(tw)
  File "/data/jenkins/workspace/Pilot_WebUI_Python_Functional_Test/automated-tests/.tox/jenkins-webui/lib/python3.5/site-packages/_pytest/_code/code.py", line 764, in toterminal
    if entry.style == "long":
AttributeError: 'dict' object has no attribute 'style'


问:
Parameters not being passed into rdlc reports
I am trying to display rdlc reports in c# windows aplication.I am passing parameters to the report by this code-named

```<code> localReport.SetParameters(new ReportParameter[] { new ReportParameter("JobC", m) });
</code>```

I have defined this parameter in the report also. But the parameter is not being passed into the report and the database table is not getting filtered. The first record, though, is being displayed., how to solve this error?

答:
1.Go to the rdlc Design view

2.on the report data view (On the left) select parameters

3.Right click Add

4.set the name (best you Check Allow blank and allow null value)click OK

5.add the textfiled value OR select one from your tablix,right click and select Expression

6.set the expression e.g

```=Parameters!title.Value```
7.In your form that contains your report view add the following lines for a single parameter

```ReportParameter rp = new ReportParameter("title", title); this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp });
           });
            reportViewer1.RefreshReport();```
8.for multiple parameters

``` ReportParameter rp = new ReportParameter("title", title);
 ReportParameter rps  = new ReportParameter("expense", totalExpense.ToString());
 this.reportViewer1.LocalReport.SetParameters(new R`enter code here`eportParameter[] { rp });
 this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rps });
 reportViewer1.RefreshReport();```

Body:
I am trying to display rdlc reports in c# windows aplication.I am passing parameters to the report by this code-named

 localReport.SetParameters(new ReportParameter[] { new ReportParameter("JobC", m) });

I have defined this parameter in the report also. But the parameter is not being passed into the report and the database table is not getting filtered. The first record, though, is being displayed., how to solve this error?

Body:
1.Go to the rdlc Design view

2.on the report data view (On the left) select parameters

3.Right click Add

4.set the name (best you Check Allow blank and allow null value)click OK

5.add the textfiled value OR select one from your tablix,right click and select Expression

6.set the expression e.g

=Parameters!title.Value

7.In your form that contains your report view add the following lines for a single parameter

ReportParameter rp = new ReportParameter("title", title); this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp });
           });
            reportViewer1.RefreshReport();

8.for multiple parameters

 ReportParameter rp = new ReportParameter("title", title);
 ReportParameter rps  = new ReportParameter("expense", totalExpense.ToString());
 this.reportViewer1.LocalReport.SetParameters(new R`enter code here`eportParameter[] { rp });
 this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rps });
 reportViewer1.RefreshReport();