问:
VueJS component display other component content
The objective: Vue component input-address has to be inside Vue component mail-composer and display a list of addresses only when someone click Address Book button. When someone click one of displayed mails  or fill the To field by hand, createdmail.to has to get the value and I have to hide the list of addresses.

Vue component mail-composer. This component receives a list of addresses. (Everything is working here, I think the only part that is not working properly is v-model inside input-address tag)

```<code>Vue.component('mail-composer', {
    props: ['addressesbook'],
    methods: {
      send: function(createmail) {
        this.$emit('send', createmail);
      }

    },
            template:
            `
            <div>
              <input-address :addresses="addressesbook" v-model="createmail.to"></input-address>
              <p><b>Subject: </b><input type="text" v-model="createmail.subject"></input></p>
              <p><b>Body: </b><textarea v-model="createmail.body"></textarea></p>
              <button @click="send(createmail)">Send</button>
            </div>
            `,
            data(){
              return{
                createmail:{
                  to: '',
                  subject: '',
                  body: ''
                }

              }
            }

      });
</code>```

The other Vue component is this one, which is in the same file. (I think all problems are here).

I need to display the list of addresses only when someone click Address Book button, and I have to hide it when someone click again the button or one of the emails which are in the list. When someone clicks a mail from list, the createmail.to property from the mail-composer has to get the value of the mail , also if I decide to put the mail by hand it has to occurs the same.

```<code>Vue.component('input-address',{
        props:["addresses"],
        template:
        `
          <div>
          <label><b>To: </b><input type="text"></input><button @click="!(displayAddressBook)">Address Book</button></label>
          <ul v-if="displayAddressBook">
            <li  v-for="address in addresses">
            {{address}}
            </li>
          </ul>
          </div>
        `,
        data(){
          return{
            displayAddressBook: false
          }
        }

      })
</code>```

答:
There're some errors in your code:

@click="!(displayAddressBook)" should be @click="displayAddressBook = !displayAddressBook" - the first really does nothing (interesting), the second (suggested) sets the value of displayAddressBook to the opposite it has currently.

the input-address component does not really do anything with the input field (missing v-model)

the changes in the child component (input-address) are not sent back to the parent (added a watcher to do that in the child component)

the parent component (mail-composer) has to handle the values emitted from the child (added the @address-change action handler)

the v-for in your input-address component does not have a key set. Added key by using the index for it (not the best solution, but easy to do).

just put createmail.to: {{ createmail.to }} at the end of MailComposer, so you can see how it changes

Suggestions

always use CamelCase for component names - if you get used to it, then you get less "why is it not working?!" moments

watch for typos: createmail doesn't look good - createEmail or just simply createemail would be better (ok, it doesn't look so nice - maybe you should choose a totally different name for that)

Vue.component('InputAddress', {
  props: ["addresses"],
  data() {
    return {
      displayAddressBook: false,
      address: null
    }
  },
  template: `

          To:
            <input
              type="text"
              v-model="address"
            />
            <button
              @click="displayAddressBook = !displayAddressBook"
            >
              Address Book
            </button>

              {{address}}

        `,
  watch: {
    address(newVal) {
      // emitting value to parent on change of the address
      // data attribute
      this.$emit('address-change', newVal)
    }
  },
  methods: {
    clickAddressHandler(address) {
      // handling click on an address in the address book
      this.address = address
      this.displayAddressBook = false
    }
  }
})

Vue.component('MailComposer', {
  props: ['addressesbook'],
  data() {
    return {
      createmail: {
        to: '',
        subject: '',
        body: ''
      }
    }
  },
  methods: {
    send: function(createmail) {
      this.$emit('send', createmail);
    },
    addressChangeHandler(value) {
      this.createmail.to = value
    }
  },
  template: `

              <input-address
                :addresses="addressesbook"
                v-model="createmail.to"
                @address-change="addressChangeHandler"
              />

                Subject:
                <input
                  type="text"
                  v-model="createmail.subject"
                />

                Body:
                <textarea v-model="createmail.body"></textarea>

              <button @click="send(createmail)">Send</button>

              createmail.to: {{ createmail.to }}

            `
});

new Vue({
  el: "#app",
  data: {
    addressesbook: [
      'abcd@abcd.com',
      'fghi@fghi.com'
    ]
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <mail-composer :addressesbook="addressesbook" />
</div></code>```

Body:
The objective: Vue component input-address has to be inside Vue component mail-composer and display a list of addresses only when someone click Address Book button. When someone click one of displayed mails  or fill the To field by hand, createdmail.to has to get the value and I have to hide the list of addresses.

Vue component mail-composer. This component receives a list of addresses. (Everything is working here, I think the only part that is not working properly is v-model inside input-address tag)

Vue.component('mail-composer', {
    props: ['addressesbook'],
    methods: {
      send: function(createmail) {
        this.$emit('send', createmail);
      }

    },
            template:
            `

              <input-address :addresses="addressesbook" v-model="createmail.to"></input-address>

Subject: <input type="text" v-model="createmail.subject"></input>

Body: <textarea v-model="createmail.body"></textarea>

              <button @click="send(createmail)">Send</button>

            `,
            data(){
              return{
                createmail:{
                  to: '',
                  subject: '',
                  body: ''
                }

              }
            }

      });

The other Vue component is this one, which is in the same file. (I think all problems are here).

I need to display the list of addresses only when someone click Address Book button, and I have to hide it when someone click again the button or one of the emails which are in the list. When someone clicks a mail from list, the createmail.to property from the mail-composer has to get the value of the mail , also if I decide to put the mail by hand it has to occurs the same.

Vue.component('input-address',{
        props:["addresses"],
        template:
        `

          To: <input type="text"></input><button @click="!(displayAddressBook)">Address Book</button>

            {{address}}

        `,
        data(){
          return{
            displayAddressBook: false
          }
        }

      })

Body:
There're some errors in your code:

@click="!(displayAddressBook)" should be @click="displayAddressBook = !displayAddressBook" - the first really does nothing (interesting), the second (suggested) sets the value of displayAddressBook to the opposite it has currently.

the input-address component does not really do anything with the input field (missing v-model)

the changes in the child component (input-address) are not sent back to the parent (added a watcher to do that in the child component)

the parent component (mail-composer) has to handle the values emitted from the child (added the @address-change action handler)

the v-for in your input-address component does not have a key set. Added key by using the index for it (not the best solution, but easy to do).

just put createmail.to: {{ createmail.to }} at the end of MailComposer, so you can see how it changes

Suggestions

always use CamelCase for component names - if you get used to it, then you get less "why is it not working?!" moments

watch for typos: createmail doesn't look good - createEmail or just simply createemail would be better (ok, it doesn't look so nice - maybe you should choose a totally different name for that)

Vue.component('InputAddress', {
  props: ["addresses"],
  data() {
    return {
      displayAddressBook: false,
      address: null
    }
  },
  template: `
          <div>
          <label><b>To: </b>
            <input
              type="text"
              v-model="address"
            />
            <button
              @click="displayAddressBook = !displayAddressBook"
            >
              Address Book
            </button>
          </label>
          <ul v-if="displayAddressBook">
            <li
              v-for="(address, i) in addresses"
              :key="i"
              @click="clickAddressHandler(address)"
             >
              {{address}}
            </li>
          </ul>
          </div>
        `,
  watch: {
    address(newVal) {
      // emitting value to parent on change of the address
      // data attribute
      this.$emit('address-change', newVal)
    }
  },
  methods: {
    clickAddressHandler(address) {
      // handling click on an address in the address book
      this.address = address
      this.displayAddressBook = false
    }
  }
})

Vue.component('MailComposer', {
  props: ['addressesbook'],
  data() {
    return {
      createmail: {
        to: '',
        subject: '',
        body: ''
      }
    }
  },
  methods: {
    send: function(createmail) {
      this.$emit('send', createmail);
    },
    addressChangeHandler(value) {
      this.createmail.to = value
    }
  },
  template: `
            <div>
              <input-address
                :addresses="addressesbook"
                v-model="createmail.to"
                @address-change="addressChangeHandler"
              />
              <p>
                <b>Subject: </b>
                <input
                  type="text"
                  v-model="createmail.subject"
                />
              </p>
              <p>
                <b>Body: </b>
                <textarea v-model="createmail.body"></textarea>
              </p>
              <button @click="send(createmail)">Send</button><br />
              createmail.to: {{ createmail.to }}
            </div>
            `
});

new Vue({
  el: "#app",
  data: {
    addressesbook: [
      'abcd@abcd.com',
      'fghi@fghi.com'
    ]
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <mail-composer :addressesbook="addressesbook" />
</div>


来源: stackexchange

问:
Detect if a Tcl script is run in a background process
I'm looking for a preferably cross-platform way to detect from within a Tcl script if the interpreter is running in a foreground or in a background process.

I've seen how to do it via ps (or /proc/$$/stat on Linux); is there a better way or do I have to hack something around that approach? I already have a utility library written in C so exposing the lowlevel API that ps also uses so I don't have to parse process output (or special file content) would be fine.

答:
There's no truly cross-platform notion of foreground, but the main platforms do have ways of doing it according to the notion they have of foreground.

Linux, macOS, and other Unix:

For determining if a process is foreground or not, you need to check if its process group ID is the terminal's controlling process group ID. For Tcl, you'd be looking to surface the getpgrp() and tcgetpgrp() system calls (both POSIX). Tcl has no built-in exposure of either, so you're talking either a compiled extension (may I recommend Critcl for this?) or calling an external program like ps. Fortunately, if you use the latter (a reasonable option if this is just an occasional operation) you can typically condition the output so that you get just the information you want and need to do next to no parsing.

```<code># Tested on macOS, but may work on other platforms
proc isForeground {{pid 0}} {
    try {
        lassign [exec ps -p [expr {$pid ? $pid : [pid]}] -o "pgid=,tpgid="] pgid tpgid
    } on error {} {
        return -code error "no such process"
    }
    # If tpgid is zero, the process is a daemon of some kind
    expr {$pgid == $tpgid  &&  $tpgid != 0}
}
</code>```

Windows

There's code to do it, and the required calls are supported by the TWAPI extension so you don't need to make your own. (WARNING! I've not tested this!)

```<code>package require twapi_ui

proc isForeground {{pid 0}} {
    set forground_pid [get_window_thread [get_foreground_window]]
    return [expr {($pid ? $pid : [pid]) == $foreground_pid}]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There's no truly cross-platform notion of foreground, but the main platforms do have ways of doing it according to the notion they have of foreground.

Linux, macOS, and other Unix:

For determining if a process is foreground or not, you need to check if its process group ID is the terminal's controlling process group ID. For Tcl, you'd be looking to surface the getpgrp() and tcgetpgrp() system calls (both POSIX). Tcl has no built-in exposure of either, so you're talking either a compiled extension (may I recommend Critcl for this?) or calling an external program like ps. Fortunately, if you use the latter (a reasonable option if this is just an occasional operation) you can typically condition the output so that you get just the information you want and need to do next to no parsing.

# Tested on macOS, but may work on other platforms
proc isForeground {{pid 0}} {
    try {
        lassign [exec ps -p [expr {$pid ? $pid : [pid]}] -o "pgid=,tpgid="] pgid tpgid
    } on error {} {
        return -code error "no such process"
    }
    # If tpgid is zero, the process is a daemon of some kind
    expr {$pgid == $tpgid  &&  $tpgid != 0}
}

Windows

There's code to do it, and the required calls are supported by the TWAPI extension so you don't need to make your own. (WARNING! I've not tested this!)

package require twapi_ui

proc isForeground {{pid 0}} {
    set forground_pid [get_window_thread [get_foreground_window]]
    return [expr {($pid ? $pid : [pid]) == $foreground_pid}]
}


问:
Why saved_model_cli works and loading saved_model.pb does not?
I received a new Tensorflow Saved Model today (saved_model.pb + variables/) and I'm trying to predict images with it.

I have no clues about input and output but I can use saved_model_cli show to get some.

Using saved_model_cli, I was able to get prediction for one input image.

saved_model_cli run --dir /path/to/SavedModels/mymodel --signature_def model_signature --tag_set serve --inputs 'input=/path/to/image/as/numpy/image.npy' --outdir=/tmp/out --overwrite

I'm trying to load this model in a Python code but I cannot get the same result.
Here is the code I tried :

```<code>        from tensorflow.core.protobuf import saved_model_pb2
        from tensorflow.python.platform import gfile

        with gfile.FastGFile(model_filename, 'rb') as f:
            data = compat.as_bytes(f.read())
            sm = saved_model_pb2.SavedModel()
            sm.ParseFromString(data)
            if 1 != len(sm.meta_graphs):
                print('More than one graph found. Not sure which to write')
                sys.exit(1)
        tf.compat.v1.import_graph_def(sm.meta_graphs[0].graph_def)

        graph = tf.compat.v1.get_default_graph();
        with graph.as_default():
            session = tf.compat.v1.Session(graph=graph)
            with session.as_default():
                output_tensor = graph.get_tensor_by_name('import/output_tensorname:0')
                image = load('/path/to/numpy/image/image-wxh.npy')
                predictions = self.session.run(output_tensor,{'import/input:0': image})
                print(predictions.shape)
</code>```

When I run this code , I have error messages like

tensorflow.python.framework.errors_impl.FailedPreconditionError: 2 root error(s) found.
  (0) Failed precondition: Error while reading resource variable conv2d_xx/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/conv2d_xx/kernel)

Am I missing something ?

What is the difference with the saved_model_cli ?

答:
Well, this was a problem with the loading of model.

```<code>import tensorflow as tf
import settings
import numpy as np
from PIL import Image
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.framework import convert_to_constants

def get_func_from_saved_model(saved_model_dir):
  saved_model_loaded = tf.saved_model.load(
      saved_model_dir, tags=[tag_constants.SERVING])
  graph_func = saved_model_loaded.signatures['my_model_signature']
  graph_func = convert_to_constants.convert_variables_to_constants_v2(graph_func)
  return graph_func

export_path='/path/to/saved/model'

graph_func =  get_func_from_saved_model(export_path)

path = '/path/to/image/image.png'
img = Image.open(path)
img.show()

img_data = np.array(img).reshape(1,224,224,1)

y_pred = graph_func(tf.convert_to_tensor(img_data))[0].numpy()

</code>```

y_pred contains the same output image as with saved_model_cli script.

Body:
I received a new Tensorflow Saved Model today (saved_model.pb + variables/) and I'm trying to predict images with it.

I have no clues about input and output but I can use saved_model_cli show to get some.

Using saved_model_cli, I was able to get prediction for one input image.

saved_model_cli run --dir /path/to/SavedModels/mymodel --signature_def model_signature --tag_set serve --inputs 'input=/path/to/image/as/numpy/image.npy' --outdir=/tmp/out --overwrite

I'm trying to load this model in a Python code but I cannot get the same result.
Here is the code I tried :

        from tensorflow.core.protobuf import saved_model_pb2
        from tensorflow.python.platform import gfile

        with gfile.FastGFile(model_filename, 'rb') as f:
            data = compat.as_bytes(f.read())
            sm = saved_model_pb2.SavedModel()
            sm.ParseFromString(data)
            if 1 != len(sm.meta_graphs):
                print('More than one graph found. Not sure which to write')
                sys.exit(1)
        tf.compat.v1.import_graph_def(sm.meta_graphs[0].graph_def)

        graph = tf.compat.v1.get_default_graph();
        with graph.as_default():
            session = tf.compat.v1.Session(graph=graph)
            with session.as_default():
                output_tensor = graph.get_tensor_by_name('import/output_tensorname:0')
                image = load('/path/to/numpy/image/image-wxh.npy')
                predictions = self.session.run(output_tensor,{'import/input:0': image})
                print(predictions.shape)

When I run this code , I have error messages like

tensorflow.python.framework.errors_impl.FailedPreconditionError: 2 root error(s) found.
  (0) Failed precondition: Error while reading resource variable conv2d_xx/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/conv2d_xx/kernel)

Am I missing something ?

What is the difference with the saved_model_cli ?

Body:
Well, this was a problem with the loading of model.

import tensorflow as tf
import settings
import numpy as np
from PIL import Image
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.framework import convert_to_constants

def get_func_from_saved_model(saved_model_dir):
  saved_model_loaded = tf.saved_model.load(
      saved_model_dir, tags=[tag_constants.SERVING])
  graph_func = saved_model_loaded.signatures['my_model_signature']
  graph_func = convert_to_constants.convert_variables_to_constants_v2(graph_func)
  return graph_func

export_path='/path/to/saved/model'

graph_func =  get_func_from_saved_model(export_path)

path = '/path/to/image/image.png'
img = Image.open(path)
img.show()

img_data = np.array(img).reshape(1,224,224,1)

y_pred = graph_func(tf.convert_to_tensor(img_data))[0].numpy()

y_pred contains the same output image as with saved_model_cli script.


问:
No executable found for solver 'glpk' on pyomo
I have an optimization model written on pyomo (Python 3.7/Ubuntu 18.04) and using

```<code>from pyomo.opt import SolverFactory
opt = SolverFactory("gurobi")
results = opt.solve(model)
</code>```

It works exactly as it should. However, when I try to use glpk as the solver, I get the following error:

```<code>ApplicationError: No executable found for solver 'glpk'.
</code>```

Importing the package also returns an error:

```<code>ModuleNotFoundError: No module named 'glpk'
</code>```

But when I do conda list on the terminal, I get this information for glpk package:

```<code>glpk                      4.65              he80fd80_1002    conda-forge

</code>```

How can I fix this?

答:
On terminal, trying running which glpsol.

This ought to return a path to your glpsol executable. I am guessing you won't get a result. If that's the case you need to add the location of 'glpsol' to your PATH variable. You should be able to find it by seaching for where the 'glpk' package was installed. It should be in the 'bin' folder. Hopefully.

Body:
I have an optimization model written on pyomo (Python 3.7/Ubuntu 18.04) and using

from pyomo.opt import SolverFactory
opt = SolverFactory("gurobi")
results = opt.solve(model)

It works exactly as it should. However, when I try to use glpk as the solver, I get the following error:

ApplicationError: No executable found for solver 'glpk'.

Importing the package also returns an error:

ModuleNotFoundError: No module named 'glpk'

But when I do conda list on the terminal, I get this information for glpk package:

glpk                      4.65              he80fd80_1002    conda-forge

How can I fix this?


问:
How to limit DBA_AUDIT_TRAIL activity visibility by schema or other possibilities to see activity for targeted schemas
I am asking the DBA to turn on DBA_AUDIT_TRAIL logging and I am getting push back.  In some environments, I see change activity logged when I query this table, in other environments, I do not.

I am only interested in a handful of schemas. In my opinion, if my visibility of this table could be limited to the schemas that I have an interest in tracking, then there might potentially be less resistance to granting me access. What is the best way to grant me access to only the objects in a target schema list? Is there an alternate view that I could be granted access to?

Is there an existing Oracle view that limits row activity to only those objects that a user otherwise has visibility to or do we have to create our own view or more primitively, say, create a view like this

```<code>SELECT * FROM DBA_AUDIT_TRAIL WHERE OWNER IN ('schema1','schema2')
</code>```

and limit SELECT access to the view? I'm not sure if this query is returning no rows in some envs because logging isn't turned on or whether I just don't have the proper access.

答:
While someone could create a view as you suggest, it still wouldn't necessarily limit your access to the main audit trail, as access to the data dictionary in Oracle isn't fine grained. It tends to be all or nothing - so you could have a custom view, but you would still have access to DBA_AUDIT_TRAIL because the "SELECT ANY DICTIONARY" privilege would be required in most environments. The only way I can see that might work is to create the view in a dedicated application schema with the necessary privilege using definer's rights, then grant select access to that view to your account.

That said, auditing itself is very fine grained. If it isn't already enabled and being used by others, then it can be turned on only for what you want to audit, so there wouldn't be a need to create a custom view.

Body:
I am asking the DBA to turn on DBA_AUDIT_TRAIL logging and I am getting push back.  In some environments, I see change activity logged when I query this table, in other environments, I do not.

I am only interested in a handful of schemas. In my opinion, if my visibility of this table could be limited to the schemas that I have an interest in tracking, then there might potentially be less resistance to granting me access. What is the best way to grant me access to only the objects in a target schema list? Is there an alternate view that I could be granted access to?

Is there an existing Oracle view that limits row activity to only those objects that a user otherwise has visibility to or do we have to create our own view or more primitively, say, create a view like this

SELECT * FROM DBA_AUDIT_TRAIL WHERE OWNER IN ('schema1','schema2')

and limit SELECT access to the view? I'm not sure if this query is returning no rows in some envs because logging isn't turned on or whether I just don't have the proper access.


问:
Accessing vector in class
If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

```<code>class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}
</code>```

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.

答:
Create a public function called

std:vector getMyVec() {return my_vec;}

ContentLicense: CC BY-SA 3.0

Title: Accessing vector in class

Body:
If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.


问:
In Python what is the best way to read a pdf table with no outline?
I am trying to read data from a table in a pdf into a pandas dataframe. I am able to do so using tabula-py when the pdf has outlines around the table, but when I try on the pdf without an outline the script produces an error.

For example, I am looking at the pdfs available from two different urls. I have downloaded the pdfs from the urls and saved them as 'JSE Opts.pdf' and 'JSE Divs.pdf' respectively.

```<code>import requests
import pandas as pd

url='https://clientportal.jse.co.za/JSE%20Equity%20Derivatives/Dividends/ED_DividendsReport.pdf'
response = requests.get(url)
fname = 'JSE Divs.pdf'
f= open(fname, 'wb')
f.write(response.content)
f.close()

url='https://clientportal.jse.co.za/JSE%20Equity%20Derivatives/Options%20Daily%20Traded%20Report/ED_OptionsDailyTradedReport.pdf'
response = requests.get(url)
fname = 'JSE Opts.pdf'
f= open(fname, 'wb')
f.write(response.content)
f.close()
</code>```

I am able to read the 'JSE Opts.pdf' into a pandas dataframe using the code:

```<code>import tabula as tb

pdf = './JSE Opts.pdf'
data = tb.read_pdf(pdf,pages = 1)
data = data[0]
print(data)
</code>```

When I try to do the same for 'JSE Divs.pdf', I get errors and tabula-py is only able to read the header:

```<code>pdf = './JSE Divs.pdf'
data = tb.read_pdf(pdf,pages = 1)
data = data[0]
print(data)
</code>```

I suspect that this is because there are no lines around the table. If that is the case, what is the best way to go about reading the data from 'JSE Divs.pdf' into pandas?

答:
I was able to read the data into a string using pdfplumber, save the string as a CSV file (after cleaning the data to suit my needs) and then import into pandas. </p>

```<code>import pdfplumber
pdf = pdfplumber.open("./JSE Divs.pdf")

text = ''
i = 0
while True:
    try:
        text += pdf.pages[i].extract_text() + '\n'
        i = i+1
    except IndexError:
        break

for replace_s in [' DN',' CA1',' ANY',' CSH',' PHY',' QUANTO']:
    text = text.replace(replace_s,'')

while True:
    try:
        idx = text.index('EXO')
        replace_s =text[idx-1:idx+8]
        text = text.replace(replace_s,'')
    except ValueError:
        break

cols ='EXPIRY_s,USYM,EXPIRY,EX_DATE,CUM_PV_DIVS,CUM_DIVS,ISIN,INSTR_ID\n'
text = text[text.index('Div\n')+4:]
text = cols + text
text = text.replace(' ',',')

f = open('divs.csv','w')
f.write(text)
f.close()
</code>```

Body:
I am trying to read data from a table in a pdf into a pandas dataframe. I am able to do so using tabula-py when the pdf has outlines around the table, but when I try on the pdf without an outline the script produces an error.

For example, I am looking at the pdfs available from two different urls. I have downloaded the pdfs from the urls and saved them as 'JSE Opts.pdf' and 'JSE Divs.pdf' respectively.

import requests
import pandas as pd

url='https://clientportal.jse.co.za/JSE%20Equity%20Derivatives/Dividends/ED_DividendsReport.pdf'
response = requests.get(url)
fname = 'JSE Divs.pdf'
f= open(fname, 'wb')
f.write(response.content)
f.close()

url='https://clientportal.jse.co.za/JSE%20Equity%20Derivatives/Options%20Daily%20Traded%20Report/ED_OptionsDailyTradedReport.pdf'
response = requests.get(url)
fname = 'JSE Opts.pdf'
f= open(fname, 'wb')
f.write(response.content)
f.close()

I am able to read the 'JSE Opts.pdf' into a pandas dataframe using the code:

import tabula as tb

pdf = './JSE Opts.pdf'
data = tb.read_pdf(pdf,pages = 1)
data = data[0]
print(data)

When I try to do the same for 'JSE Divs.pdf', I get errors and tabula-py is only able to read the header:

pdf = './JSE Divs.pdf'
data = tb.read_pdf(pdf,pages = 1)
data = data[0]
print(data)

I suspect that this is because there are no lines around the table. If that is the case, what is the best way to go about reading the data from 'JSE Divs.pdf' into pandas?

Body:
I was able to read the data into a string using pdfplumber, save the string as a CSV file (after cleaning the data to suit my needs) and then import into pandas.

import pdfplumber
pdf = pdfplumber.open("./JSE Divs.pdf")

text = ''
i = 0
while True:
    try:
        text += pdf.pages[i].extract_text() + '\n'
        i = i+1
    except IndexError:
        break

for replace_s in [' DN',' CA1',' ANY',' CSH',' PHY',' QUANTO']:
    text = text.replace(replace_s,'')

while True:
    try:
        idx = text.index('EXO')
        replace_s =text[idx-1:idx+8]
        text = text.replace(replace_s,'')
    except ValueError:
        break

cols ='EXPIRY_s,USYM,EXPIRY,EX_DATE,CUM_PV_DIVS,CUM_DIVS,ISIN,INSTR_ID\n'
text = text[text.index('Div\n')+4:]
text = cols + text
text = text.replace(' ',',')

f = open('divs.csv','w')
f.write(text)
f.close()


问:
plotting on the y-axis in Mathematica
I have another question about Wolfram Mathematica. Is there someone that knows how I can plot a graphic on the y axis?

I hope that the figure helps.

答: Depending on how you wanted the axis labels to show, you could just wrap the code for the original Plot in the Rotate function. </p>

Title: plotting on the y-axis in Mathematica


问:
Video modal keeps closing when I try to click on video to play HTML/CSS
I am having an issue implementing video pop up using html/css and bootstrap.

Basically when I click on the link, the modal appears with the video, but the moment I click on the video to play, it closes the modal.

I want it so that the user can play the video and interact with the controls, the moment they click anywhere in the background away from the video, it closes the video.

You can see how it's currently working on our website https://www.metis-online.com/#courses and you will see under 'Explainder Videos' two links that opens up the relevant video models.

HTML:

```<code><h5>Explainer Videos</h5>
<p>Check out our videos below taken from one of our recorded webinars to see if this certification is right for you:
<ul class="nobullet">
<li><a style="text-decoration: underline; color:white;" data-toggle="modal" data-target="#flitpc-video-1">See what our online course looks like</a></li>
<li><a style="text-decoration: underline; color:white;" data-toggle="modal" data-target="#flitpc-video-2">Sample lessons</a></li>
</ul>
<br/>
</p>

<div class="modal fade" id="flitpc-video-1">
   <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content-vid">
         <div class="modal-body">
            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>
         </div>
      </div>
   </div>
</div>

<div class="modal fade" id="flitpc-video-2">
   <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content-vid">
         <div class="modal-body">
            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>
         </div>
      </div>
   </div>
</div>
</code>```

CSS:

```<code>.modal-content-vid{
    background: transparent !important;
    border: none !important;
}
</code>```

答:
Its probably the case of event bubbling

https://javascript.info/bubbling-and-capturing

In short what is happening is you click on video, but event bubbles and reaches to the parent element which has event which closes your popup
So you should stop bubbling,

like

```<code><div class="modal-body" onclick=onModalBodyClick(event)>
    <video id="flitpcdemo" controls autoplay width="100%">
       <source src="./video2.mp4" type="video/mp4">
    </video>
</div>
</code>```

And In JS

```<code>function onModalBodyClick(event) {
    event.stoppropagation();
}
</code>```

Body:
I am having an issue implementing video pop up using html/css and bootstrap.

Basically when I click on the link, the modal appears with the video, but the moment I click on the video to play, it closes the modal.

I want it so that the user can play the video and interact with the controls, the moment they click anywhere in the background away from the video, it closes the video.

You can see how it's currently working on our website https://www.metis-online.com/#courses and you will see under 'Explainder Videos' two links that opens up the relevant video models.

HTML:

Explainer Videos

Check out our videos below taken from one of our recorded webinars to see if this certification is right for you:

See what our online course looks like

Sample lessons

            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>

            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>

CSS:

.modal-content-vid{
    background: transparent !important;
    border: none !important;
}

Body:
Its probably the case of event bubbling

https://javascript.info/bubbling-and-capturing

In short what is happening is you click on video, but event bubbles and reaches to the parent element which has event which closes your popup
So you should stop bubbling,

like

<div class="modal-body" onclick=onModalBodyClick(event)>
    <video id="flitpcdemo" controls autoplay width="100%">
       <source src="./video2.mp4" type="video/mp4">
    </video>
</div>

And In JS

function onModalBodyClick(event) {
    event.stoppropagation();
}


问:
Removing duplicate XML nodes in XSLT
I would appreciated if someone could help me to create xslt to remove duplicates nodes from XML
        based on duplicated element's value(PlayBack--ControlInfo-ControlName).

I want to remove all the duplicate elements(PlayBack--ControlInfo-ControlName) from the GStep/Step

Input XML

```<code><?xml version="1.0" encoding="utf-8"?>
      <Document>
       <Meta>
         <GpsFile>notepad_may_30_file</GpsFile>
         <GpsId>36fa4fe8-9691-4a7f-8bc1-9543f6b7d29a</GpsId>
          <ExePath>
             <ExePath1>C:\WINDOWS\SYSTEM32\notepad.exe</ExePath1>
          </ExePath>
        </Meta>
         <Process>
            <GStep DialogName="Untitled - Notepad">
             <Step DialogName="Untitled - Notepad">
              <Step-ID>3</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>4</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>5</Step-ID>
              <PlayBack--ControlInfo-ControlName>Edit</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>6</Step-ID>
              <PlayBack--ControlInfo-ControlName>Replace...\tCtrl+H</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>12</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>13</Step-ID>
              <PlayBack--ControlInfo-ControlName>Edit</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>14</Step-ID>
              <PlayBack--ControlInfo-ControlName>Replace...\tCtrl+H</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>15</Step-ID>
              <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
            </Step>
          </GStep>
          <GStep DialogName="Replace">
             <Step DialogName="Replace">
                <Step-ID>8</Step-ID>
                <PlayBack--ControlInfo-ControlName />
             </Step>
             <Step DialogName="Replace">
                <Step-ID>9</Step-ID>
                <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
             </Step>
             <Step DialogName="Replace">
                <Step-ID>10</Step-ID>
                <PlayBack--ControlInfo-ControlName />
             </Step>
             <Step DialogName="Replace">
                <Step-ID>16</Step-ID>
                <PlayBack--ControlInfo-ControlName />
             </Step>
           </GStep>
         </Process>
       </Document>
</code>```

Actually expecting a result like below.

```<code> <?xml version="1.0" encoding="utf-8"?>
       <Document>
         <Meta>
           <GpsFile>notepad_may_30_file</GpsFile>
           <GpsId>36fa4fe8-9691-4a7f-8bc1-9543f6b7d29a</GpsId>
           <ExePath>
              <ExePath1>C:\WINDOWS\SYSTEM32\notepad.exe</ExePath1>
          </ExePath>
        </Meta>
        <Process>
              <GStep DialogName="Untitled - Notepad">
              <Step DialogName="Untitled - Notepad">
                 <Step-ID>3</Step-ID>
                 <PlayBack--ControlInfo-ControlName />
              </Step>
              <Step DialogName="Untitled - Notepad">
                   <Step-ID>5</Step-ID>
                   <PlayBack--ControlInfo-ControlName>Edit</PlayBack--ControlInfo-ControlName>
              </Step>
             <Step DialogName="Untitled - Notepad">
                  <Step-ID>6</Step-ID>
                  <PlayBack--ControlInfo-ControlName>Replace...\tCtrl+H</PlayBack--ControlInfo-
                      ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
                 <Step-ID>15</Step-ID>
                 <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
             </Step>
        </GStep>
       <GStep DialogName="Replace">
             <Step DialogName="Replace">
              <Step-ID>8</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Replace">
                <Step-ID>9</Step-ID>
                <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
            </Step>
         </GStep>
     </Process>
   </Document>
</code>```

I tried with the below xslt code snippet.

```<code>  <xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:key name="ControlNameInfo" match="Step" use="PlayBack--ControlInfo-ControlName"/>
     <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
   <xsl:template match="GStep/Step[not(generate-id() = generate-id(key('ControlNameInfo', PlayBack--
        ControlInfo-ControlName)[1]))]"/>
        </xsl:stylesheet>

  Can anyone help
  Thanks very much.
</code>```

答:
In order to keep only distinct Step nodes in each GStep , you must include the parent GStep in the key. Try:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="k1" match="Step" use="concat(PlayBack--ControlInfo-ControlName, '|', generate-id(..))"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="GStep">
    <xsl:copy>
        <xsl:apply-templates select="Step[generate-id()=generate-id(key('k1', concat(PlayBack--ControlInfo-ControlName, '|', generate-id(..)))[1])]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Title: Removing duplicate XML nodes in XSLT

Body:
I would appreciated if someone could help me to create xslt to remove duplicates nodes from XML
        based on duplicated element's value(PlayBack--ControlInfo-ControlName).

I want to remove all the duplicate elements(PlayBack--ControlInfo-ControlName) from the GStep/Step

Input XML

<?xml version="1.0" encoding="utf-8"?>
      <Document>
       <Meta>
         <GpsFile>notepad_may_30_file</GpsFile>
         <GpsId>36fa4fe8-9691-4a7f-8bc1-9543f6b7d29a</GpsId>
          <ExePath>
             <ExePath1>C:\WINDOWS\SYSTEM32\notepad.exe</ExePath1>
          </ExePath>
        </Meta>
         <Process>
            <GStep DialogName="Untitled - Notepad">
             <Step DialogName="Untitled - Notepad">
              <Step-ID>3</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>4</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>5</Step-ID>
              <PlayBack--ControlInfo-ControlName>Edit</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>6</Step-ID>
              <PlayBack--ControlInfo-ControlName>Replace...\tCtrl+H</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>12</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>13</Step-ID>
              <PlayBack--ControlInfo-ControlName>Edit</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>14</Step-ID>
              <PlayBack--ControlInfo-ControlName>Replace...\tCtrl+H</PlayBack--ControlInfo-ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
              <Step-ID>15</Step-ID>
              <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
            </Step>
          </GStep>
          <GStep DialogName="Replace">
             <Step DialogName="Replace">
                <Step-ID>8</Step-ID>
                <PlayBack--ControlInfo-ControlName />
             </Step>
             <Step DialogName="Replace">
                <Step-ID>9</Step-ID>
                <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
             </Step>
             <Step DialogName="Replace">
                <Step-ID>10</Step-ID>
                <PlayBack--ControlInfo-ControlName />
             </Step>
             <Step DialogName="Replace">
                <Step-ID>16</Step-ID>
                <PlayBack--ControlInfo-ControlName />
             </Step>
           </GStep>
         </Process>
       </Document>

Actually expecting a result like below.

 <?xml version="1.0" encoding="utf-8"?>
       <Document>
         <Meta>
           <GpsFile>notepad_may_30_file</GpsFile>
           <GpsId>36fa4fe8-9691-4a7f-8bc1-9543f6b7d29a</GpsId>
           <ExePath>
              <ExePath1>C:\WINDOWS\SYSTEM32\notepad.exe</ExePath1>
          </ExePath>
        </Meta>
        <Process>
              <GStep DialogName="Untitled - Notepad">
              <Step DialogName="Untitled - Notepad">
                 <Step-ID>3</Step-ID>
                 <PlayBack--ControlInfo-ControlName />
              </Step>
              <Step DialogName="Untitled - Notepad">
                   <Step-ID>5</Step-ID>
                   <PlayBack--ControlInfo-ControlName>Edit</PlayBack--ControlInfo-ControlName>
              </Step>
             <Step DialogName="Untitled - Notepad">
                  <Step-ID>6</Step-ID>
                  <PlayBack--ControlInfo-ControlName>Replace...\tCtrl+H</PlayBack--ControlInfo-
                      ControlName>
            </Step>
            <Step DialogName="Untitled - Notepad">
                 <Step-ID>15</Step-ID>
                 <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
             </Step>
        </GStep>
       <GStep DialogName="Replace">
             <Step DialogName="Replace">
              <Step-ID>8</Step-ID>
              <PlayBack--ControlInfo-ControlName />
            </Step>
            <Step DialogName="Replace">
                <Step-ID>9</Step-ID>
                <PlayBack--ControlInfo-ControlName>Cancel</PlayBack--ControlInfo-ControlName>
            </Step>
         </GStep>
     </Process>
   </Document>

I tried with the below xslt code snippet.

  <xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:key name="ControlNameInfo" match="Step" use="PlayBack--ControlInfo-ControlName"/>
     <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
   <xsl:template match="GStep/Step[not(generate-id() = generate-id(key('ControlNameInfo', PlayBack--
        ControlInfo-ControlName)[1]))]"/>
        </xsl:stylesheet>

  Can anyone help
  Thanks very much.

Body:
In order to keep only distinct Step nodes in each GStep , you must include the parent GStep in the key. Try:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="k1" match="Step" use="concat(PlayBack--ControlInfo-ControlName, '|', generate-id(..))"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="GStep">
    <xsl:copy>
        <xsl:apply-templates select="Step[generate-id()=generate-id(key('k1', concat(PlayBack--ControlInfo-ControlName, '|', generate-id(..)))[1])]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


问:
Sending h5 file throught TCP ethernet
My main objective is to send via ethernet TCP protokoll an h5 file. I used the h5py to load the file, i get the length of data, and I want to send from PC to RPi (PC is client RPi is host).

```<code>
Host = "169.254.110.54"
Port = 7777
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((Host, Port))
print("Succeded connection!")

send_obj = h5py.File(model_path, 'r')
print(send_obj)
len = str(send_obj.__sizeof__())
print(len)

print(bytes(len, 'utf-8'))
i = 0

while True and i<1:
      try:
         s.send(bytes(len, 'utf-8'))
         print("Sending data!\n")
         ack = s.recv(1024)
         msg = ack.decode('utf-8')
         if(msg == "DRCV"):
             s.send(send_obj)
         print(msg)
         i= i+1
       except:
          pass
s.close()
print("Connection ended!")
</code>```

Somebody any idea? I tried to convert my file into bytes or something else, whitout any result.

答: For some reason I couldn't manage to send this kind of file(h5) format over TCP connection, but if you save your model in .json you can easilly open(model.json, 'r') and spliting in desired datarame and sending socket.send(bytes(modelString/1024),'utf-8') (1024 bytes want to send in every package). I hope it helps everybody! :D

Title: Sending h5 file throught TCP ethernet

Body:
My main objective is to send via ethernet TCP protokoll an h5 file. I used the h5py to load the file, i get the length of data, and I want to send from PC to RPi (PC is client RPi is host).

Host = "169.254.110.54"
Port = 7777
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((Host, Port))
print("Succeded connection!")

send_obj = h5py.File(model_path, 'r')
print(send_obj)
len = str(send_obj.__sizeof__())
print(len)

print(bytes(len, 'utf-8'))
i = 0

while True and i<1:
      try:
         s.send(bytes(len, 'utf-8'))
         print("Sending data!\n")
         ack = s.recv(1024)
         msg = ack.decode('utf-8')
         if(msg == "DRCV"):
             s.send(send_obj)
         print(msg)
         i= i+1
       except:
          pass
s.close()
print("Connection ended!")

Somebody any idea? I tried to convert my file into bytes or something else, whitout any result.


问:
Overloading [] and + simultaneously
I have class which has array inside.

Suppose we have class A and array12 inside it.

All I need to do is A[index]+value so I suppose add to array12[index] that value.

```<code>int &operator[](int index)
{
    return array12[index];
}
</code>```

But what I need write when I overload operator +?

How do I know element index when overloading +?

答:
Firstly -  pay attention for some misinformation in your question

A[index] + value - A Is the name of the class, not the object of the class.

operator+ This operator should not update the value, but to return the expected copy result. You probably meant for operator+=.

For your question

The operator+= overloading should be implemented in the type that your array contains. For example, if array12 contains int this code will work as you expected:

```<code>int main() {
    A a;
    /* ... Some a initialization ... */
    a[3] += 2;
    return EXIT_SUCCESS;
}
</code>```

Suppose your array12 contains a more complex type, for example a custom class named B- Then you should overload operator+= inside B.

Title: Overloading [] and + simultaneously

Body:
I have class which has array inside.

Suppose we have class A and array12 inside it.

All I need to do is A[index]+value so I suppose add to array12[index] that value.

int &operator[](int index)
{
    return array12[index];
}

But what I need write when I overload operator +?

How do I know element index when overloading +?

Body:
Firstly -  pay attention for some misinformation in your question

A[index] + value - A Is the name of the class, not the object of the class.

operator+ This operator should not update the value, but to return the expected copy result. You probably meant for operator+=.

For your question

The operator+= overloading should be implemented in the type that your array contains. For example, if array12 contains int this code will work as you expected:

int main() {
    A a;
    /* ... Some a initialization ... */
    a[3] += 2;
    return EXIT_SUCCESS;
}

Suppose your array12 contains a more complex type, for example a custom class named B- Then you should overload operator+= inside B.


问:
How do I have to use extern variables?
I'm having some problems with extern variables. It's the first time I use it, so I don't know how it works. I have this code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <time.h>

extern double *x, *y, a;
extern unsigned int N;

inline void f1 ()
{
    int i;

    for (i=0; i<N; i++)
    {
        y[i] = a*x[i] + y[i];
    }
}
</code>```

And the error that I get when I compile it it's that x,y,a and N are not defined. So, could someone help me please?

答:
This program throws an error in compilation because *x,*y and a etc are declared but not defined anywhere. Essentially, *x,*y and a etc isn’t allocated any memory. And the program is trying to change the value of these variable that doesn’t exist at all.

checkout this link for better understanding of extern keyword.
https://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

Title: How do I have to use extern variables?

Body:
I'm having some problems with extern variables. It's the first time I use it, so I don't know how it works. I have this code:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

extern double *x, *y, a;
extern unsigned int N;

inline void f1 ()
{
    int i;

    for (i=0; i<N; i++)
    {
        y[i] = a*x[i] + y[i];
    }
}

And the error that I get when I compile it it's that x,y,a and N are not defined. So, could someone help me please?


问:
SingleCellExperiment. Why I'm not succeeding in change rownames and colnames in my single cell experiment?
I have to manipulate some data in order to get insight about adenocarcinoma. In order to get more insight I have to manipulate my data. Until now my pipe line is as follows :

```<code>nsclc <- read.table("D:\\Bioinformatica\\Project Work and PhD Proposal\\Data\\Data Extracted\\GSE143423_lbm_scRNAseq_gene_expression_counts.csv",
header=TRUE,sep=",")

meta_1 <- read.table("D:\\Bioinformatica\\Project Work and PhD Proposal\\Data\\Data Extracted\\GSE143423_lbm_scRNAseq_metadata.csv",
header = TRUE,sep =",")

meta_1$X <- NULL
#......Creation of first Single cell Experiment

sce_lc <- SingleCellExperiment(
assays = list(counts = as.matrix(nsclc)),
rowData =nsclc[1:dim(nsclc)[1],1] %>% data.frame ,
colData = cell <- paste0("cell_",1:dim(nsclc)[2]) %>% data.frame,metadata = meta_1)
</code>```

when I explore sce_lc experiment no change in rownames is observed as well as it is for colnames.
Can anyone help me?

答:
You need to name the rows of your matrix. read the vignette before embarking on your journey. rowData and colData are something else. You can just specify the rownames and colnames of your matrix before slotting them in. And avoid the pipes when creating the object.. some of the assignments are really weird:</p>

```<code>library(SingleCellExperiment)

nsclc = data.frame(what=paste0("gene",1:100),
matrix(rnbinom(1000,mu=100,size=1),ncol=10,nrow=10))
meta_1 = data.frame(id=1:10,var=letters[1:10])

rownames(nsclc) = as.character(nsclc[,1])
colnames(nsclc) = paste0("cell_",1:ncol(nsclc))

sce_lc <- SingleCellExperiment(
assays = list(counts = as.matrix(nsclc[,-1])),
metadata = meta_1)

class: SingleCellExperiment
dim: 100 10
metadata(2): id var
assays(1): counts
rownames(100): gene1 gene2 ... gene99 gene100
rowData names(0):
colnames(10): cell_2 cell_3 ... cell_10 cell_11
colData names(0):
reducedDimNames(0):
spikeNames(0):
</code>```

Body:
I have to manipulate some data in order to get insight about adenocarcinoma. In order to get more insight I have to manipulate my data. Until now my pipe line is as follows :

nsclc <- read.table("D:\\Bioinformatica\\Project Work and PhD Proposal\\Data\\Data Extracted\\GSE143423_lbm_scRNAseq_gene_expression_counts.csv",
header=TRUE,sep=",")

meta_1 <- read.table("D:\\Bioinformatica\\Project Work and PhD Proposal\\Data\\Data Extracted\\GSE143423_lbm_scRNAseq_metadata.csv",
header = TRUE,sep =",")

meta_1$X <- NULL
#......Creation of first Single cell Experiment

sce_lc <- SingleCellExperiment(
assays = list(counts = as.matrix(nsclc)),
rowData =nsclc[1:dim(nsclc)[1],1] %>% data.frame ,
colData = cell <- paste0("cell_",1:dim(nsclc)[2]) %>% data.frame,metadata = meta_1)

when I explore sce_lc experiment no change in rownames is observed as well as it is for colnames.
Can anyone help me?

Body:
You need to name the rows of your matrix. read the vignette before embarking on your journey. rowData and colData are something else. You can just specify the rownames and colnames of your matrix before slotting them in. And avoid the pipes when creating the object.. some of the assignments are really weird:

library(SingleCellExperiment)

nsclc = data.frame(what=paste0("gene",1:100),
matrix(rnbinom(1000,mu=100,size=1),ncol=10,nrow=10))
meta_1 = data.frame(id=1:10,var=letters[1:10])

rownames(nsclc) = as.character(nsclc[,1])
colnames(nsclc) = paste0("cell_",1:ncol(nsclc))

sce_lc <- SingleCellExperiment(
assays = list(counts = as.matrix(nsclc[,-1])),
metadata = meta_1)

class: SingleCellExperiment
dim: 100 10
metadata(2): id var
assays(1): counts
rownames(100): gene1 gene2 ... gene99 gene100
rowData names(0):
colnames(10): cell_2 cell_3 ... cell_10 cell_11
colData names(0):
reducedDimNames(0):
spikeNames(0):


问:
MAT-FORM-FIELD-OUTLINE label text overlapping with form-field-outline border
In my application, i have 3 step mat-stepper process. In First stepper, i have mat-form-field outline and it works fine but in Second and Third Stepper i have the same mat-form-field outline but the label is overlapping with border line like below.

```<code><mat-form-field appearance="outline">
      <mat-label>Member ID *</mat-label>
      <input matInput placeholder="Test"
                   formControlName="memberID"
                   [(ngModel)]="submitPaymentRequest.getAccount().acctNum">
       <mat-placeholder>TEst</mat-placeholder>
       <mat-error app-validation-message></mat-error>
</mat-form-field>
</code>```

i could see this is happening in IE only not in Chrome.

could any one help on this. Thanks in Advance

答:
Unfortunately, Material Angular does not support IE properly (officialy, IE11+ is supported...).

If IE support is important to your project, use something else like https://materializecss.com/

Body:
In my application, i have 3 step mat-stepper process. In First stepper, i have mat-form-field outline and it works fine but in Second and Third Stepper i have the same mat-form-field outline but the label is overlapping with border line like below.

<mat-form-field appearance="outline">
      <mat-label>Member ID *</mat-label>
      <input matInput placeholder="Test"
                   formControlName="memberID"
                   [(ngModel)]="submitPaymentRequest.getAccount().acctNum">
       <mat-placeholder>TEst</mat-placeholder>
       <mat-error app-validation-message></mat-error>
</mat-form-field>

i could see this is happening in IE only not in Chrome.

could any one help on this. Thanks in Advance


问:
Couldn't find or load main class when running java class in command prompt
I have written a simple program HelloWorld in java. But when I try to run my java code in command prompt using

```<code>java HelloWorld
</code>```

It returns

```<code>Couldn't find or load main class
</code>```

What should I do??
There's no syntax error in my code!!

答:
Adding . to CLASSPATH variable in Environment variables solved my problem!!

Java searches for the classes in the paths mentioned in CLASSPATH variable, if you don't add . there, it won't search for classes in current working directory!!!

Go to Control panel > System and Security > System > Advanced System Settings > Advanced

Click Environment Variables

If CLASSPATH variable is present under User variables , add '.' separated by semicolon. For example if java is installed in C:\Program Files\Java\jdk1.8.0_25\bin , CLASSPATH will be

```<code>C:\Program Files\Java\jdk1.8.0_25\bin;.;
</code>```

Click OK.

Body:
I have written a simple program HelloWorld in java. But when I try to run my java code in command prompt using

java HelloWorld

It returns

Couldn't find or load main class

What should I do??
There's no syntax error in my code!!

Body:
Adding . to CLASSPATH variable in Environment variables solved my problem!!

Java searches for the classes in the paths mentioned in CLASSPATH variable, if you don't add . there, it won't search for classes in current working directory!!!

Go to Control panel > System and Security > System > Advanced System Settings > Advanced

Click Environment Variables

If CLASSPATH variable is present under User variables , add '.' separated by semicolon. For example if java is installed in C:\Program Files\Java\jdk1.8.0_25\bin , CLASSPATH will be

C:\Program Files\Java\jdk1.8.0_25\bin;.;

Click OK.


问:
float not working in mysql database
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.</p>

```<code>include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens
</code>```

答: From what I know float type isn't precise. It doesn't show you that actual value so 1.1 that you saved may not be the actual value stored. Trying setting your field as decimal and give it a length of say, 10,1 where 10 is the maximum number of digits (the precision) and 1 is the number of digits to the right of the decimal point (the scale). It should work doing query like stuff='1.1' or stuff=1.1.

Title: float not working in mysql database

Body:
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.

include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens


问:
How to update and increment a counter in postgresql and mybatis
I am using spring-mybatis and I am doing this update.

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.Article">

    <update resultType="java.lang.Long"  id="updateClickCount" flushCache="true">
        UPDATE "article"
        SET "click_count" = "click_count" + 1
        WHERE "id" = #{id,jdbcType=NUMERIC}
        RETURNING "click_count";
    </update>

</mapper>
</code>```

I expect to be able to read the count in the same request as the one that increment the count.

Instead, it gives me this error:

Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 81; Attribute "resultType" must be declared for element type "update".
```

How can I read the update count value in postgrsql and mybatis?

答:
I believe that an UPDATE...RETURNING statement returns values in a ResultSet. MyBatis only decodes ResultSets in <select> statements. So you will need to write your statement as a <select>. This will look weird, but will work perfectly fine. The different XML tags don't do any checking to ensure that the included SQL actually matches the tag.

One other thing you will need to think about is that <select> statements do not get committed automatically by MyBatis - so you might need to manually commit after the statement executes depending on how you have setup your transaction manager.

Body:
I am using spring-mybatis and I am doing this update.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.Article">

    <update resultType="java.lang.Long"  id="updateClickCount" flushCache="true">
        UPDATE "article"
        SET "click_count" = "click_count" + 1
        WHERE "id" = #{id,jdbcType=NUMERIC}
        RETURNING "click_count";
    </update>

</mapper>

I expect to be able to read the count in the same request as the one that increment the count.

Instead, it gives me this error:

Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 81; Attribute "resultType" must be declared for element type "update".

How can I read the update count value in postgrsql and mybatis?


问:
Jquery Select load back after refresh page
Well, It's a simple one and I know there are a lot of source about this thing.

I've a jquery script like:

```<code><script>
    $(document).ready(function () {
        $("#CountryId").change(function () {
            $.get("@Url.Action("GetStateList","Controllers1")", { sOId: $("#CountryId").val() }, function (data) {
                $("#StateId").empty();
                $.each(data, function (index, row) {
                    $("#StateId").append("<option value='" + row.PersonnelNumber + "'>" + row.Name + "</option>")
                });
            });
        })
    });
</script>

public JsonResult GetStateList(string sOId)
    {
        string sPositionNumber = Session["xPersonnelNumber"].ToString();

        db.Configuration.ProxyCreationEnabled = false;
        List<Employee> StateList = db.Employees.Where(x => x.OrganizationNumber == sOId && x.Name != null).OrderBy(o => o.Name).ToList();
        return Json(StateList, JsonRequestBehavior.AllowGet);
    }
</code>```

After the page refresh, the StateId option is empty. How can I keep the option list after the page is refresh? If I remove the .Empty(), it will append another option. It's cascading dropdown using MVC .NET

Really appreciated.

答:
HTTP is stateless. There are however ways to persist data in ASP.NET MVC:

Hidden Field

Cookies

Query String

ViewData

ViewBag

TempData

Good article:

https://www.c-sharpcorner.com/article/state-management-in-asp-net-mvc

However most of these methods require you to post the data to the controller, and as such data will get lost on refresh.

So viable options are...

Option 1: Caching

You could use a simple memory cache to store the list against a custom identifier, such as the user ID for a period of time, and update it every time the GetStateList method is called. Populating the initial list on page load from the cache.

Option 2: Browser side persistence

You could look at browser side persistence of data and look into things like:

IndexedDB

Web storage API

PouchDb

Browser Cookies

Body:
Well, It's a simple one and I know there are a lot of source about this thing.

I've a jquery script like:

public JsonResult GetStateList(string sOId)
    {
        string sPositionNumber = Session["xPersonnelNumber"].ToString();

        db.Configuration.ProxyCreationEnabled = false;
        List<Employee> StateList = db.Employees.Where(x => x.OrganizationNumber == sOId && x.Name != null).OrderBy(o => o.Name).ToList();
        return Json(StateList, JsonRequestBehavior.AllowGet);
    }

After the page refresh, the StateId option is empty. How can I keep the option list after the page is refresh? If I remove the .Empty(), it will append another option. It's cascading dropdown using MVC .NET

Really appreciated.


问:
Creating a table of data in Python
I am creating a table of data in Python to print on the console using the code below:

```<code>print("Model Results:\n")
print("R&D Spend\tAdministration\tMarketing Spend\tState\tPredicted Profit")
for i in range(50):
    print("%0.2f\t%0.2f\t%0.2f\t%d\t%0.2f"%(
        X_test[i][0],X_test[i][1],X_test[i][2],X_test[i][3], y_predict[i]))
</code>```

The trouble is some of the rows are not displaying correctly (highlighted in the attached screenshot). This seems to happen for rows where the first column is 4 figures. What trick can I use to overcome this?

This is the console output with my table:

答:
This can be easily done with format:

```<code>def print_row(*args):
    print((len(args) * '{:<15.3f}').format(*args))
</code>```

In {:<15.3f} 15 is width of column and 3 is number of digits after decimal point. (Omit the < for right alignment.)
This way you don't need to use tabs.

Title: Creating a table of data in Python

Body:
I am creating a table of data in Python to print on the console using the code below:

print("Model Results:\n")
print("R&D Spend\tAdministration\tMarketing Spend\tState\tPredicted Profit")
for i in range(50):
    print("%0.2f\t%0.2f\t%0.2f\t%d\t%0.2f"%(
        X_test[i][0],X_test[i][1],X_test[i][2],X_test[i][3], y_predict[i]))

The trouble is some of the rows are not displaying correctly (highlighted in the attached screenshot). This seems to happen for rows where the first column is 4 figures. What trick can I use to overcome this?

This is the console output with my table:

Body:
This can be easily done with format:

def print_row(*args):
    print((len(args) * '{:<15.3f}').format(*args))

In {:<15.3f} 15 is width of column and 3 is number of digits after decimal point. (Omit the < for right alignment.)
This way you don't need to use tabs.


答:
bootsrap modal has its own structure. So modal-content class is one of its element to make inside its content clickable so you need to add modal-content class

$(function(){
    $('.modal').modal({
        show: false
    }).on('hidden.bs.modal', function(){
        $(this).find('video')[0].pause();
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal-content-vid{
    background: transparent !important;
    border: none !important;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

Explainer Videos

Check out our videos below taken from one of our recorded webinars to see if this certification is right for you:

See what our online course looks like

Sample lessons

            <video id="flitpcdemo" controls autoplay width="100%;z-index:100%">
               <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            </video>

            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>

CSS:```

Title: Video modal keeps closing when I try to click on video to play HTML/CSS

Body:
I am having an issue implementing video pop up using html/css and bootstrap.

Basically when I click on the link, the modal appears with the video, but the moment I click on the video to play, it closes the modal.

I want it so that the user can play the video and interact with the controls, the moment they click anywhere in the background away from the video, it closes the video.

You can see how it's currently working on our website https://www.metis-online.com/#courses and you will see under 'Explainder Videos' two links that opens up the relevant video models.

HTML:

Explainer Videos

Check out our videos below taken from one of our recorded webinars to see if this certification is right for you:

See what our online course looks like

Sample lessons

            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>

            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>

CSS:

.modal-content-vid{
    background: transparent !important;
    border: none !important;
}

Body:
bootsrap modal has its own structure. So modal-content class is one of its element to make inside its content clickable so you need to add modal-content class

$(function(){
    $('.modal').modal({
        show: false
    }).on('hidden.bs.modal', function(){
        $(this).find('video')[0].pause();
    });
});

.modal-content-vid{
    background: transparent !important;
    border: none !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<h5>Explainer Videos</h5>
<p>Check out our videos below taken from one of our recorded webinars to see if this certification is right for you:
<ul class="nobullet">
<li><a style="text-decoration: underline; color:white;" data-toggle="modal" data-target="#flitpc-video-1">See what our online course looks like</a></li>
<li><a style="text-decoration: underline; color:white;" data-toggle="modal" data-target="#flitpc-video-2">Sample lessons</a></li>
</ul>
<br/>
</p>

<div class="modal fade" id="flitpc-video-1">
   <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content modal-content-vid">
         <div class="modal-body">
            <video id="flitpcdemo" controls autoplay width="100%;z-index:100%">
               <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            </video>
         </div>
      </div>
   </div>
</div>

<div class="modal fade" id="flitpc-video-2">
   <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content modal-content-vid">
         <div class="modal-body">
            <video id="flitpcdemo" controls autoplay width="100%">
               <source src="./video2.mp4" type="video/mp4">
            </video>
         </div>
      </div>
   </div>
</div>
CSS:


答: Don't use float( even if you insert 1.1 into the table, the actual value for float type is not 1.1, but something like 1.100000023841858) . Change it to double in database (or decimal)

Title: float not working in mysql database


问:
unable to find type in interface
I cannot find the type of the object "history" in the Class, with "any []" there is no problem but I prefer to avoid using it and to have a good typing.

```<code>interface GameClass{
  history: any[] ////////////Here
  stepNumber:number
  xIsNext:boolean
}

class Game extends React.Component<GameProps,GameClass>{
  constructor(props:GameProps) {
    super(props);
    this.state = {
      history: [{ squares: Array(9).fill(null) }], ////////////Here
      stepNumber: 0,
      xIsNext: true
    };
  }
}
</code>```

CodePen

Thank you

答:
Create a type for it.</p>

```<code>interface History {
    squares: number[]; // Not sure what type you want here `number` or `string`
}

interface GameClass{
  history: History[];
  stepNumber: number
  xIsNext: boolean;
}
</code>```

Title: unable to find type in interface

Body:
I cannot find the type of the object "history" in the Class, with "any []" there is no problem but I prefer to avoid using it and to have a good typing.

interface GameClass{
  history: any[] ////////////Here
  stepNumber:number
  xIsNext:boolean
}

class Game extends React.Component<GameProps,GameClass>{
  constructor(props:GameProps) {
    super(props);
    this.state = {
      history: [{ squares: Array(9).fill(null) }], ////////////Here
      stepNumber: 0,
      xIsNext: true
    };
  }
}

CodePen

Thank you

Body:
Create a type for it.

interface History {
    squares: number[]; // Not sure what type you want here `number` or `string`
}

interface GameClass{
  history: History[];
  stepNumber: number
  xIsNext: boolean;
}


问:
transpose pandas columns with duplicate values
I have a data frame like as shown below

```<code>df1 = pd.DataFrame({'Gender':['Male','Male','Male','Male','Female','Female','Female','Female','Male','Male','Male','Male','Female','Female','Female','Female'],
                'Year' :[2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009],
           'rate':[2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6,2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6],
           'Heading':['TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123',
                     'TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456'],
           'target':[31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2,31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2],
            'day_type':['wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend']})
</code>```

As you can see there are duplicate values in all columns.

I would like to transpose/pivot them to get an output as shown below. Though I tried the below it didn't work.

```<code>df1.pivot(index='Year', columns='Heading', values='rate')
</code>```

I expect my output to be like as shown below where each year is made as a row and all the corresponding entries for that year are made as columns.

Please note I haven't filled in the values as table column structure is more important.

Can you help me, please?

答:
You can try this. You can use df.unstack() here and convert the Multi-Index to single level index using join.

```<code>df1 = df1.pivot_table(index=['Year','Gender'],columns='Heading',values='rate').unstack()

df1.columns = ['_'.join(i) for i in df1.columns.tolist()]

df1
      TDAS3_Female  TDAS3_Male  TNMAB123_Female  TNMAB123_Male  TSAD4_Female  TSAD4_Male  TWQE2_Female  TWQE2_Male
Year
2008           NaN         NaN              6.3            2.3           NaN         NaN           NaN         NaN
2009           NaN         NaN              7.1            3.2           NaN         NaN           2.1         4.5
2010           5.3         5.6              NaN            NaN           NaN         NaN           4.2         6.7
2011           3.6         3.2              NaN            NaN           2.9         3.5           NaN         NaN
2012           NaN         NaN              NaN            NaN           6.2         2.6           NaN         NaN
</code>```

There are couple of ways to convert Multi-Index to single level. Using df.colums or df.columns.tolist or pd.MultiIndex.to_flat_index

['_'.join(i) for i in df1.columns.tolist()]

['_'.join(i) for i in df1.columns]

['_'.join(i) for i in df1.columns.to_flat_index()]

Body:
I have a data frame like as shown below

df1 = pd.DataFrame({'Gender':['Male','Male','Male','Male','Female','Female','Female','Female','Male','Male','Male','Male','Female','Female','Female','Female'],
                'Year' :[2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009],
           'rate':[2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6,2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6],
           'Heading':['TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123',
                     'TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456'],
           'target':[31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2,31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2],
            'day_type':['wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend']})

As you can see there are duplicate values in all columns.

I would like to transpose/pivot them to get an output as shown below. Though I tried the below it didn't work.

df1.pivot(index='Year', columns='Heading', values='rate')

I expect my output to be like as shown below where each year is made as a row and all the corresponding entries for that year are made as columns.

Please note I haven't filled in the values as table column structure is more important.

Can you help me, please?

Body:
You can try this. You can use df.unstack() here and convert the Multi-Index to single level index using join.

df1 = df1.pivot_table(index=['Year','Gender'],columns='Heading',values='rate').unstack()

df1.columns = ['_'.join(i) for i in df1.columns.tolist()]

df1
      TDAS3_Female  TDAS3_Male  TNMAB123_Female  TNMAB123_Male  TSAD4_Female  TSAD4_Male  TWQE2_Female  TWQE2_Male
Year
2008           NaN         NaN              6.3            2.3           NaN         NaN           NaN         NaN
2009           NaN         NaN              7.1            3.2           NaN         NaN           2.1         4.5
2010           5.3         5.6              NaN            NaN           NaN         NaN           4.2         6.7
2011           3.6         3.2              NaN            NaN           2.9         3.5           NaN         NaN
2012           NaN         NaN              NaN            NaN           6.2         2.6           NaN         NaN

There are couple of ways to convert Multi-Index to single level. Using df.colums or df.columns.tolist or pd.MultiIndex.to_flat_index

['_'.join(i) for i in df1.columns.tolist()]

['_'.join(i) for i in df1.columns]

['_'.join(i) for i in df1.columns.to_flat_index()]


问:
Accessing vector in class
If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

```<code>class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}
</code>```

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.

答:
return it by const reference, or just by reference if you want to allow changing.

```<code>const std::vector<T> & getVector() const
{
    return vector;
}
</code>```

usage:

```<code>const std::vector<T> &v = myClass.getVector();
</code>```

Title: Accessing vector in class

Body:
If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.

Body:
return it by const reference, or just by reference if you want to allow changing.

const std::vector<T> & getVector() const
{
    return vector;
}

usage:

const std::vector<T> &v = myClass.getVector();


问:
Is there a way to disable checkboxes with different names and id, if radio button is checked?
I figured out the solution, but the name attribute must be the same or it won't work. I was thinking of auto-incrementing the id attribute someway, but I had no luck so far. Here's what I have so far(that works):

function ckChange(ckType) {
  var ckName = document.getElementsByName(ckType.name);

  for (var i = 0; i < ckName.length; i++) {
    if (!ckName[i].checked) {
      ckName[i].disabled = true;
    } else {
      if (ckName[i].checked) {
        ckName[i].disabled = false;
      }
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
 <input type="radio" name="No Past Conditions" id="rb0" onclick="ckChange(this)" />
   <label for="rb0">No Past Conditions </label>

 <input type="checkbox" name="No Past Conditions" id="cb1" value="Yes" onclick="ckChange(this)" />
   <label for="cb1">Heart disease </label>

<!-- WORKS GREAT IF NAME IS THE SAME, HOWEVER I WANT TO CHANGE IT IN ORDER FOR READABILITY WHEN I COLLECT THE FORM -->

<!-- this part here doesn't work, bcz the name attrib is different -->
  <input type="checkbox" name="Anemia or other blood disease" id="cb2" value="Yes" />
          <label for="cb2">Anemia or other blood disease</label>
  <input type="checkbox" name="Severe headaches" id="cb3" value="Yes" />
          <label for="cb3">Severe headaches</label>
</form></code>```

Now I tried declaring a checkbox variable to be autoincremented, using the base id name(cb: checkbox) + j(concatenating it I guess?) but that's not the right syntax I think. Code:

var j;
var checkbox = document.getElementById(cb + j);
for (var j = 0; j < 20; j++)```

Clearly I know it's wrong but I've searched for hours and I'm really upset. Can you guys help me?

Edit:@shingo.nakanishi answer generates this error

答:
You need put getElementById in for loop.
You don't need to declare var j twice.

```<code>for (var j = 0; j < 20; j++) {
  var checkbox = document.getElementById(cb + j);
  ...
}
</code>```

If you do not have a cb variable, let cb be a String literal as below code.

```<code>for (var j = 0; j < 20; j++) {
  var checkbox = document.getElementById("cb" + j);
  ...
}
</code>```

Note

This is a bad practice to use id as @Chris G commented.

If you want a good design, you'll need to make a full revision of the code.

Body:
I figured out the solution, but the name attribute must be the same or it won't work. I was thinking of auto-incrementing the id attribute someway, but I had no luck so far. Here's what I have so far(that works):

function ckChange(ckType) {
  var ckName = document.getElementsByName(ckType.name);

  for (var i = 0; i < ckName.length; i++) {
    if (!ckName[i].checked) {
      ckName[i].disabled = true;
    } else {
      if (ckName[i].checked) {
        ckName[i].disabled = false;
      }
    }
  }
}

<form>
 <input type="radio" name="No Past Conditions" id="rb0" onclick="ckChange(this)" />
   No Past Conditions

 <input type="checkbox" name="No Past Conditions" id="cb1" value="Yes" onclick="ckChange(this)" />
   Heart disease

  <input type="checkbox" name="Anemia or other blood disease" id="cb2" value="Yes" />
          Anemia or other blood disease
  <input type="checkbox" name="Severe headaches" id="cb3" value="Yes" />
          Severe headaches
</form>

Now I tried declaring a checkbox variable to be autoincremented, using the base id name(cb: checkbox) + j(concatenating it I guess?) but that's not the right syntax I think. Code:

var j;
var checkbox = document.getElementById(cb + j);
for (var j = 0; j < 20; j++)

Clearly I know it's wrong but I've searched for hours and I'm really upset. Can you guys help me?

Edit:@shingo.nakanishi answer generates this error

Body:
You need put getElementById in for loop.
You don't need to declare var j twice.

for (var j = 0; j < 20; j++) {
  var checkbox = document.getElementById(cb + j);
  ...
}

If you do not have a cb variable, let cb be a String literal as below code.

for (var j = 0; j < 20; j++) {
  var checkbox = document.getElementById("cb" + j);
  ...
}

Note

This is a bad practice to use id as @Chris G commented.

If you want a good design, you'll need to make a full revision of the code.


问:
Error in SQL syntax when running SQL in Java but not in HeidiSQL
I'm trying to run an insert or update on a table - the string generated from below works fine when copy pasted into HeidiSQL but throws SQLSyntaxErrorExceptions when run from Java:

```<code>Statement statement = con.createStatement();
String escapedXML = EscapeString(billboard.getXml());
String sql = String.format(
    "DELIMITER $ \r\nBEGIN NOT ATOMIC\r\n" +
    "IF EXISTS(SELECT * FROM billboards where Name='%s') THEN UPDATE billboards SET XML='%s' where Name='%s';\r\n" +
    "ELSE insert into billboards(Name, XML, CreatorName) values('%s', '%s', '%s');\r\n" +
    "END IF;\r\n" +
    "END $\r\n" +
    "DELIMITER ;", billboard.getName(), escapedXML, billboard.getName(), billboard.getName(), escapedXML, billboard.getCreatorName());
// Insert or update billboard
statement.execute(sql);
</code>```

I can't figure out why.

答:
The reason that you are getting a syntax error is that DELIMITER is a MySQL client command and not an SQL statement.  MySQL commands may not be used in with JDBC.

For more information:

Delimiters in MySQL

Body:
I'm trying to run an insert or update on a table - the string generated from below works fine when copy pasted into HeidiSQL but throws SQLSyntaxErrorExceptions when run from Java:

Statement statement = con.createStatement();
String escapedXML = EscapeString(billboard.getXml());
String sql = String.format(
    "DELIMITER $ \r\nBEGIN NOT ATOMIC\r\n" +
    "IF EXISTS(SELECT * FROM billboards where Name='%s') THEN UPDATE billboards SET XML='%s' where Name='%s';\r\n" +
    "ELSE insert into billboards(Name, XML, CreatorName) values('%s', '%s', '%s');\r\n" +
    "END IF;\r\n" +
    "END $\r\n" +
    "DELIMITER ;", billboard.getName(), escapedXML, billboard.getName(), billboard.getName(), escapedXML, billboard.getCreatorName());
// Insert or update billboard
statement.execute(sql);

I can't figure out why.


问:
Remove child nodes from parent - PugiXML
```<code><Node>
  <A>
    <B id = "it_DEN"></B>
  </A>
  <A>
    <B id = "en_KEN"></B>
  </A>
  <A>
    <B id = "it_BEN"></B>
  </A>
</Node>
</code>```

How can I remove child node of  that has child node  which has attribute id not starts with it using PugiXML.
The result would be as below:

```<code><Node>
  <A>
    <B id = "it_DEN"></B>
  </A>
  <A>
    <B id = "it_BEN"></B>
  </A>
</Node>
</code>```

答:
Another way is to increment the iterator before removing the child. To remove an attribute while iterating.</p>

```<code>for(pugi::xml_attribute_iterator it = node.attributes_begin(); it != node.attributes_end();){
    pugi::xml_attribute attr = *it++;
    if(should_remove(attr)){
        node.remove_attribute(attr);
    }
}
</code>```

Body:
<Node>

</Node>

How can I remove child node of  that has child node  which has attribute id not starts with it using PugiXML.
The result would be as below:

<Node>

</Node>

Body:
Another way is to increment the iterator before removing the child. To remove an attribute while iterating.

for(pugi::xml_attribute_iterator it = node.attributes_begin(); it != node.attributes_end();){
    pugi::xml_attribute attr = *it++;
    if(should_remove(attr)){
        node.remove_attribute(attr);
    }
}


问:
Get distinct values of two columns and merge into rows
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

```<code>IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com
</code>```

I want to do a distinct query for the IP Address and combine the SiteName like below

```<code>IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15
</code>```

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

```<code>Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO
</code>```

答:
Please use below query,</p>

```<code>update Table1 T1 set IP = T2.SiteName
from
(select IPAddress, string_agg(SiteName, '') as SiteName from dbo.WebsiteIP
) T2
where T2.IPAddress =  T1.IPAddress;
</code>```

Body:
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com

I want to do a distinct query for the IP Address and combine the SiteName like below

IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO

Body:
Please use below query,

update Table1 T1 set IP = T2.SiteName
from
(select IPAddress, string_agg(SiteName, '') as SiteName from dbo.WebsiteIP
) T2
where T2.IPAddress =  T1.IPAddress;


问:
Matplotlib axis for FacetGrid
Why
https://seaborn.pydata.org/generated/seaborn.FacetGrid.html

does not have ax argument that accepts matplotlib axis like other graphs

e.g., https://seaborn.pydata.org/generated/seaborn.distplot.html?

As I need to set the matplotlib axis for FacetGrid to bring in customized style.

答:
FaceGrid makes the grid, so you cannot pass a grid to it. The individual plots are stored inside, and can be manipulated like in the code below. Also note that that Axes and Axis are different in Matplotlib. The code below shows a way to obtain both Axes and Axis:

```<code>import seaborn as sns
import pandas as pd

#dummy data
data= pd.DataFrame(data={'a':np.random.randint(0,2, 100),
                         'b':np.random.rand(100),
                         'c':np.random.rand(100)})

# make facetgrid and store in variable
g = sns.FacetGrid(data, col='a') # make facetgrid with 2 columns, because there are two distinct values in column a of data
g.map(plt.scatter, 'b', 'c') # map function to grid

# the individual axes of the grid are stored in g.
# you can access and edit them like so:

for ax in g.axes[0]:
    ax.set_ylabel('test')
    ax.set_ylim(0,1.5)
    ax.set_title('title')
    # now you can obtain the axis from one of the axes
    x_axis = ax.get_xaxis()
</code>```

Title: Matplotlib axis for FacetGrid

Body:
FaceGrid makes the grid, so you cannot pass a grid to it. The individual plots are stored inside, and can be manipulated like in the code below. Also note that that Axes and Axis are different in Matplotlib. The code below shows a way to obtain both Axes and Axis:

import seaborn as sns
import pandas as pd

#dummy data
data= pd.DataFrame(data={'a':np.random.randint(0,2, 100),
                         'b':np.random.rand(100),
                         'c':np.random.rand(100)})

# make facetgrid and store in variable
g = sns.FacetGrid(data, col='a') # make facetgrid with 2 columns, because there are two distinct values in column a of data
g.map(plt.scatter, 'b', 'c') # map function to grid

# the individual axes of the grid are stored in g.
# you can access and edit them like so:

for ax in g.axes[0]:
    ax.set_ylabel('test')
    ax.set_ylim(0,1.5)
    ax.set_title('title')
    # now you can obtain the axis from one of the axes
    x_axis = ax.get_xaxis()


问:
How to avoid command window popping on cmd.exe
I have a command as:

```<code>cmd.exe /c ping 1.1.1.1 -n 1 -w 10000 && echo second command goes here
</code>```

But when executed it opens a command window. Is there a way to avoid the command window from popping up?

PS: I cannot remove cmd.exe from there. As you can see, I am trying to tie two commands one after the other in the same string.

Thanks.

Edit: Sorry. Its not a bat file. I want to execute 2 commands in the "UninstallString" of msiexec. I was trying so many things that my question got a bit carried away.

The command is:

```<code>msiexec <product> <package> && reg delete /xxx
</code>```

答:
From win cmd:

```<code>start /b cmd.exe /c "ping 1.1.1.1 -n 1 -w 10000 & echo second command goes here"
</code>```

runs both commands without opening another cmd window, leaving parent window unblocked for further commands without waiting.

Body:
I have a command as:

cmd.exe /c ping 1.1.1.1 -n 1 -w 10000 && echo second command goes here

But when executed it opens a command window. Is there a way to avoid the command window from popping up?

PS: I cannot remove cmd.exe from there. As you can see, I am trying to tie two commands one after the other in the same string.

Thanks.

Edit: Sorry. Its not a bat file. I want to execute 2 commands in the "UninstallString" of msiexec. I was trying so many things that my question got a bit carried away.

The command is:

msiexec <product> <package> && reg delete /xxx

Body:
From win cmd:

start /b cmd.exe /c "ping 1.1.1.1 -n 1 -w 10000 & echo second command goes here"

runs both commands without opening another cmd window, leaving parent window unblocked for further commands without waiting.