问:
Reading c++ 2d array in python swig
C++ part
I have a class a with a public variable 2d int array b that I want to print out in python.(The way I want to access it is a.b)

I have been able to wrap the most part of the code and I can call most of the functions in class a in python now.

So how can I read b in python? How to read it into an numpy array with numpy.i(I find some solution on how to work with a function not variable)? Is there a way I can read any array in the c++ library? Or I have to deal with each of the variables in the interface file.

for now b is <Swig Object of type 'int (*)[24]' at 0x02F65158> when I try to use it in python

ps:
1. If possible I don't want to modify the cpp part.

I'm trying to access a variable, not a function.

So don't refer me to links that doesn't really answer my question, thanks.

答:
You'll find that passing things back and forth between languages is much easier if you use a one-dimensional array in which you access elements using, e.g. arr[y*WIDTH+x].

Since you are operating in C++ you can even wrap these arrays in classes with nice operator()(int x, int y) methods for use on the C++ side.

In fact, this is the internal representation which Numpy uses for arrays: they are all one-dimensional.

Title: Reading c++ 2d array in python swig


来源: stackexchange

问:
Android Studio Unit Testing
I am doing the unit testing on android studio, I create a test case in test class and on every time when I run that it give different output but when I debug it give me fine out put.It may be problem of caching or something else. I have also tried Invalidate studio and clean project but still occurring. Please Help.</p>

答:
In your @Before method, make sure to use Intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) to make sure the app is not already running in the background of your test when you begin testing. This could be what is introducing your cache issue.

to clarify, your @Before method should look something like this:

```<code>@Before
public void setup() {
    //Initialize UiDevice instance
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    mDevice = UiDevice.getInstance(instrumentation);

    mDevice.pressHome();

    Intent intent = new Intent("com.REDACTED.auto.diagnostics.dealer.MAIN");
    intent.setClassName("com.REDACTED.auto.diagnostics", "com.REDACTED.auto.diagnostics.dealer.MainActivity");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Context context = InstrumentationRegistry.getContext();
    context.startActivity(intent);
}
</code>```

There are simpler ways to do this if you have the source code, however in my case I did not

ContentLicense: CC BY-SA 3.0

Title: Android Studio Unit Testing

Body:
In your @Before method, make sure to use Intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) to make sure the app is not already running in the background of your test when you begin testing. This could be what is introducing your cache issue.

to clarify, your @Before method should look something like this:

@Before
public void setup() {
    //Initialize UiDevice instance
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    mDevice = UiDevice.getInstance(instrumentation);

    mDevice.pressHome();

    Intent intent = new Intent("com.REDACTED.auto.diagnostics.dealer.MAIN");
    intent.setClassName("com.REDACTED.auto.diagnostics", "com.REDACTED.auto.diagnostics.dealer.MainActivity");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Context context = InstrumentationRegistry.getContext();
    context.startActivity(intent);
}

There are simpler ways to do this if you have the source code, however in my case I did not


问:
Problems installing OpenMPI locally for use with CUDA

Short Version

I have CUDA code I need to run locally. Thus, I am trying to install OpenMPI following the OpenMPI directions. When I try to make my code, I receive very long error output, similar to what is described by the OpenMPI documentation. I tried to reinstall OpenMPI with the documentation's suggested fix, but now I get these errors during installation:

```<code>Making all in tools/ompi_info
make[2]: Entering directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
  CC       ompi_info.o
  CC       param.o
  CCLD     ompi_info
ld: warning: libimf.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libsvml.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libirng.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libintlc.so.5, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: .libs/ompi_info: hidden symbol `__intel_cpu_features_init_x' in /opt/intel/compilers_and_libraries_2017.4.196/linux/compiler/lib/intel64_lin/libirc.a(cpu_feature_disp.o) is referenced by DSO
ld: final link failed: Bad value
Makefile:1785: recipe for target 'ompi_info' failed
make[2]: *** [ompi_info] Error 1
make[2]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
Makefile:3353: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi'
Makefile:1806: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1
</code>```

What am I doing wrong? Please help! S.O.S.!

Long Version

I have CUDA code I need to run locally. Thus, I am trying to install OpenMPI following the OpenMPI directions. I have the tar stored as ~/Downloads/openmpi-2.1.1.tar.gz. Hance, I ran

```<code>$gunzip -c openmpi-2.1.1.tar.gz | tar xf -
$cd openmpi-2.1.1
$./configure --prefix=/opt/openmpi-2.1.1 &> configure_log1
$sudo make all install &> install_log_take1
</code>```

with success. Note that I changed the --prefix=/usr/local in the directions to --prefix=/opt/openmpi-2.1.1. I have included configure_log1 and install_log_take1.

When I try to make my code using my makefile makefile.ulfhednar,

```<code>$make -f makefile.ulfhednar clean
$make -f makefile.ulfhednar &> make_log1
</code>```

I receive a very long error output in make_log1 that looks similar to what is described by the OpenMPI documentation. It says the solution is to install OpenMPI with the configure options "./configure CC=icc CXX=icpc F77=ifort FC=ifort ...", so I reinstalled using the commands,

```<code>$cd ~/Downloads/openmpi-2.1.1
$sudo make uninstall
$sudo rm -r /opt/openmpi-2.1.1
$cd ..
$sudo rm -r openmpi-2.1.1

$gunzip -c openmpi-2.1.1.tar.gz | tar xf -
$cd openmpi-2.1.1

$which icc
/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icc
$which icpc
/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icpc
$which ifort
/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/ifort

$./configure --prefix=/opt/openmpi-2.1.1 CC=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icc CXX=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icpc F77=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/ifort FC=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/ifort &> configure_log2
$sudo make all install &> install_log_take2
</code>```

Here is configure_log2 and install_log_take2. Of note in install_log_take2 are the following lines:

```<code>Making all in tools/ompi_info
make[2]: Entering directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
  CC       ompi_info.o
  CC       param.o
  CCLD     ompi_info
ld: warning: libimf.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libsvml.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libirng.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libintlc.so.5, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: .libs/ompi_info: hidden symbol `__intel_cpu_features_init_x' in /opt/intel/compilers_and_libraries_2017.4.196/linux/compiler/lib/intel64_lin/libirc.a(cpu_feature_disp.o) is referenced by DSO
ld: final link failed: Bad value
Makefile:1785: recipe for target 'ompi_info' failed
make[2]: *** [ompi_info] Error 1
make[2]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
Makefile:3353: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi'
Makefile:1806: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1
</code>```

Sorry I had to upload all the log files to mediafire, pastebin didn't accept them because they were too large.

What am I doing wrong? Please help! S.O.S.!

答:
I have found the solution!!!

I logged into root and ran through the installation steps without using sudo.

```<code>#gunzip -c openmpi-2.1.1.tar.gz | tar xf -
#cd openmpi-2.1.1
#./configure --prefix=/opt/openmpi-2.1.1 CC=icc CXX=icpc FC=ifort
#make all install
</code>```

I was trying to use OpenMPI with the Intel Composer compilers and this was causing permissions issues. I followed the installation instructions found here, but I got the same problems I had before when trying to install. The issue was that the linker, ld "could not find" the proper libraries because those libraries are no longer provided in the $LD_LIBRARY_PATH variable when sudo is called. The only way to circumvent this is by logging into the root user and setting your $LD_LIBRARY_PATH variable to be identical to the one your normal user has.

I had been stuck on this for days and I'm jumping for joy now that it's sorted out! I hope this helps someone else in the future.

Body:
Short Version

I have CUDA code I need to run locally. Thus, I am trying to install OpenMPI following the OpenMPI directions. When I try to make my code, I receive very long error output, similar to what is described by the OpenMPI documentation. I tried to reinstall OpenMPI with the documentation's suggested fix, but now I get these errors during installation:

Making all in tools/ompi_info
make[2]: Entering directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
  CC       ompi_info.o
  CC       param.o
  CCLD     ompi_info
ld: warning: libimf.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libsvml.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libirng.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libintlc.so.5, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: .libs/ompi_info: hidden symbol `__intel_cpu_features_init_x' in /opt/intel/compilers_and_libraries_2017.4.196/linux/compiler/lib/intel64_lin/libirc.a(cpu_feature_disp.o) is referenced by DSO
ld: final link failed: Bad value
Makefile:1785: recipe for target 'ompi_info' failed
make[2]: *** [ompi_info] Error 1
make[2]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
Makefile:3353: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi'
Makefile:1806: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1

What am I doing wrong? Please help! S.O.S.!

Long Version

I have CUDA code I need to run locally. Thus, I am trying to install OpenMPI following the OpenMPI directions. I have the tar stored as ~/Downloads/openmpi-2.1.1.tar.gz. Hance, I ran

$gunzip -c openmpi-2.1.1.tar.gz | tar xf -
$cd openmpi-2.1.1
$./configure --prefix=/opt/openmpi-2.1.1 &> configure_log1
$sudo make all install &> install_log_take1

with success. Note that I changed the --prefix=/usr/local in the directions to --prefix=/opt/openmpi-2.1.1. I have included configure_log1 and install_log_take1.

When I try to make my code using my makefile makefile.ulfhednar,

$make -f makefile.ulfhednar clean
$make -f makefile.ulfhednar &> make_log1

I receive a very long error output in make_log1 that looks similar to what is described by the OpenMPI documentation. It says the solution is to install OpenMPI with the configure options "./configure CC=icc CXX=icpc F77=ifort FC=ifort ...", so I reinstalled using the commands,

$cd ~/Downloads/openmpi-2.1.1
$sudo make uninstall
$sudo rm -r /opt/openmpi-2.1.1
$cd ..
$sudo rm -r openmpi-2.1.1

$gunzip -c openmpi-2.1.1.tar.gz | tar xf -
$cd openmpi-2.1.1

$which icc
/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icc
$which icpc
/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icpc
$which ifort
/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/ifort

$./configure --prefix=/opt/openmpi-2.1.1 CC=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icc CXX=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/icpc F77=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/ifort FC=/opt/intel/compilers_and_libraries_2017.4.196/linux/bin/intel64/ifort &> configure_log2
$sudo make all install &> install_log_take2

Here is configure_log2 and install_log_take2. Of note in install_log_take2 are the following lines:

Making all in tools/ompi_info
make[2]: Entering directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
  CC       ompi_info.o
  CC       param.o
  CCLD     ompi_info
ld: warning: libimf.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libsvml.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libirng.so, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: warning: libintlc.so.5, needed by ../../../ompi/.libs/libmpi.so, not found (try using -rpath or -rpath-link)
ld: .libs/ompi_info: hidden symbol `__intel_cpu_features_init_x' in /opt/intel/compilers_and_libraries_2017.4.196/linux/compiler/lib/intel64_lin/libirc.a(cpu_feature_disp.o) is referenced by DSO
ld: final link failed: Bad value
Makefile:1785: recipe for target 'ompi_info' failed
make[2]: *** [ompi_info] Error 1
make[2]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi/tools/ompi_info'
Makefile:3353: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/hatfull/Downloads/openmpi-2.1.1/ompi'
Makefile:1806: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1

Sorry I had to upload all the log files to mediafire, pastebin didn't accept them because they were too large.

What am I doing wrong? Please help! S.O.S.!

Body:
I have found the solution!!!

I logged into root and ran through the installation steps without using sudo.

#gunzip -c openmpi-2.1.1.tar.gz | tar xf -
#cd openmpi-2.1.1
#./configure --prefix=/opt/openmpi-2.1.1 CC=icc CXX=icpc FC=ifort
#make all install

I was trying to use OpenMPI with the Intel Composer compilers and this was causing permissions issues. I followed the installation instructions found here, but I got the same problems I had before when trying to install. The issue was that the linker, ld "could not find" the proper libraries because those libraries are no longer provided in the $LD_LIBRARY_PATH variable when sudo is called. The only way to circumvent this is by logging into the root user and setting your $LD_LIBRARY_PATH variable to be identical to the one your normal user has.

I had been stuck on this for days and I'm jumping for joy now that it's sorted out! I hope this helps someone else in the future.


问:
Spring security - how to mention both form based and basic authentication
Is it possible to mention both form-based and basic authentication in Spring security using namespace configuration without overriding other ? So that the appliciation could serve both browser based request and remoting client.</p>

答: It is now possible with Spring Security 3.1.0</p>

ContentLicense: CC BY-SA 2.5


问:
Regular expression to select group of text/bunch of lines based on specific line of text
I have the text in below format

```<code>Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint4 @543fsdf
Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint1 @345277
Scenario: Sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt returned correct singular message
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur

@Sprint1 @xyz1234
Scenario: At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur
</code>```

I want to select whole scenario based on a line of text in it.

For eg.

based on the line 'Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'

I want the second scenario

```<code>Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla
</code>```

, also the third and fourth scenario - but not the first one

I am trying

```<code>Scenario[\s\S]*?Given sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua[\s\S]*?(?=(@|Scenario))
</code>```

But that gives me first and second scenarios together and third but no fourth scenario. I tried other patterns as well but not a lot of success. Help?

答:
I don't know if will help, but what I did was to match all lines with @ until the end of line. So you could replace that by null, if this is the case.

```<code>(@\V+)
</code>```

https://regex101.com/r/iCt1j2/1

Body:
I have the text in below format

Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint4 @543fsdf
Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint1 @345277
Scenario: Sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt returned correct singular message
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur

@Sprint1 @xyz1234
Scenario: At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur

I want to select whole scenario based on a line of text in it.

For eg.

based on the line 'Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'

I want the second scenario

Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

, also the third and fourth scenario - but not the first one

I am trying

Scenario[\s\S]*?Given sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua[\s\S]*?(?=(@|Scenario))

But that gives me first and second scenarios together and third but no fourth scenario. I tried other patterns as well but not a lot of success. Help?

Body:
I don't know if will help, but what I did was to match all lines with @ until the end of line. So you could replace that by null, if this is the case.

(@\V+)

https://regex101.com/r/iCt1j2/1


问:
rename batch of file remove anything in the parenthesis
I want to remove the file and remove anything in the parenthesis

Now I have file:

123-456(434).jpg

454-6hf(32).jpg

99-ggr4(44335).jpg

rename to:

123-456.jpg

454-6hf.jpg

99-ggr4.jpg

答:
This bash script will move the files as named:

```<code>#!/bin/bash
for f in *.jpg; do
   if [[ $f =~ ([^\)]+)\([^\)]+\)(.*) ]]; then
     mv "$f" "${BASH_REMATCH[1]}${BASH_REMATCH[2]}";
   fi
done
</code>```

Original:

ls [14]*

  123-456(434).jpg  454-6hf(32).jpg

Post:

ls [14]*

  123-456.jpg  454-6hf.jpg

Note: if the files all definitely start with a number, you could adjust the *.jpg or the match to ensure limiting to just those files. The example above would, e.g., move myfile(123).jpg to myfile.jpg. Changing to [0-9]*.jpg would limit to just .jpg files that started with a number.

Body:
This bash script will move the files as named:

#!/bin/bash
for f in *.jpg; do
   if [[ $f =~ ([^\)]+)\([^\)]+\)(.*) ]]; then
     mv "$f" "${BASH_REMATCH[1]}${BASH_REMATCH[2]}";
   fi
done

Original:

ls [14]*

  123-456(434).jpg  454-6hf(32).jpg

Post:

ls [14]*

  123-456.jpg  454-6hf.jpg

Note: if the files all definitely start with a number, you could adjust the *.jpg or the match to ensure limiting to just those files. The example above would, e.g., move myfile(123).jpg to myfile.jpg. Changing to [0-9]*.jpg would limit to just .jpg files that started with a number.


问:
D3 node position after transform
I am trying to get the new position of the node after it has been transformed. In this case I am moving a rectangle across the screen. I was hoping to be able to access the transform on the rectangle in another context but this only shows the starting position of the node. How do I get the node's final position?

The problem seems to be related to the use of transition() in combination with a transform function ("myTransform" in the example below). I just can't figure out what is going on.

var moveButton = d3.selectAll("#move");
moveButton.on("click", moveBox);

var myTransform = function(d) {
  return "translate(" + d.a + "," + d.b + ")";
};

var data = [{
  "a": 40,
  "b": 40
}];

var box = d3.selectAll("svg")
  .append("g")
  .selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("id", "myBox")
  .attr("height", "50")
  .attr("width", "100")
  .attr("fill", "green")

function moveBox(d) {
  box = d3.select("#myBox")
    .transition()
    .attr("transform", myTransform);

    // How do I retrieve the transform?
    //console.log(box.attr("transform"));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>

<body>
  <form action="move">
    <input id="move" name="move" type="button" value="Move" />
  </form>
  <svg>
</svg>
</body>

</html></code>```

答:
Sure, so you're looking to access the transform after the transition has finished. You can do so by using the transition's .on method, as documented in d3-transition and the life of a transition. In this case:

```<code>  box = d3.select("#myBox")
    .transition()
    .attr("transform", myTransform)
    .on('end', function() {
        console.log(box.attr("transform"));
    });
</code>```

Should do it for you.

Title: D3 node position after transform

Body:
I am trying to get the new position of the node after it has been transformed. In this case I am moving a rectangle across the screen. I was hoping to be able to access the transform on the rectangle in another context but this only shows the starting position of the node. How do I get the node's final position?

The problem seems to be related to the use of transition() in combination with a transform function ("myTransform" in the example below). I just can't figure out what is going on.

var moveButton = d3.selectAll("#move");
moveButton.on("click", moveBox);

var myTransform = function(d) {
  return "translate(" + d.a + "," + d.b + ")";
};

var data = [{
  "a": 40,
  "b": 40
}];

var box = d3.selectAll("svg")
  .append("g")
  .selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("id", "myBox")
  .attr("height", "50")
  .attr("width", "100")
  .attr("fill", "green")

function moveBox(d) {
  box = d3.select("#myBox")
    .transition()
    .attr("transform", myTransform);

    // How do I retrieve the transform?
    //console.log(box.attr("transform"));
}

  <form action="move">
    <input id="move" name="move" type="button" value="Move" />
  </form>
  <svg>
</svg>

Body:
Sure, so you're looking to access the transform after the transition has finished. You can do so by using the transition's .on method, as documented in d3-transition and the life of a transition. In this case:

  box = d3.select("#myBox")
    .transition()
    .attr("transform", myTransform)
    .on('end', function() {
        console.log(box.attr("transform"));
    });

Should do it for you.


问:
Regex to replace a part of string
I have a string like

```<code> "target:40,trg: tra:20,this:30"
</code>```

I want to replace trg:
or in other words, anything before colon followed by one empty space should be replaced.

I don't have any easy way to do it.
Any help will be great.

答:
I'm a newb and not sure about this question. But from what I understand I would do this.

```<code>import re
text = "target:40,trg: tra:20,this:30"
findText = re.compile(r": ")
mo = ft.search(text)
mog = mo.group()
textsplit = re.split((mog), text)[1]
print(textsplit)
</code>```

which will output:

```<code>tra:20,this:30
</code>```

Title: Regex to replace a part of string

Body:
I have a string like

 "target:40,trg: tra:20,this:30"

I want to replace trg:
or in other words, anything before colon followed by one empty space should be replaced.

I don't have any easy way to do it.
Any help will be great.

Body:
I'm a newb and not sure about this question. But from what I understand I would do this.

import re
text = "target:40,trg: tra:20,this:30"
findText = re.compile(r": ")
mo = ft.search(text)
mog = mo.group()
textsplit = re.split((mog), text)[1]
print(textsplit)

which will output:

tra:20,this:30


问:
how to deal with `GCC` in tensorflow installation with gpu?
I am installing tensorflow with Gpu support. There is an installation guide in the tensorflow web site which explain more about CUDA Toolkit. In this guide system requirement is described. A row in table 1 dedicate to GCC version and other ones is Kernel and etc. I know my ubuntu 16.4 LTS is based on kernel 4.4 but the GCC version dose not match with the table. My gcc is 5.4.0 and the table said that gcc-5.3.1 needed.
My OS  is Ubuntu 16.4 LTS xenial xerus and i have a Geforce GTX 1080 in my system.
There is two question.

1- What should i do? Do i need to downgrade it or gcc-5.4.0 work as well?

2- If it is necessary to downgrade , could anyone explain how ?

3- Why gcc-5.4.0 compiler does not exist in /usr/bin ? how should refer to it ?

答:
gcc-5.4 may work, but as it's not a supported configuration it's hard to say for sure. It may be worth giving it a try to see if you hit problems if you're reluctant to switch.

If you do want to switch, I like to use the update-alternatives approach to manage different versions of gcc on Ubuntu, as described here:

https://codeyarns.com/2015/02/26/how-to-switch-gcc-version-using-update-alternatives/


问:
Updating a column in SQL based on two foreign keys
I am wondering how you would go forward on updating a column by combining two foreign keys.

I have one table, FoodPackage, which looks like this:

```<code>create table FoodPackage(
PackageNumber int primary key auto_increment,
name varchar(45),
price int);
</code>```

Another table, Product, which looks like this:

```<code>create table Product(
ProductID int primary key auto_increment,
Category varchar(45),
ProductName varchar(45),
Price int,
Allergy varchar(45));
</code>```

And lastly, Orders, which looks like this:

```<code>create table Orders(
Ordernumber int primary key auto_increment,
PackageNumber int not null,
ProductID int not null,
UserID int not null,
Frequency int,
TotalPrice int,
OrderStatus varchar(45),
 FOREIGN KEY(PackageNumber)
    REFERENCES FoodPackage(PackageNumber),
 FOREIGN KEY(ProductID)
    REFERENCES Product(ProductID),
 FOREIGN KEY(UserID)
    REFERENCES Users(UserID));
</code>```

What I want to do is to update the totalprice column based on the values of FoodPackage.price and Product.Price combined. I have tried using an update statement like this:

```<code>UPDATE Orders, FoodPackage, Product SET Orders.TotalPrice= FoodPackage.Price + Product.Price;
</code>```

However, this will only give me a constant value.

Really appreciate any help!

答:
You need a joining condition between the tables.</p>

```<code>UPDATE Orders AS o
JOIN FoodPackage AS f ON o.PackageNumber = f.PackageNumber
JOIN Product AS p ON o.ProductID = p.ProductID
SET o.TotalPrice = f.Price + p.Price
</code>```

Body:
I am wondering how you would go forward on updating a column by combining two foreign keys.

I have one table, FoodPackage, which looks like this:

create table FoodPackage(
PackageNumber int primary key auto_increment,
name varchar(45),
price int);

Another table, Product, which looks like this:

create table Product(
ProductID int primary key auto_increment,
Category varchar(45),
ProductName varchar(45),
Price int,
Allergy varchar(45));

And lastly, Orders, which looks like this:

create table Orders(
Ordernumber int primary key auto_increment,
PackageNumber int not null,
ProductID int not null,
UserID int not null,
Frequency int,
TotalPrice int,
OrderStatus varchar(45),
 FOREIGN KEY(PackageNumber)
    REFERENCES FoodPackage(PackageNumber),
 FOREIGN KEY(ProductID)
    REFERENCES Product(ProductID),
 FOREIGN KEY(UserID)
    REFERENCES Users(UserID));

What I want to do is to update the totalprice column based on the values of FoodPackage.price and Product.Price combined. I have tried using an update statement like this:

UPDATE Orders, FoodPackage, Product SET Orders.TotalPrice= FoodPackage.Price + Product.Price;

However, this will only give me a constant value.

Really appreciate any help!

Body:
You need a joining condition between the tables.

UPDATE Orders AS o
JOIN FoodPackage AS f ON o.PackageNumber = f.PackageNumber
JOIN Product AS p ON o.ProductID = p.ProductID
SET o.TotalPrice = f.Price + p.Price


问:
AWS Server Size for Hosting
I am looking into purchasing server space with AWS to host what will eventually be over 50 websites. They will have many different ranges of traffic coming in. I would like to know if anyone has a recommendation on what size of server that would be able to handle this many sites.

Also, I was wondering if it's more cost effective/efficient to host an separate EC-2 instance for each site or too purchase a large umbrella server and host all sites on a single instance?

Thanks,

答:
Co-locating services on single/multiple servers is a core architecting decision your firm should make. It will directly impact the performance, security and cost of your systems.

The benefit of having multiple services on the same Amazon EC2 instance is that they can share resources (RAM, CPU) so if one application is busy, it has access to more total resources. This is in contrast to running each one on a separate instance, where there is a smaller, finite quantity of resources. Think of it like car-pooling vs riding motorbikes.

Sharing resources means you can probably lower costs, since you'll need less total capacity.

From a security perspective, running on separate instances is much better because they are isolated from each other. You should also investigate network isolation to prevent potential breaches between instances on the same virtual network.

You should also look at the ability to host all of these services using a multi-tenant system as opposed to 50 completely separate systems. This has further benefits in terms of sharing resources and reducing costs. For example, Salesforce.com doesn't run a separate computer for each customer -- all the customers use the same systems, but security and data is kept separate at the application layer.

Bottom line: There are some major architectural decisions to make if you wish to roll-out secure, performant systems.

Title: AWS Server Size for Hosting


问:
Read a local text file using Javascript
I have read some of the previous questions on this topic but I really need to be 100% sure!

Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?

I have tried several functions, here is one:

```<code>  function readFile (path) {
  var fso = new ActiveXObject('Scripting.FileSystemObject'),
      iStream=fso.OpenTextFile(path, 1, false);
  while(!iStream.AtEndOfStream) {
      document.body.innerHTML += iStream.ReadLine() + '<br/>';
  }
  iStream.Close();
}
readFile("testing.txt");
</code>```

The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.

Is this possible without having my own server?

答:
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!</p>

```<code><html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true);
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>
</code>```

Title: Read a local text file using Javascript

Body:
I have read some of the previous questions on this topic but I really need to be 100% sure!

Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?

I have tried several functions, here is one:

  function readFile (path) {
  var fso = new ActiveXObject('Scripting.FileSystemObject'),
      iStream=fso.OpenTextFile(path, 1, false);
  while(!iStream.AtEndOfStream) {
      document.body.innerHTML += iStream.ReadLine() + '
';
  }
  iStream.Close();
}
readFile("testing.txt");

The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.

Is this possible without having my own server?

Body:
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!

<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true);
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>


问:
How to preload SVG in Ionic view?
I built a mobile app with Ionic and on one of my views I have an SVG image of 202KB

The problem is that it takes very long to load that view/page. It takes up to 3-4 seconds load and display the view. Is there any way to load svg faster?

I tried to add svg and html view to Cache in advance:

```<code>$ionicTemplateCache('img/image.svg');
$ionicTemplateCache('views/maps.html');
</code>```

I also tried a preload factory that loads images in advance but that didn't help either.

```<code>var img = ['image.svg'];

//load all the images
preloader.preloadImages( imgs ).then(function() {
  // Loading was successful.
  console.log(" Loading was successful.");
}, function() {
  // Loading failed on at least one image.
  console.log("Loading failed on at least one image.");
});
</code>```

Below is how my app looks like:

Angular directive which is the svg image:

```<code>app.directive('svgMap', [function () {
    return {
      restrict: 'E',
      templateUrl: 'img/image.svg'
    }
}]);
</code>```

maps.html where the svg image is loaded

```<code><svg-map></svg-map>
</code>```

So, when I go to maps.html it takes very long to load.

答: In preloader you're calling .preloadImages( imgs ) but your image is in var img. Also, try to gzip you svg on the server-side (if not yet).

Title: How to preload SVG in Ionic view?

Body:
I built a mobile app with Ionic and on one of my views I have an SVG image of 202KB

The problem is that it takes very long to load that view/page. It takes up to 3-4 seconds load and display the view. Is there any way to load svg faster?

I tried to add svg and html view to Cache in advance:

$ionicTemplateCache('img/image.svg');
$ionicTemplateCache('views/maps.html');

I also tried a preload factory that loads images in advance but that didn't help either.

var img = ['image.svg'];

//load all the images
preloader.preloadImages( imgs ).then(function() {
  // Loading was successful.
  console.log(" Loading was successful.");
}, function() {
  // Loading failed on at least one image.
  console.log("Loading failed on at least one image.");
});

Below is how my app looks like:

Angular directive which is the svg image:

app.directive('svgMap', [function () {
    return {
      restrict: 'E',
      templateUrl: 'img/image.svg'
    }
}]);

maps.html where the svg image is loaded

<svg-map></svg-map>

So, when I go to maps.html it takes very long to load.


问:
Partial template specialization for specific type, c++
Using partial specialization of templates I would like to  create a function/method:

A) processing only one specific primitive type (int, double, float,...) of the formal parameter and for other types throwing exception

```<code>template <class T>
T min ( Point <T> p )
{
    /*if (T == int) continue;
    else throw exception*/
}
</code>```

B)  processing more non-primitive types (user defined types) of the formal parameter and for other types throwing exception...

Some code examples would be helpful (without c++ boost library). Thanks for your help.

答:
you can use boost::mpl here for part B but this is use boost:(

```<code>#include <boost/mpl/at.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/bool.hpp>

using namespace boost;

typedef mpl::map<
    mpl::pair<int, mpl::true_>,
    mpl::pair<double, mpl::false_>,
    mpl::pair<float, mpl::false_>
> TAllowedTypesForMin;

template <class T>
T min (T p)
{
    const bool allowed = mpl::at<TAllowedTypesForMin, T>::type::value;
    if (allowed)
    {

    }

    return p;
}
</code>```

EDIT

with compile time check everything is simpler:

```<code>#include <boost/mpl/set.hpp>
#include <boost/mpl/assert.hpp>

using namespace boost;

template<class T> struct Point {};
typedef mpl::set<int, double, float> TAllowedTypesForMin;

template <class T>
T min (Point<T> p)
{
    typedef mpl::has_key<TAllowedTypesForMin, T> allowedType;
    BOOST_MPL_ASSERT_MSG( allowedType::value, NOT_SUPPORTED_TYPE, () );

// do something

    return T();
}

int main()
{
        min(Point<long>());
        return 0;
}
</code>```

Body:
Using partial specialization of templates I would like to  create a function/method:

A) processing only one specific primitive type (int, double, float,...) of the formal parameter and for other types throwing exception

template <class T>
T min ( Point <T> p )
{
    /*if (T == int) continue;
    else throw exception*/
}

B)  processing more non-primitive types (user defined types) of the formal parameter and for other types throwing exception...

Some code examples would be helpful (without c++ boost library). Thanks for your help.

Body:
you can use boost::mpl here for part B but this is use boost:(

#include <boost/mpl/at.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/bool.hpp>

using namespace boost;

typedef mpl::map<
    mpl::pair<int, mpl::true_>,
    mpl::pair<double, mpl::false_>,
    mpl::pair<float, mpl::false_>
> TAllowedTypesForMin;

template <class T>
T min (T p)
{
    const bool allowed = mpl::at<TAllowedTypesForMin, T>::type::value;
    if (allowed)
    {

    }

    return p;
}

EDIT

with compile time check everything is simpler:

#include <boost/mpl/set.hpp>
#include <boost/mpl/assert.hpp>

using namespace boost;

template<class T> struct Point {};
typedef mpl::set<int, double, float> TAllowedTypesForMin;

template <class T>
T min (Point<T> p)
{
    typedef mpl::has_key<TAllowedTypesForMin, T> allowedType;
    BOOST_MPL_ASSERT_MSG( allowedType::value, NOT_SUPPORTED_TYPE, () );

// do something

    return T();
}

int main()
{
        min(Point<long>());
        return 0;
}


问:
What is the smallest AMD loader to date?
I am searching for an AMD loader that supports dynamic code loading, and that is very small.

The loader is to be used in a mobile/high latency environment, and the size of requirejs simply is too much.

I do NOT need:

-text plugins

-css plugins

-i18n plugins

What is the smallest AMD loader that supports these features? I'm looking for something that ideally is no larger than 5k when minified. Gzip is not to be included in this measure.

答:
I believe this is reasonably close to the AMD spec, and at 960 bytes minified (not counting the spurious newline at the end) might grab the top spot.

https://github.com/MaxMotovilov/eeMD


问:
TensorFlow: implicit broadcasting in element-wise addition/multiplication
How does the implicit broadcasting in tensorflow using + and * work?

If i Have two tensors, such that

```<code>a.get_shape() = [64, 10, 1, 100]
b.get_shape() = [64, 100]
(a+b).get_shape = [64, 10, 64, 100]
(a*b).get_shape = [64, 10, 64, 100]
</code>```

How does that become [64, 10, 64, 100]??

答:
I think that the broadcasting isn't doing what you intended. It's actually broadcasting both directions. Let me show you what I mean by modifying your example

```<code>a = tf.ones([64, 10, 1, 100])
b = tf.ones([128, 100])
print((a+b).shape) # prints "(64, 10, 128, 100)"
</code>```

From this we see that it broadcasts by matching the last dimensions first. It's implicitly tiling a across it's third dimension to match the size of b's first dimension, then implicitly adding singletons and tiling b across a's first two dimensions.

What I think you expected to do was to implicitly tile b across a's second dimension. To do that, you need b to be a different shape:

```<code>a = tf.ones([64, 10, 1, 100])
b = tf.ones([64, 1, 1, 100])
print((a+b).shape) # prints "(64, 10, 1, 100)"
</code>```

You can use tf.expand_dims() twice on your b to add the two singleton dimensions to match this shape.

Body:
How does the implicit broadcasting in tensorflow using + and * work?

If i Have two tensors, such that

a.get_shape() = [64, 10, 1, 100]
b.get_shape() = [64, 100]
(a+b).get_shape = [64, 10, 64, 100]
(a*b).get_shape = [64, 10, 64, 100]

How does that become [64, 10, 64, 100]??

Body:
I think that the broadcasting isn't doing what you intended. It's actually broadcasting both directions. Let me show you what I mean by modifying your example

a = tf.ones([64, 10, 1, 100])
b = tf.ones([128, 100])
print((a+b).shape) # prints "(64, 10, 128, 100)"

From this we see that it broadcasts by matching the last dimensions first. It's implicitly tiling a across it's third dimension to match the size of b's first dimension, then implicitly adding singletons and tiling b across a's first two dimensions.

What I think you expected to do was to implicitly tile b across a's second dimension. To do that, you need b to be a different shape:

a = tf.ones([64, 10, 1, 100])
b = tf.ones([64, 1, 1, 100])
print((a+b).shape) # prints "(64, 10, 1, 100)"

You can use tf.expand_dims() twice on your b to add the two singleton dimensions to match this shape.


问:
Is it possible to use assignment in a if statement?
I'd like to do something like below in Python 3:

import re

s = "abcde"

if match = re.search("abc(de)", s):
    print(match.group(1))
elif match = re.search("abc(fg)", s):
    print(match.group(1))
elif match = re.search("abc(hi)", s):
    print(match.group(1))
...
```

However, Python does not allow assignment in the condition clause of if statement and the code above cannot be executed.

How can I achieve this goal without getting errors? Thank you in advance.

答:
In Python, nope, you can only use expressions in your if statements. But you can delegate if you really want to do it:

```<code>import re

_delegate = None
def delegate_search(pattern=None, data=None):
    global _delegate
    if pattern is None:
        delegate = _delegate
        _delegate = None
        return delegate
    _delegate = delegate = re.search(pattern, data)
    return delegate

s = "abcde"

if delegate_search("abc(de)", s):
    print(delegate_search().group(1))
elif delegate_search("abc(fg)", s):
    print(delegate_search().group(1))
elif delegate_search("abc(hi)", s):
    print(delegate_search().group(1))
</code>```

And you can even use some magic to make it look as if you're not calling a function, but it's just silly to use it this way.

Body:
I'd like to do something like below in Python 3:

import re

s = "abcde"

if match = re.search("abc(de)", s):
    print(match.group(1))
elif match = re.search("abc(fg)", s):
    print(match.group(1))
elif match = re.search("abc(hi)", s):
    print(match.group(1))
...

However, Python does not allow assignment in the condition clause of if statement and the code above cannot be executed.

How can I achieve this goal without getting errors? Thank you in advance.

Body:
In Python, nope, you can only use expressions in your if statements. But you can delegate if you really want to do it:

import re

_delegate = None
def delegate_search(pattern=None, data=None):
    global _delegate
    if pattern is None:
        delegate = _delegate
        _delegate = None
        return delegate
    _delegate = delegate = re.search(pattern, data)
    return delegate

s = "abcde"

if delegate_search("abc(de)", s):
    print(delegate_search().group(1))
elif delegate_search("abc(fg)", s):
    print(delegate_search().group(1))
elif delegate_search("abc(hi)", s):
    print(delegate_search().group(1))

And you can even use some magic to make it look as if you're not calling a function, but it's just silly to use it this way.


问:
why php imagick extension not showing in phpinfo?
I am trying to activate php_imagic.dll extension in php.ini i download the extension file from internet and change my php.ini file by adding ;extension=php_imagick.dll

this line is not already in my php.ini i added manually but still extension is not visible at phpinfo.can anyone help me ?

UPDATE: i am using XAMPP

答:
You should remove the ";" ( semicolon ) character, its the commenting keyword in ini file(s) .

Change it to extension=php_imagick.dll without double quotes.


问:
How to make a material-ui TableRowColumn span multiple columns
It's like the html colspan attribute. Some rows with different numbers of column than the others.

thanks

答:
Simply add the attribute, like: </p>

```<code><TableRowColumn colSpan={6}>
</code>```

Body:
Simply add the attribute, like:

<TableRowColumn colSpan={6}>


问:
Template Linked List | Uninitialized variable error
I'm practicing implementing a Template Class Linked List with the Node struct within the implementation of the Linked List Class.  In the createNode() member function, when I initialize a pointer variable to a node struct, I get the compiler error: "Uninitialized local variable 'newNode' used"

I've found if I change the initialization to:

```<code>Node* newNode = new Node();
</code>```

That it works just fine.  I'm a bit confused as to why this matters if I can initialize the basic data types like int as:

```<code>int* intPtr;
</code>```

Why can't I do the same with structs??  My code is below:

```<code>#include <iostream>
#include <string>

template<class T>
class LinkedList
{
private:
    struct Node
    {
        T data;
        Node* next;
    };
    Node* head;
    Node* tail;
    int size;

public:
    LinkedList() : head{ nullptr }, tail{ nullptr }, size{ 0 }
    {
    }

    Node* createNode(T data)
    {
        Node* newNode;
        newNode->data = data;
        newNode->next = nullptr;

        return newNode;
    }

    void display()
    {
        Node* currentNode = head;

        while (currentNode)
        {
            std::cout << currentNode->data << std::endl;
            currentNode = currentNode->next;
        }
    }

    void push(T data)
    {
        Node* newNode = createNode(data);

        if (size == 0)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail->next = newNode;
            tail = newNode;
        }

        ++size;
    }
};

int main()
{
    LinkedList<int> list;

    list.push(5);
    list.push(3);
    list.push(6);

    list.display();

    std::cin.clear();
    std::cin.ignore(32767, '\n');
    std::cin.get();

    return 0;
}
</code>```

答:
You said:

I'm a bit confused as to why this matters if I can initialize the basic data types like int as:

```<code>int* intPtr;
</code>```

That's a wrong conclusion. If you use:

```<code>int* intPtr;
*intPtr = 10;
</code>```

you'll probably see the same warning/error from the compiler. The correct way to use intPtr will be to make sure it is initialized to point to a valid object before anything is assigned to it using *intPtr.

```<code>int* intPtr = new int;
*intPtr = 10;
</code>```

This is similar to using

```<code>Node* newNode = new Node();
newNode->data = data;
newNode->next = nullptr;
</code>```

in your code.

Body:
I'm practicing implementing a Template Class Linked List with the Node struct within the implementation of the Linked List Class.  In the createNode() member function, when I initialize a pointer variable to a node struct, I get the compiler error: "Uninitialized local variable 'newNode' used"

I've found if I change the initialization to:

Node* newNode = new Node();

That it works just fine.  I'm a bit confused as to why this matters if I can initialize the basic data types like int as:

int* intPtr;

Why can't I do the same with structs??  My code is below:

#include <iostream>
#include <string>

template<class T>
class LinkedList
{
private:
    struct Node
    {
        T data;
        Node* next;
    };
    Node* head;
    Node* tail;
    int size;

public:
    LinkedList() : head{ nullptr }, tail{ nullptr }, size{ 0 }
    {
    }

    Node* createNode(T data)
    {
        Node* newNode;
        newNode->data = data;
        newNode->next = nullptr;

        return newNode;
    }

    void display()
    {
        Node* currentNode = head;

        while (currentNode)
        {
            std::cout << currentNode->data << std::endl;
            currentNode = currentNode->next;
        }
    }

    void push(T data)
    {
        Node* newNode = createNode(data);

        if (size == 0)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail->next = newNode;
            tail = newNode;
        }

        ++size;
    }
};

int main()
{
    LinkedList<int> list;

    list.push(5);
    list.push(3);
    list.push(6);

    list.display();

    std::cin.clear();
    std::cin.ignore(32767, '\n');
    std::cin.get();

    return 0;
}

Body:
You said:

I'm a bit confused as to why this matters if I can initialize the basic data types like int as:

int* intPtr;

That's a wrong conclusion. If you use:

int* intPtr;
*intPtr = 10;

you'll probably see the same warning/error from the compiler. The correct way to use intPtr will be to make sure it is initialized to point to a valid object before anything is assigned to it using *intPtr.

int* intPtr = new int;
*intPtr = 10;

This is similar to using

Node* newNode = new Node();
newNode->data = data;
newNode->next = nullptr;

in your code.


问:
How do I programmatically retrieve the actual path to the "Program Files" folder?

Possible Duplicate:

  C# - How to get Program Files (x86) on Windows Vista 64 bit

I realize the odds of a user changing the Windows default of C:\Program Files is fairly slim, but stranger things have happened!

How can I get the correct path to Program Files from the system?

答:
```<code>Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
</code>```

gets "program files (x86)" in 64-bits Windows and "program files" in 32 bit.

Body:
Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

gets "program files (x86)" in 64-bits Windows and "program files" in 32 bit.


问:
PHP - Pull data from JSON
I have a JSON file where I'm struggling getting the data out. Here is the JSON.

```<code>{"data":[
        {"tag":"operatingrevenue","value":215639000000.0},
        {"tag":"totalrevenue","value":215639000000.0},
        {"tag":"operatingcostofrevenue","value":131376000000.0},
        {"tag":"totalcostofrevenue","value":131376000000.0},
        {"tag":"totalgrossprofit","value":84263000000.0},
        {"tag":"sgaexpense","value":14194000000.0},
        {"tag":"rdexpense","value":10045000000.0},
        {"tag":"totaloperatingexpenses","value":24239000000.0},
        {"tag":"totaloperatingincome","value":60024000000.0},
        {"tag":"otherincome","value":1348000000.0},
        {"tag":"totalotherincome","value":1348000000.0},
        {"tag":"totalpretaxincome","value":61372000000.0},
        {"tag":"incometaxexpense","value":15685000000.0},
        {"tag":"netincomecontinuing","value":45687000000.0},
        {"tag":"netincome","value":45687000000.0},
        {"tag":"netincometocommon","value":45687000000.0},
        {"tag":"weightedavebasicsharesos","value":5470820000.0},
        {"tag":"basiceps","value":8.35},
        {"tag":"weightedavedilutedsharesos","value":5500281000.0},
        {"tag":"dilutedeps","value":8.31},
        {"tag":"weightedavebasicdilutedsharesos","value":5471500000.0},
        {"tag":"basicdilutedeps","value":8.35},
        {"tag":"cashdividendspershare","value":2.18}]
</code>```

I'm converting it to an array using

```<code>$data = json_decode($jsondata, true);
</code>```

I can then pull the data by:

```<code>$operatingRevenue = $data['data'][0]['value'];
$totalrevenue = $data['data'][1]['value'];
</code>```

etc, however, I want to use the tag name and not just the order just in case the order changes in the JSON. Something like

```<code>$operatingRevenue = $data['data']['operatingRevenue'];
</code>```

答:
Iterate $data and use array_push.
Read it here. https://www.w3schools.com/php/func_array_push.asp</p>

```<code>$data = json_decode($jsondata, true);
$datas = [];
foreach($data['data'] as $val){
   array_push($datas,["tag"=>$val['tag'],"value"=>$val['tag']])
}
</code>```

Title: PHP - Pull data from JSON

Body:
I have a JSON file where I'm struggling getting the data out. Here is the JSON.

{"data":[
        {"tag":"operatingrevenue","value":215639000000.0},
        {"tag":"totalrevenue","value":215639000000.0},
        {"tag":"operatingcostofrevenue","value":131376000000.0},
        {"tag":"totalcostofrevenue","value":131376000000.0},
        {"tag":"totalgrossprofit","value":84263000000.0},
        {"tag":"sgaexpense","value":14194000000.0},
        {"tag":"rdexpense","value":10045000000.0},
        {"tag":"totaloperatingexpenses","value":24239000000.0},
        {"tag":"totaloperatingincome","value":60024000000.0},
        {"tag":"otherincome","value":1348000000.0},
        {"tag":"totalotherincome","value":1348000000.0},
        {"tag":"totalpretaxincome","value":61372000000.0},
        {"tag":"incometaxexpense","value":15685000000.0},
        {"tag":"netincomecontinuing","value":45687000000.0},
        {"tag":"netincome","value":45687000000.0},
        {"tag":"netincometocommon","value":45687000000.0},
        {"tag":"weightedavebasicsharesos","value":5470820000.0},
        {"tag":"basiceps","value":8.35},
        {"tag":"weightedavedilutedsharesos","value":5500281000.0},
        {"tag":"dilutedeps","value":8.31},
        {"tag":"weightedavebasicdilutedsharesos","value":5471500000.0},
        {"tag":"basicdilutedeps","value":8.35},
        {"tag":"cashdividendspershare","value":2.18}]

I'm converting it to an array using

$data = json_decode($jsondata, true);

I can then pull the data by:

$operatingRevenue = $data['data'][0]['value'];
$totalrevenue = $data['data'][1]['value'];

etc, however, I want to use the tag name and not just the order just in case the order changes in the JSON. Something like

$operatingRevenue = $data['data']['operatingRevenue'];

Body:
Iterate $data and use array_push.
Read it here. https://www.w3schools.com/php/func_array_push.asp

$data = json_decode($jsondata, true);
$datas = [];
foreach($data['data'] as $val){
   array_push($datas,["tag"=>$val['tag'],"value"=>$val['tag']])
}


问:
String Manipulation: Find the discount of a price/number while in a String in JavaScript
I had a technical interview and this question was particularly hard for me to answer. Not sure how to go about this issue, would really appreciate if someone helped me figure out this question.

You have a string that states the price of an item. You want to return a string with the all the numbers 15% off the original number.

```<code>example.)

if an item was 15% off

input string:

str1 = "This person bought an iphone for $500 and a macbook for $1400"

output string:

str2 = "This person bought an iphone for $425 and a macbook for $1190"
</code>```

I know I should split the string, and probably locate all the numbers that proceeds a "$" symbol but I am not sure how to go from there.

答:
Using String.replace with a RegExp and a callback receiving the full match and the matching group as parameters:

let str = "This person bought an iphone for $500 and a macbook for $1400"

let result = str.replace(/\$(\d+)/g, (match, price) => '$' + 0.85 * price);

console.log(result);```

I assumed you only want to match prices preceded by a dollar symbol. Depending on your needs, you could refine the RegExp to match prices with decimal points etc.

Body:
I had a technical interview and this question was particularly hard for me to answer. Not sure how to go about this issue, would really appreciate if someone helped me figure out this question.

You have a string that states the price of an item. You want to return a string with the all the numbers 15% off the original number.

example.)

if an item was 15% off

input string:

str1 = "This person bought an iphone for $500 and a macbook for $1400"

output string:

str2 = "This person bought an iphone for $425 and a macbook for $1190"

I know I should split the string, and probably locate all the numbers that proceeds a "$" symbol but I am not sure how to go from there.

Body:
Using String.replace with a RegExp and a callback receiving the full match and the matching group as parameters:

let str = "This person bought an iphone for $500 and a macbook for $1400"

let result = str.replace(/\$(\d+)/g, (match, price) => '$' + 0.85 * price);

console.log(result);

I assumed you only want to match prices preceded by a dollar symbol. Depending on your needs, you could refine the RegExp to match prices with decimal points etc.


问:
Does rest_framework coreapi not support PUT / PATCH?
I'm wanting to use the Python Client Library, but having no end of pain getting PUT/PATCH to work. Whenever I try using update / partial_update, the URL param isn't interpolated from the dictionary, and the server returns a 404.

```<code>[06-Jun-2017 12:30:05] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23
</code>```

Which clearly shows that the {cid} param was never replaced with the actual value. Which brings me to the TL/DR version of my question, does CoreAPI not support PUT / PATCH?

The PUT / PATCH options are correctly setup, according to this info:

```<code>GET /api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e90c/
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
</code>```

```<code>{
    "url": "http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/",
    "created": "2016-04-16T19:35:02.169898Z",
    "modified": "2017-05-30T17:25:29.768740Z",
    "cid": "2892c424-3a86-16bb-8b60-12a79900e8fb",
    "name": "10.0.0.0/8",
    "comments": "Local Area Network - 10.x",
    "builtin": true
}
</code>```

Now that I've blown most of a morning trying to make this work, I realize that there's no documentation example showing update / partial update.

So I thought I'd try using coreapi-cli instead, but I have the same problem.

```<code>coreapi action networks partial_update --param cid='2892c424-3a86-16bb-8b60-12a79900e8fb' --param comments='this is WAAAY too hard'
<Error: 404 Not Found>
    detail: "Not found."
</code>```

Django's logline shows that the URL param was never substituted from the 'cid' param provided:

```<code>[06-Jun-2017 13:07:01] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23
</code>```

I can use override params to force the URL, and this now updates as anticipated.

```<code>client.action(['networks', 'partial_update'],
          params={'comments': 'this is WAAAY too hard', 'cid': '2892c424-3a86-16bb-8b60-12a79900e8fb'},
          overrides={'url': 'http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/'},
          )
</code>```

But that feels haaacky, and should be utterly unnecessary. So...

Is this a bug?

Have I gotten the function signature wrong?

Does CoreAPI not support PUT / PATCH methods?

Edit

Here's the viewset

```<code>class LCModelViewSet(mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.DestroyModelMixin,
                     mixins.ListModelMixin,
                     GenericViewSet):
    """
    Base ModelViewSet
    """
    lookup_field = 'cid'

class NetworksViewSet(LCModelViewSet):
    queryset = Networks.objects.all()
    serializer_class = NetworksSerializer
    filter_class = NetworksFilter
</code>```

and the Router

```<code>router = DefaultRouter()
router.register(r'accounts/networks', av.NetworksViewSet, base_name='api-networks')
</code>```

and the output of router.routes

```<code>[Route(url='^{prefix}{trailing_slash}$', mapping={'get': 'list', 'post': 'create'}, name='{basename}-list', initkwargs={'suffix': 'List'}),
 DynamicListRoute(url='^{prefix}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={}),
 Route(url='^{prefix}/{lookup}{trailing_slash}$', mapping={'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}, name='{basename}-detail', initkwargs={'suffix': 'Instance'}),
 DynamicDetailRoute(url='^{prefix}/{lookup}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={})]
</code>```

Edit #2

At hurturk's suggestion, I reduced everything to defaults - views.ModelViewset and serializers.ModelSerializer, and put the lookup_field on the NetworksViewSet. Still same problem.

Then I removed the custom lookup field and just tried using the default id field (cid is not the PK), and VOILA, PUT/PATCH then worked - URL generated correctly! So, I wondered if for some reason it's a UUID-related issue.

Since name is a unique field, I set lookup_field = name. The same behavior as UUID. GET/POST methods work. PUT/PATCH don't "PATCH /api/accounts/networks/%7Bname%7D/ HTTP/1.1" 404 23.

So it seems to come to this, that when the lookup_field is the PK, then PUT/PATCH url is generated correctly. When lookup_field is some other field, then the URL lookup_field placeholder is never interpolated.

I don't know what to do. CID is a must-have requirement...

答:
This is certainly a bug with CoreAPI http transport as it is assuming all field names in schema are distinct. I have provided a PR to fix it but this might need further design considerations by the project owner.

As you also mentioned, making lookup field read-only is an alternative solution to the problem because that would cause it to appear only once in the field analysis.

Body:
I'm wanting to use the Python Client Library, but having no end of pain getting PUT/PATCH to work. Whenever I try using update / partial_update, the URL param isn't interpolated from the dictionary, and the server returns a 404.

[06-Jun-2017 12:30:05] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23

Which clearly shows that the {cid} param was never replaced with the actual value. Which brings me to the TL/DR version of my question, does CoreAPI not support PUT / PATCH?

The PUT / PATCH options are correctly setup, according to this info:

GET /api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e90c/
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "url": "http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/",
    "created": "2016-04-16T19:35:02.169898Z",
    "modified": "2017-05-30T17:25:29.768740Z",
    "cid": "2892c424-3a86-16bb-8b60-12a79900e8fb",
    "name": "10.0.0.0/8",
    "comments": "Local Area Network - 10.x",
    "builtin": true
}

Now that I've blown most of a morning trying to make this work, I realize that there's no documentation example showing update / partial update.

So I thought I'd try using coreapi-cli instead, but I have the same problem.

coreapi action networks partial_update --param cid='2892c424-3a86-16bb-8b60-12a79900e8fb' --param comments='this is WAAAY too hard'
<Error: 404 Not Found>
    detail: "Not found."

Django's logline shows that the URL param was never substituted from the 'cid' param provided:

[06-Jun-2017 13:07:01] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23

I can use override params to force the URL, and this now updates as anticipated.

client.action(['networks', 'partial_update'],
          params={'comments': 'this is WAAAY too hard', 'cid': '2892c424-3a86-16bb-8b60-12a79900e8fb'},
          overrides={'url': 'http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/'},
          )

But that feels haaacky, and should be utterly unnecessary. So...

Is this a bug?

Have I gotten the function signature wrong?

Does CoreAPI not support PUT / PATCH methods?

Edit

Here's the viewset

class LCModelViewSet(mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.DestroyModelMixin,
                     mixins.ListModelMixin,
                     GenericViewSet):
    """
    Base ModelViewSet
    """
    lookup_field = 'cid'

class NetworksViewSet(LCModelViewSet):
    queryset = Networks.objects.all()
    serializer_class = NetworksSerializer
    filter_class = NetworksFilter

and the Router

router = DefaultRouter()
router.register(r'accounts/networks', av.NetworksViewSet, base_name='api-networks')

and the output of router.routes

[Route(url='^{prefix}{trailing_slash}$', mapping={'get': 'list', 'post': 'create'}, name='{basename}-list', initkwargs={'suffix': 'List'}),
 DynamicListRoute(url='^{prefix}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={}),
 Route(url='^{prefix}/{lookup}{trailing_slash}$', mapping={'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}, name='{basename}-detail', initkwargs={'suffix': 'Instance'}),
 DynamicDetailRoute(url='^{prefix}/{lookup}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={})]

Edit #2

At hurturk's suggestion, I reduced everything to defaults - views.ModelViewset and serializers.ModelSerializer, and put the lookup_field on the NetworksViewSet. Still same problem.

Then I removed the custom lookup field and just tried using the default id field (cid is not the PK), and VOILA, PUT/PATCH then worked - URL generated correctly! So, I wondered if for some reason it's a UUID-related issue.

Since name is a unique field, I set lookup_field = name. The same behavior as UUID. GET/POST methods work. PUT/PATCH don't "PATCH /api/accounts/networks/%7Bname%7D/ HTTP/1.1" 404 23.

So it seems to come to this, that when the lookup_field is the PK, then PUT/PATCH url is generated correctly. When lookup_field is some other field, then the URL lookup_field placeholder is never interpolated.

I don't know what to do. CID is a must-have requirement...


问:
Partitioning table for amazon athena
I'm trying to partition data queried by amazon athena by year, month and day. However, when I try to query from the partitioned data, I cannot get any records. I followed the instructions found in this blog post.

Create table query:

```<code>CREATE external TABLE mvc_test2 (
ROLE struct<Scope: string, Id: string>,
ACCOUNT struct<ClientId: string, Id: string, Name: string>,
USER struct<Id: string, Name: string>,
IsAuthenticated INT,
Device struct<IpAddress: string>,
Duration double,
Id string,
ResultMessage string,
Application struct<Version: string, Build: string, Name: string>,
Timestamp string,
ResultCode INT
)
Partitioned by(year string, month string, day string)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION 's3://firehose-titlesdesk-logs/Mvc/'
</code>```

The table is created successfully, and the result message says:

"Query successful. If your table has partitions, you need to load these
  partitions to be able to query data. You can either load all
  partitions or load them individually. If you use the load all
  partitions (MSCK REPAIR TABLE) command, partitions must be in a format
  understood by Hive. Learn more."

Running

```<code>msck repair table mvc_test2;
</code>```

I get the result:

"Partitions not in
  metastore:    mvc_test2:2017/06/06/21 mvc_test2:2017/06/06/22"

At this point, I get no results when I try to query the table.

The logs are stored in a subfolder format by year/month/day/hour.
e.g: 's3://firehose-application-logs/process/year/month/day/hour'

How do I correctly partition the data?

答:
It appears that your directory format is 2017/06/06/22. This is not compatible with HIVE partitions, that have naming conversions of year=2017/month=06/day=06/hour=22.

Therefore, the current format of your data precludes your ability to use partitions. You would need to rename directories or (preferably) process your data through HIVE to store it in the correct format.

See also: Analyzing Data in S3 using Amazon Athena

Title: Partitioning table for amazon athena

Body:
I'm trying to partition data queried by amazon athena by year, month and day. However, when I try to query from the partitioned data, I cannot get any records. I followed the instructions found in this blog post.

Create table query:

CREATE external TABLE mvc_test2 (
ROLE struct<Scope: string, Id: string>,
ACCOUNT struct<ClientId: string, Id: string, Name: string>,
USER struct<Id: string, Name: string>,
IsAuthenticated INT,
Device struct<IpAddress: string>,
Duration double,
Id string,
ResultMessage string,
Application struct<Version: string, Build: string, Name: string>,
Timestamp string,
ResultCode INT
)
Partitioned by(year string, month string, day string)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION 's3://firehose-titlesdesk-logs/Mvc/'

The table is created successfully, and the result message says:

"Query successful. If your table has partitions, you need to load these
  partitions to be able to query data. You can either load all
  partitions or load them individually. If you use the load all
  partitions (MSCK REPAIR TABLE) command, partitions must be in a format
  understood by Hive. Learn more."

Running

msck repair table mvc_test2;

I get the result:

"Partitions not in
  metastore:    mvc_test2:2017/06/06/21 mvc_test2:2017/06/06/22"

At this point, I get no results when I try to query the table.

The logs are stored in a subfolder format by year/month/day/hour.
e.g: 's3://firehose-application-logs/process/year/month/day/hour'

How do I correctly partition the data?


问:
Building wpf Ribbon at runtime
I am trying to databind a ribbon control for dynamic menus.

```<code><ribbon:Ribbon>
   <ribbon:RibbonTab Header="Reports"
        ItemsSource="{Binding ReportMenus}"
        ItemTemplate="{StaticResource RibbonGroupDataTemplate}">
    </ribbon:RibbonTab>
    <ribbon:RibbonTab Header="Test">
     <ribbon:RibbonGroup Header="TestGROUP"
      ItemsSource="{Binding ReportMenus}"
      ItemTemplate="{StaticResource RibbonButtonDataTemplate}">
     </ribbon:RibbonGroup>
    </ribbon:RibbonTab>
</ribbon:Ribbon>
</code>```

The top ribbon tab is my 'real' ribbontab. The bottom started out as a manually built that I am verifying my theories with.

Here are the datatemplates I am trying to use:

```<code><Style TargetType="{x:Type ribbon:RibbonButton}">
   <Setter Property="Label"
           Value="{Binding ReportDisplayName}" />
</Style>

<DataTemplate x:Key="RibbonButtonDataTemplate">
   <ribbon:RibbonButton />
</DataTemplate>
</code>```

This is my first attempt at the Group DataTemplate:

```<code><HierarchicalDataTemplate x:Key="RibbonGroupDataTemplate" DataType="{x:Type Ribbon:RibbonGroup}"
 ItemsSource="{Binding Converter={StaticResource DebugConverter}}"
 ItemTemplate="{StaticResource RibbonButtonDataTemplate}">
   <TextBlock Text="{Binding Path=ReportDisplayName}" />
</HierarchicalDataTemplate>
</code>```

Then I was trying this one:

```<code><DataTemplate x:Key="RibbonGroupDataTemplate">
  <ribbon:RibbonGroup ItemsSource="{Binding Converter={StaticResource DebugConverter}}"
          ItemTemplate="{StaticResource RibbonButtonDataTemplate}" />
</DataTemplate>
</code>```

The problem is that I cant get the buttons to show up under the group. If I dont have a grouptemplate as in my second ribbontab, I can get it working.
But if I try to do the group dynamically as well it fails to create the buttons. Also by doing the datatemplate with the ribbongroup inside of it, the headings get cutoff. I already read about that and that was the reason for trying to use the HierarchicalDatatemplate. The Regular Datatemplate does not allow for itemsource or itemtemplate.

So How do i get a dynamic RibbonGroup to show Dynamic RibbonButtons?

I have implemented some other changes now and its at least filling it in, however its not correct.

Right now it looks like this:

I want it to look like this which is partially hardcoded.

here is the xaml

```<code><DataTemplate x:Key="RibbonButtonDataTemplate">
   <ribbon:RibbonButton />
</DataTemplate>

<HierarchicalDataTemplate x:Key="RibbonGroupDataTemplate"
                                  DataType="{x:Type ribbon:RibbonGroup}"
                                  ItemsSource="{Binding ReportsMenuCollection}"
                                  ItemTemplate="{StaticResource RibbonButtonDataTemplate}">
   <TextBlock Text="{Binding Path=ReportDisplayName}" />
</HierarchicalDataTemplate>
</code>```

the only thing I have left to try is changing my RibbonButtonDataTemplate to a hierarchical datatemplate.

答: You will need two Hierarchical data templates and two underlying binding entities one that represents a group and another that represents an item. The same concept would apply to a dynamic menu structure. </p>

Title: Building wpf Ribbon at runtime

Body:
I am trying to databind a ribbon control for dynamic menus.

<ribbon:Ribbon>
   <ribbon:RibbonTab Header="Reports"
        ItemsSource="{Binding ReportMenus}"
        ItemTemplate="{StaticResource RibbonGroupDataTemplate}">
    </ribbon:RibbonTab>
    <ribbon:RibbonTab Header="Test">
     <ribbon:RibbonGroup Header="TestGROUP"
      ItemsSource="{Binding ReportMenus}"
      ItemTemplate="{StaticResource RibbonButtonDataTemplate}">
     </ribbon:RibbonGroup>
    </ribbon:RibbonTab>
</ribbon:Ribbon>

The top ribbon tab is my 'real' ribbontab. The bottom started out as a manually built that I am verifying my theories with.

Here are the datatemplates I am trying to use:

<DataTemplate x:Key="RibbonButtonDataTemplate">
   <ribbon:RibbonButton />
</DataTemplate>

This is my first attempt at the Group DataTemplate:

<HierarchicalDataTemplate x:Key="RibbonGroupDataTemplate" DataType="{x:Type Ribbon:RibbonGroup}"
 ItemsSource="{Binding Converter={StaticResource DebugConverter}}"
 ItemTemplate="{StaticResource RibbonButtonDataTemplate}">
   <TextBlock Text="{Binding Path=ReportDisplayName}" />
</HierarchicalDataTemplate>

Then I was trying this one:

<DataTemplate x:Key="RibbonGroupDataTemplate">
  <ribbon:RibbonGroup ItemsSource="{Binding Converter={StaticResource DebugConverter}}"
          ItemTemplate="{StaticResource RibbonButtonDataTemplate}" />
</DataTemplate>

The problem is that I cant get the buttons to show up under the group. If I dont have a grouptemplate as in my second ribbontab, I can get it working.
But if I try to do the group dynamically as well it fails to create the buttons. Also by doing the datatemplate with the ribbongroup inside of it, the headings get cutoff. I already read about that and that was the reason for trying to use the HierarchicalDatatemplate. The Regular Datatemplate does not allow for itemsource or itemtemplate.

So How do i get a dynamic RibbonGroup to show Dynamic RibbonButtons?

I have implemented some other changes now and its at least filling it in, however its not correct.

Right now it looks like this:

I want it to look like this which is partially hardcoded.

here is the xaml

<DataTemplate x:Key="RibbonButtonDataTemplate">
   <ribbon:RibbonButton />
</DataTemplate>

<HierarchicalDataTemplate x:Key="RibbonGroupDataTemplate"
                                  DataType="{x:Type ribbon:RibbonGroup}"
                                  ItemsSource="{Binding ReportsMenuCollection}"
                                  ItemTemplate="{StaticResource RibbonButtonDataTemplate}">
   <TextBlock Text="{Binding Path=ReportDisplayName}" />
</HierarchicalDataTemplate>

the only thing I have left to try is changing my RibbonButtonDataTemplate to a hierarchical datatemplate.


问:
How can I test if an pointer type can be safely converted to another potiner type?
I'm trying to build a pointer class with conversion safeguards in it to monitor pointer conversions.  Specifically, I want it to do a dynamic_cast inside of an assert and make sure the result is not a nullptr.  Unfortunately, if the pointer does not point to a class type, it gives a compile-time error indicating that dynamic_cast cannot be used.

Next I tried:

```<code>assert( (std::is_same<T,T2>() || dynamic_cast<T*>(in_ptr)) );
</code>```

...but this approach still didn't work because short-circuiting only happens at run time; the same error occurred.

My next idea is to build a convert_ok struct that is specialized such that if both pointers are the same its operator() returns true, but otherwise it returns the bool result of a dynamic_cast.

I think this approach will work, but I feel like I must be missing something from the standard library. std::is_convertable comes close, but when moving from a base class to a derived class it can only know at run time if the conversion will be legal... hence the dynamic cast.

WHY: Since I know people will ask, I've built a Ptr template that reduces to a regular pointer when NDEBUG is set, but otherwise does reference counting and trips asserts if memory issues occur (reference count goes to 0 without delete, pointer accessed after deletion, pointer deleted multiple times, etc.) It has worked better for me than smart pointers because it does more bookkeeping in debug mode, while having a near-zero overhead when NDEBUG is set.  It's already helped me clean up some tricky pointer juggling, and I'm now working to extend its functionality.

答:
Use std::enable_if in combination with a test to see if dynamic_cast is well-formed to SFINAE the right assertion. This will avoid using dynamic_cast whenever it would be ill-formed, such as when:

Casting to or from a non-class type, or

Casting from a non-polymorphic class type A to a class type B where B is not an accessible base of A.

I am using this boilerplate to implement the test.

```<code>template <typename T, typename U>
using dynamic_cast_r = decltype(dynamic_cast<U*>(static_cast<T*>(nullptr)));

template <typename T, typename U>
using can_dynamic_cast = can_apply<dynamic_cast_r, T, U>;

template <typename T>
class foo
{
public:
    foo(T *p) : p(p) { }

public:
    template <typename U>
    typename std::enable_if<can_dynamic_cast<T, U>::value, bool>::type convert_ok()
    {
        return dynamic_cast<U*>(p) != nullptr;
    }

    template <typename U>
    typename std::enable_if<!can_dynamic_cast<T, U>::value, bool>::type convert_ok()
    {
        return std::is_same<T, U>::value;
    }

private:
    T *p;
};
</code>```

Demo

Body:
I'm trying to build a pointer class with conversion safeguards in it to monitor pointer conversions.  Specifically, I want it to do a dynamic_cast inside of an assert and make sure the result is not a nullptr.  Unfortunately, if the pointer does not point to a class type, it gives a compile-time error indicating that dynamic_cast cannot be used.

Next I tried:

assert( (std::is_same<T,T2>() || dynamic_cast<T*>(in_ptr)) );

...but this approach still didn't work because short-circuiting only happens at run time; the same error occurred.

My next idea is to build a convert_ok struct that is specialized such that if both pointers are the same its operator() returns true, but otherwise it returns the bool result of a dynamic_cast.

I think this approach will work, but I feel like I must be missing something from the standard library. std::is_convertable comes close, but when moving from a base class to a derived class it can only know at run time if the conversion will be legal... hence the dynamic cast.

WHY: Since I know people will ask, I've built a Ptr template that reduces to a regular pointer when NDEBUG is set, but otherwise does reference counting and trips asserts if memory issues occur (reference count goes to 0 without delete, pointer accessed after deletion, pointer deleted multiple times, etc.) It has worked better for me than smart pointers because it does more bookkeeping in debug mode, while having a near-zero overhead when NDEBUG is set.  It's already helped me clean up some tricky pointer juggling, and I'm now working to extend its functionality.

Body:
Use std::enable_if in combination with a test to see if dynamic_cast is well-formed to SFINAE the right assertion. This will avoid using dynamic_cast whenever it would be ill-formed, such as when:

Casting to or from a non-class type, or

Casting from a non-polymorphic class type A to a class type B where B is not an accessible base of A.

I am using this boilerplate to implement the test.

template <typename T, typename U>
using dynamic_cast_r = decltype(dynamic_cast<U*>(static_cast<T*>(nullptr)));

template <typename T, typename U>
using can_dynamic_cast = can_apply<dynamic_cast_r, T, U>;

template <typename T>
class foo
{
public:
    foo(T *p) : p(p) { }

public:
    template <typename U>
    typename std::enable_if<can_dynamic_cast<T, U>::value, bool>::type convert_ok()
    {
        return dynamic_cast<U*>(p) != nullptr;
    }

    template <typename U>
    typename std::enable_if<!can_dynamic_cast<T, U>::value, bool>::type convert_ok()
    {
        return std::is_same<T, U>::value;
    }

private:
    T *p;
};

Demo


问:
Insert elements in numpy array given X and Y index
I have the following code:

```
import numpy as np

b = np.full([20, 20], 0)

x = [3, 6, 3, 6]
y = [18, 18, 19, 19]

print(b)
for _x, _y in zip(y, x):
    b[_x][_y] = 1
    pass

print('\n')

print(b)```

However, I don't understand some of the things in there, such as the x and y coordinates. Why are they flipped?
Is there any cleaner way to implement this using a built-in numpy function?

答:
Create a smaller array (easier to display), and a pair of indices (forget the x,y labels):

```<code>In [270]: arr = np.zeros((10,10), int)
In [271]: I = [3,6,3,6]
In [272]: J = [4,4,5,5]
In [273]: for i,j in zip(I,J):
     ...:     arr[i,j] = i+j     # note the [i,j] indexing
In [274]: arr
Out[274]:
array([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  7,  8,  0,  0,  0,  0],  # row 3
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0, 10, 11,  0,  0,  0,  0],  # row 6
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0]])
#                      col 4 5
</code>```

We could have set the values directly with the I,J lists; or we can retrieve the values:

```<code>In [275]: arr[I,J]
Out[275]: array([ 7, 10,  8, 11])
</code>```

The convention with numpy 2d arrays, the first index is displayed as rows, the 2nd as columns.

np.meshgrid has an indexing parameter that accomodates different labeling:

```<code>In [279]: np.meshgrid([3,6],[4,5],indexing='xy')
Out[279]:
[array([[3, 6],
        [3, 6]]),
 array([[4, 4],
        [5, 5]])]
In [280]: np.meshgrid([3,6],[4,5],indexing='ij')
Out[280]:
[array([[3, 3],
        [6, 6]]),
 array([[4, 5],
        [4, 5]])]
</code>```

Displaying the array is one thing, plotting it as a scatter plot or image is another.

The default imshow parameters display the array the same orientation, with origin in the upper left.

```<code>plt.imshow(arr,origin='upper')
</code>```

I really should have given the array different dimensions, e.g.

```<code>In [289]: arr = np.arange(12).reshape(3,4)
In [290]: arr
Out[290]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
</code>```

The (3,4) shape is displayed as 3 rows, 4 columns.  This is a wide spread practice when talking about arrays and/or matrices.

Body:
I have the following code:

import numpy as np

b = np.full([20, 20], 0)

x = [3, 6, 3, 6]
y = [18, 18, 19, 19]

print(b)
for _x, _y in zip(y, x):
    b[_x][_y] = 1
    pass

print('\n')

print(b)

However, I don't understand some of the things in there, such as the x and y coordinates. Why are they flipped?
Is there any cleaner way to implement this using a built-in numpy function?

Body:
Create a smaller array (easier to display), and a pair of indices (forget the x,y labels):

In [270]: arr = np.zeros((10,10), int)
In [271]: I = [3,6,3,6]
In [272]: J = [4,4,5,5]
In [273]: for i,j in zip(I,J):
     ...:     arr[i,j] = i+j     # note the [i,j] indexing
In [274]: arr
Out[274]:
array([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  7,  8,  0,  0,  0,  0],  # row 3
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0, 10, 11,  0,  0,  0,  0],  # row 6
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0]])
#                      col 4 5

We could have set the values directly with the I,J lists; or we can retrieve the values:

In [275]: arr[I,J]
Out[275]: array([ 7, 10,  8, 11])

The convention with numpy 2d arrays, the first index is displayed as rows, the 2nd as columns.

np.meshgrid has an indexing parameter that accomodates different labeling:

In [279]: np.meshgrid([3,6],[4,5],indexing='xy')
Out[279]:
[array([[3, 6],
        [3, 6]]),
 array([[4, 4],
        [5, 5]])]
In [280]: np.meshgrid([3,6],[4,5],indexing='ij')
Out[280]:
[array([[3, 3],
        [6, 6]]),
 array([[4, 5],
        [4, 5]])]

Displaying the array is one thing, plotting it as a scatter plot or image is another.

The default imshow parameters display the array the same orientation, with origin in the upper left.

plt.imshow(arr,origin='upper')

I really should have given the array different dimensions, e.g.

In [289]: arr = np.arange(12).reshape(3,4)
In [290]: arr
Out[290]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

The (3,4) shape is displayed as 3 rows, 4 columns.  This is a wide spread practice when talking about arrays and/or matrices.


问:
Why is it not giving memory leak?
I have this code (modified from a tutorial I am following):

```<code>#import <Foundation/Foundation.h>

@class Car;
@class Person;

@interface Person: NSObject

@property Car* owningCar;

@end

@implementation Person:NSObject

-(void)dealloc {
    NSLog(@"Person is gone");
}

@end

@interface Car:NSObject

@property Person* owner;

@end

@implementation Car:NSObject

-(void)dealloc {
    NSLog(@"Car is gone");
}

@end

void testRefCycle () {
    Person* me = [[Person alloc] init];
    Car* civic = [[Car alloc] init];
    me.owningCar = civic;
    civic.owner = me;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        testRefCycle();
    }
    return 0;
}
</code>```

I opened up Profiler Leaks, and ran it, expecting to get Leaks, but nothing shows up. Why is there no leak if this creates a reference cycle?

When I ran the project, there is also no output. Why is there no output if there is no leaks?

答:
There is a leak, which is why there is no output — your dealloc methods never run.

But the leak detector never has a chance to detect it, because your program comes to an end in a millionth of a second. You do not have any persistent state over the longer term, which is what is needed for something to count as a leak.

If you ran testRefCycle in an app, for example, where the app itself persists over time, you would see the leak reported. But you are not going to see it in a one-line command-line program without a run loop, which is what you've got.

Title: Why is it not giving memory leak?

Body:
I have this code (modified from a tutorial I am following):

#import <Foundation/Foundation.h>

@class Car;
@class Person;

@interface Person: NSObject

@property Car* owningCar;

@end

@implementation Person:NSObject

-(void)dealloc {
    NSLog(@"Person is gone");
}

@end

@interface Car:NSObject

@property Person* owner;

@end

@implementation Car:NSObject

-(void)dealloc {
    NSLog(@"Car is gone");
}

@end

void testRefCycle () {
    Person* me = [[Person alloc] init];
    Car* civic = [[Car alloc] init];
    me.owningCar = civic;
    civic.owner = me;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        testRefCycle();
    }
    return 0;
}

I opened up Profiler Leaks, and ran it, expecting to get Leaks, but nothing shows up. Why is there no leak if this creates a reference cycle?

When I ran the project, there is also no output. Why is there no output if there is no leaks?


问:
How to update React-Native listview?
I am having strange behavior when a row is being added to my listview. I am not sure where my logic is wrong. I have tabs using react-native-tab-view. On Tab 2 I am adding a object to "Favorites" array that has is being displayed on Tab 4. Before I add the object this is what is being displayed

After I add the object and go back to Tab 4 this is what I am see

And Code

```<code>   const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})

constructor(props) {
    super(props)
    this.state = {
      favoriteDB: props.favorites,
      renderPlaceholder: true,
      dataSource: ds.cloneWithRows([])
    }
  }

 componentDidMount() {
    InteractionManager.runAfterInteractions(() => {
      this.setState({
        dataSource: ds.cloneWithRows(this.state.favoriteDB),
        renderPlaceholder: false
      })
    })
  }

  componentWillReceiveProps(prevProps) {
    const {favorites} = this.props

    if (JSON.stringify(favorites) != JSON.stringify(prevProps.favorites)) {
      this._updateFavorites()
    }
  }

  _updateFavorites() {
    const {favorites} = this.props

    this.setState({
      favoriteDB: favorites,
      dataSource: ds.cloneWithRows(favorites)
    })
  }

 render() {
    const {dataSource} = this.state
    const {visibleHeight, visibleWidth} = this.props

    if (this.state.renderPlaceholder)
      return <Placeholder/>

    return (
      <Container theme={theme}>
        <View style={{ flex:1, height: visibleHeight - 100, width: visibleWidth }}>
          <Row>
            <Col>
              <List>
                <ListView
                  style={{ height: visibleHeight - 100, width: visibleWidth }}
                  enableEmptySections={TRUE}
                  automaticallyAdjustContentInsets={FALSE}
                  initialListSize={100}
                  pageSize={100}
                  dataSource={dataSource}
                  renderRow={rowData => this._renderRow(rowData)}/>
              </List>
            </Col>
          </Row>
        </View>
      </Container>
    )
  }
</code>```

答:
I experienced this adding and removing rows to the input of cloneWithRows with ListView as well as the data array for the new SectionList.

My workaround is to add a key for ListView that changes when the dataSource changes (name and size worked).

```<code>   return (
    <SectionList
      key={"mylistview_" + this.props.maps.length}
      style=
   ...
</code>```

See https://stackoverflow.com/a/31481960/7223

Title: How to update React-Native listview?

Body:
I am having strange behavior when a row is being added to my listview. I am not sure where my logic is wrong. I have tabs using react-native-tab-view. On Tab 2 I am adding a object to "Favorites" array that has is being displayed on Tab 4. Before I add the object this is what is being displayed

After I add the object and go back to Tab 4 this is what I am see

And Code

   const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})

constructor(props) {
    super(props)
    this.state = {
      favoriteDB: props.favorites,
      renderPlaceholder: true,
      dataSource: ds.cloneWithRows([])
    }
  }

 componentDidMount() {
    InteractionManager.runAfterInteractions(() => {
      this.setState({
        dataSource: ds.cloneWithRows(this.state.favoriteDB),
        renderPlaceholder: false
      })
    })
  }

  componentWillReceiveProps(prevProps) {
    const {favorites} = this.props

    if (JSON.stringify(favorites) != JSON.stringify(prevProps.favorites)) {
      this._updateFavorites()
    }
  }

  _updateFavorites() {
    const {favorites} = this.props

    this.setState({
      favoriteDB: favorites,
      dataSource: ds.cloneWithRows(favorites)
    })
  }

 render() {
    const {dataSource} = this.state
    const {visibleHeight, visibleWidth} = this.props

    if (this.state.renderPlaceholder)
      return <Placeholder/>

    return (
      <Container theme={theme}>
        <View style={{ flex:1, height: visibleHeight - 100, width: visibleWidth }}>
          <Row>
            <Col>
              <List>
                <ListView
                  style={{ height: visibleHeight - 100, width: visibleWidth }}
                  enableEmptySections={TRUE}
                  automaticallyAdjustContentInsets={FALSE}
                  initialListSize={100}
                  pageSize={100}
                  dataSource={dataSource}
                  renderRow={rowData => this._renderRow(rowData)}/>
              </List>
            </Col>
          </Row>
        </View>
      </Container>
    )
  }

Body:
I experienced this adding and removing rows to the input of cloneWithRows with ListView as well as the data array for the new SectionList.

My workaround is to add a key for ListView that changes when the dataSource changes (name and size worked).

   return (
    <SectionList
      key={"mylistview_" + this.props.maps.length}
      style=
   ...

See https://stackoverflow.com/a/31481960/7223


问:
Iterative solving for unknowns in a fluids problem
I am a Mechanical engineer with a computer scientist question. This is an example of what the equations I'm working with are like:

x = √((y-z)×2/r)

  z = f×(L/D)×(x/2g)

  f = something crazy with x in it

  etc…(there are more equations with x in it)

The situation is this:

I need r to find x, but I need x to find z. I also need x to find f which is a part of finding z. So I guess a value for x, and then I use that value to find r and f. Then I go back and use the value I found for r and f to find x. I keep doing this until the guess and the calculated are the same.

My question is:

How do I get the computer to do this? I've been using mathcad, but an example in another language like C++ is fine.

答:
It appears that mathcad has many abstractions for iterative algorithms without the need to actually implement them directly using a "lower level" language. Perhaps this question is better suited for the mathcad forums at:

http://communities.ptc.com/index.jspa


问:
Do two installations of Oracle SQL Developer on the same machine conflict?
I already have oracle SQL developer installed in my machine. I want to install another oracle SQL developer in my computer that I want to use for my personal web application. Of course I can work with one SQL developer, but in order to ease my maintenance I am planing to have two.

So, do they conflict? Can I run my applications smoothly?

答:
yes you can have two copies of SQL Developer 'installed' on your computer. There's not an install process - there's nothing written to the registry for example, and there's no un-installer.

You unzip the application to a directory, and run the EXE.

SQL Developer will write its preferences to your User AppData Roaming profiles folder. If they're the same exact version #, they'll share a parent directory, but there is a system_cache folder that can handle multiple instances of the app.

The framework uses the system_cache folder under user settings to ...
1. Speed up SQL Developer startup.
2. Persist certain settings if multiple instances are opened. Each additional instance creates a system_cache_N, where N=1,2,..

In your scenario, I can't think why you would need to do this. You could simply start up the application twice - it would have the same net effect.

So, do they conflict? Can I run my applications smoothly?
    No. And, yes. But you don't need to do this.