问:
error:bad operand type for binary operation &&
Here's the code

```<code>import java.io.*;
class WORD2
 {
public void main() throws IOException
{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the sentence");
        String str=br.readLine().toUpperCase()+" ";
        int l=str.length();
        String word="";
        int p=0;
        String word2[]=new String[l];
        for(int i=0;i<str.length();i++)
        {
            char ch=str.charAt(i);
            **if((str.charAt(i))&&(str.charAt(i+1)!= ' '))**// THE ERROR COMES IN THIS STATEMNET SHOWING THE ERROR
            {
                if(ch!=' ')
                {
                    word=word+ch;   //TAKING EACH WORD
                }
                else
                {
                    word2[p++]=word;  //STORING EACH WORD
                    word="";
                }

        }}
        String q="";
            for(int k=0;k<p;k++)
            {
                q=q+word2[k]+" ";
            }
            System.out.print("q="+q);
        }}
</code>```

Its a program to remove the unnecessary blank space between the words in a sentence.

答:
```<code>if((str.charAt(i)!= ' ' )&&(str.charAt(i+1)!= ' '))
</code>```

is the correct syntax, since IF requires bool (true/false) to consider.
As you have it the first part returns char.
Also, make a check at str.charAt(i+1) else you will get StringIndexOutOfBoundsException!

Body:
Here's the code

import java.io.*;
class WORD2
 {
public void main() throws IOException
{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the sentence");
        String str=br.readLine().toUpperCase()+" ";
        int l=str.length();
        String word="";
        int p=0;
        String word2[]=new String[l];
        for(int i=0;i<str.length();i++)
        {
            char ch=str.charAt(i);
            **if((str.charAt(i))&&(str.charAt(i+1)!= ' '))**// THE ERROR COMES IN THIS STATEMNET SHOWING THE ERROR
            {
                if(ch!=' ')
                {
                    word=word+ch;   //TAKING EACH WORD
                }
                else
                {
                    word2[p++]=word;  //STORING EACH WORD
                    word="";
                }

        }}
        String q="";
            for(int k=0;k<p;k++)
            {
                q=q+word2[k]+" ";
            }
            System.out.print("q="+q);
        }}

Its a program to remove the unnecessary blank space between the words in a sentence.

Body:
if((str.charAt(i)!= ' ' )&&(str.charAt(i+1)!= ' '))

is the correct syntax, since IF requires bool (true/false) to consider.
As you have it the first part returns char.
Also, make a check at str.charAt(i+1) else you will get StringIndexOutOfBoundsException!


来源: stackexchange

问:
What is the best way to tell openMDAO driver or solver that it is impossible to evaluate the model at some point?
Sometimes there are points in a model in which it is impossible to evaluate the objective function, the unknowns or resids. Which is the best way to tell openMDAO that this is an invalid point?

Setting the unknowns and resids to nan, inf or some other way?

答:
OpenMDAO has a special error class, AnalysisError, specifically for this purpose. You should raise the analysis error any time you your analysis can't converge or compute valid outputs. </p>

<p>The linesearch algorithms all look for that and backtrack when they see it. Some of the gradient based optimizers can also handle it correctly (SLSQP for example). </p>

ContentLicense: CC BY-SA 3.0

Body:
OpenMDAO has a special error class, AnalysisError, specifically for this purpose. You should raise the analysis error any time you your analysis can't converge or compute valid outputs.

The linesearch algorithms all look for that and backtrack when they see it. Some of the gradient based optimizers can also handle it correctly (SLSQP for example).


问:
Leap.JS: How can I select items on a webpage using the LeapMotion?
I am looking to select items in a web page using the LeapMotion and I am struggling with programming this interaction.

Using this code as a base (but updating the link so it connects to the current SDK) I can get my cursor to move around the window based on where my hand is in space. However, I do not know how to make the equivalent of the event listener "click" using the LeapMotion. I am using Leap.js and have built a crude GUI using svg.js.

How do I program an event listener that selects using the LeapMotion in Javascript?

答:
I have working code with Leap motion. I did quize software. Here cursor is a div element which styled as:

```<code>    #cursor {
        width: 60px;
        height: 60px;
        position: fixed;
        margin-left: 20px;
        margin-top: 20px;
        z-index: 99999;
        opacity: 0.9;
        background: black;
        border-radius: 100%;
        background: -webkit-radial-gradient(100px 100px, circle, #f00, #ff6a00);
        background: -moz-radial-gradient(100px 100px, circle, #f00, #ff6a00);
        background: radial-gradient(100px 100px, circle, #f00, #ff6a00);

    }
</code>```

and Java script at bottom. What I did, I get HTML element by position and triggering click event on it by tap gestures.

```<code>    var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
   // Setting cursor and output position
   window.cursor = $('#cursor');
    var controller= Leap.loop(function(frame) {

    if (frame.pointables.length > 0) {
        try
        {

          var position = frame.pointables[0].stabilizedTipPosition;
          var normalized = frame.interactionBox.normalizePoint(position);
            var cx = w * normalized[0];
            var cy = h * (1 - normalized[1]);
            $('#cursor').css('left', cx);
            $('#cursor').css('top', cy);

        }catch(e){
            console.error(e);
        }
    }
});
 controller.use('screenPosition', {
  scale: 1
});
controller.on('gesture', onGesture);
function onGesture(gesture,frame)
{
        try
        {
            // If gesture type is keyTap
            switch(gesture.type)
            {
                case 'keyTap':
                case 'screenTap':

                  var position = frame.pointables[0].stabilizedTipPosition;
                  var normalized = frame.interactionBox.normalizePoint(position);
                    //Hiding cursor for getting background element
                    cursor.hide();
                    // Trying find element by position
                    var cx = w * normalized[0];
                    var cy = h * (1 - normalized[1]);
                    var el = document.elementFromPoint(cx, cy);
                    cursor.show();
                    console.log(el);
                    if (el) {
                        $(el).trigger("click");
                    }

                break;
            }
        }
        catch (e) {
            console.info(e);
        }
}
</code>```

Body:
I have working code with Leap motion. I did quize software. Here cursor is a div element which styled as:

    #cursor {
        width: 60px;
        height: 60px;
        position: fixed;
        margin-left: 20px;
        margin-top: 20px;
        z-index: 99999;
        opacity: 0.9;
        background: black;
        border-radius: 100%;
        background: -webkit-radial-gradient(100px 100px, circle, #f00, #ff6a00);
        background: -moz-radial-gradient(100px 100px, circle, #f00, #ff6a00);
        background: radial-gradient(100px 100px, circle, #f00, #ff6a00);

    }

and Java script at bottom. What I did, I get HTML element by position and triggering click event on it by tap gestures.

    var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
   // Setting cursor and output position
   window.cursor = $('#cursor');
    var controller= Leap.loop(function(frame) {

    if (frame.pointables.length > 0) {
        try
        {

          var position = frame.pointables[0].stabilizedTipPosition;
          var normalized = frame.interactionBox.normalizePoint(position);
            var cx = w * normalized[0];
            var cy = h * (1 - normalized[1]);
            $('#cursor').css('left', cx);
            $('#cursor').css('top', cy);

        }catch(e){
            console.error(e);
        }
    }
});
 controller.use('screenPosition', {
  scale: 1
});
controller.on('gesture', onGesture);
function onGesture(gesture,frame)
{
        try
        {
            // If gesture type is keyTap
            switch(gesture.type)
            {
                case 'keyTap':
                case 'screenTap':

                  var position = frame.pointables[0].stabilizedTipPosition;
                  var normalized = frame.interactionBox.normalizePoint(position);
                    //Hiding cursor for getting background element
                    cursor.hide();
                    // Trying find element by position
                    var cx = w * normalized[0];
                    var cy = h * (1 - normalized[1]);
                    var el = document.elementFromPoint(cx, cy);
                    cursor.show();
                    console.log(el);
                    if (el) {
                        $(el).trigger("click");
                    }

                break;
            }
        }
        catch (e) {
            console.info(e);
        }
}


问:
Not able to use JpaReposiory?
I have already added the mysql connector dependency

```<code><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>
</code>```

I have made a repository package and made an interface in it.

in that when I made an Interface, name Teacher

```<code>public interface TeacherRepository extends  JpaRe
</code>```

when I press ctrl + space it is not auto completing meaning there is no available interface like that.

What could be the problem?

答:
I assume you have already parent dependency like that

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>
</code>```

JpaRepository coming with this dependency in springboot:

```<code> <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
</code>```

try this hope will helpful

Title: Not able to use JpaReposiory?

Body:
I have already added the mysql connector dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

I have made a repository package and made an interface in it.

in that when I made an Interface, name Teacher

public interface TeacherRepository extends  JpaRe

when I press ctrl + space it is not auto completing meaning there is no available interface like that.

What could be the problem?

Body:
I assume you have already parent dependency like that

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>

JpaRepository coming with this dependency in springboot:

 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

try this hope will helpful


问:
Spring Boot: Make property non-configurable
In Spring Boot I have several options to externalize my configuration. However, how can I make such properties non-configurable, i.e. readonly.

Concretly, I want to set server.tomcat.max-threads to a fixed value and do not want somebody who is going to start the application to have the ability to change it. This could easily be done by passing it as a command line argument for instance.

It's probably not possible by default, maybe someone could suggest workarounds?

答:
You have 2 options

Set System.setProperty("prop", "value") Property hard coded

Use properties that will override all other properties

Set system property hard coded

```<code>    public static void main(String[] args) {
      System.setProperty("server.tomcat.max-threads","200");
      SpringApplication.run(DemoApplication.class, args);
    }
</code>```

Properties in secure.properties will override all others (see, Prevent overriding some property in application.properties - Spring Boot)

```<code>@Configuration
public class SecurePropertiesConfig {

@Autowired
private ConfigurableEnvironment env;

@Autowired
public void setConfigurableEnvironment(ConfigurableEnvironment env) {
  try {
    final Resource resource = new
    ClassPathResource("secure.properties");
    env.getPropertySources().addFirst(new
        PropertiesPropertySource(resource.getFilename(),
        PropertiesLoaderUtils.loadProperties(resource)));
  } catch (Exception ex) {
    throw new RuntimeException(ex.getMessage(), ex);
  }
}
</code>```

Body:
You have 2 options

Set System.setProperty("prop", "value") Property hard coded

Use properties that will override all other properties

Set system property hard coded

    public static void main(String[] args) {
      System.setProperty("server.tomcat.max-threads","200");
      SpringApplication.run(DemoApplication.class, args);
    }

Properties in secure.properties will override all others (see, Prevent overriding some property in application.properties - Spring Boot)

@Configuration
public class SecurePropertiesConfig {

@Autowired
private ConfigurableEnvironment env;

@Autowired
public void setConfigurableEnvironment(ConfigurableEnvironment env) {
  try {
    final Resource resource = new
    ClassPathResource("secure.properties");
    env.getPropertySources().addFirst(new
        PropertiesPropertySource(resource.getFilename(),
        PropertiesLoaderUtils.loadProperties(resource)));
  } catch (Exception ex) {
    throw new RuntimeException(ex.getMessage(), ex);
  }
}


问:
Creating Xcode project from command line
My question is how can I create and Xcode project from the command line. By create I don't mean building a project. I mean how can i create a project forlder i.e shift + cmd + N. </p>

答:
An Xcode project consists of the source files for the project and and .xcodeproj folder (it looks like a file, but it's actually a bundle, i.e. a folder and files within it treated by Finder as a single object).

If you look inside the .xcodeproj folder (you can do this with the terminal app or you can right-click on the .xcodeproj bundle and select "Show Package Contents") you will see several files. The only file that matter is project.pbxproj. The format of this file is undocumented, but it is a text file and if you take a look at it, the format doesn't seem too complicated.

To generate a project you need to create a folder with an appropriate .xcodeproj folder within it and an appropriate project.pbxproj file inside that folder. If your project needs are simple, you could always start with a canned project.pbxproj file generated by Xcode and stick it in your .xcodeproj folder.


问:
Ember: Nested findRecord calls to to associate one model with another only work once
I have two Ember models which define a relationship in which a license can belong to a customer, and a customer can have many licenses:

models/license.js

export default DS.Model.extend({
  code: DS.attr('string'),
  customer: DS.belongsTo('customer'),
});```
</div>
</div>
</p>

<p><strong>models/customer.js</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export default DS.Model.extend({
  license: DS.hasMany('license'),
});</code>```

In my route I have a function that sets which customer a license belongs to. I have to fetch both the relevant customer and license records from Ember data, so I use nested findRecord calls.

routes/license.js

updateLicense: function(license) {
  var self = this;
  self.get('store').findRecord('license', license.id).then(function(licenseRecord) {
    self.get('store').findRecord('customer', 11).then(function(customer) {
      licenseRecord.set('customer', customer);
      licenseRecord.set('code', '23412342');
    });
  });
}```
</div>
</div>
</p>

<p>The first time the <strong>updateLicense</strong> action runs, the customer is correctly set for the relevant license record. The HBS below correctly shows the customer ID where <code>{{license.customer.id}}</code> exists.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><td class="customer">{{license.customer.id}}<button {{action 'updateLicense'}}>Update</button></td></code>```

However, each time the action runs after that, the customer is set and then immediately unset, hence the ID appears for an instant and then disappears. The data tab in Ember inspector confirms that the customer relationship for these licenses has a value of null for data.

The line licenseRecord.set('code', '23412342'); in the updateLicense action always works correctly. Why would Ember data be setting and then unsetting the customer for all but the first license?

答:
I found a workaround. The license object that is passed into the updateLicense action can simply have the customer set:

routes/licenses.js

  self.get('store').findRecord('customer', customerId).then(function(customer) {
    license.set('customer', customer);
    license.set('code', '23412342');
});```

Body:
I have two Ember models which define a relationship in which a license can belong to a customer, and a customer can have many licenses:

models/license.js

export default DS.Model.extend({
  code: DS.attr('string'),
  customer: DS.belongsTo('customer'),
});

models/customer.js

export default DS.Model.extend({
  license: DS.hasMany('license'),
});

In my route I have a function that sets which customer a license belongs to. I have to fetch both the relevant customer and license records from Ember data, so I use nested findRecord calls.

routes/license.js

updateLicense: function(license) {
  var self = this;
  self.get('store').findRecord('license', license.id).then(function(licenseRecord) {
    self.get('store').findRecord('customer', 11).then(function(customer) {
      licenseRecord.set('customer', customer);
      licenseRecord.set('code', '23412342');
    });
  });
}

The first time the updateLicense action runs, the customer is correctly set for the relevant license record. The HBS below correctly shows the customer ID where {{license.customer.id}} exists.

{{license.customer.id}}<button {{action 'updateLicense'}}>Update</button>

However, each time the action runs after that, the customer is set and then immediately unset, hence the ID appears for an instant and then disappears. The data tab in Ember inspector confirms that the customer relationship for these licenses has a value of null for data.

The line licenseRecord.set('code', '23412342'); in the updateLicense action always works correctly. Why would Ember data be setting and then unsetting the customer for all but the first license?


问:
Center vertically a div in Bootstrap 4
I want to center automatically a div on my paga using bootstrap 3 but I cannot achieve it. I got an image (with a fixed responsive height) and I want the text to be centered (horizontally and verticaly)

I've made a bootly : https://www.bootply.com/4AyZFwlOdE

答:
Different ways of aligning content in the center(horizontal and vertical) given in the codepen link below:

```<code>.style2{
  display: table;
  width: 100%;
  height: 30vh;
  background-color: #8E113F;
  margin-bottom: 20px;
  div{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    color: #fff;
  }
}
</code>```

https://codepen.io/kk2989/pen/LNjojY

Title: Center vertically a div in Bootstrap 4

Body:
Different ways of aligning content in the center(horizontal and vertical) given in the codepen link below:

.style2{
  display: table;
  width: 100%;
  height: 30vh;
  background-color: #8E113F;
  margin-bottom: 20px;
  div{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    color: #fff;
  }
}

https://codepen.io/kk2989/pen/LNjojY


问:
Remove app title bar android
I know this question has been asked million times but whichever method I use is not good for me.

If I use

```<code>android:theme="@android:style/Theme.NoTitleBar"
</code>```

in the manifest file, the whole theme of the app changes. If I put

```<code>requestWindowFeature(Window.FEATURE_NO_TITLE);
</code>```

in the onCreate activities, it shows up shortly when starting an app.

Btw I don't have any theme selected, just using standard android.

答:
If you have made a custom theme in styles.xml you can do this:

```<code><style name="AppTheme" parent="android:Theme.Material.Light">
    <!-- Override the android colour scheme etc. -->
    <item name="android:colorPrimary">@color/color_primary</item>
</style>
</code>```

To remove the Action bar and title add to styles.xml:

```<code><style name="AppTheme.NoActionBar">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>
</code>```

Then in your AndroidManifest.xml you can use your custom theme with or without the action bar

```<code><application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"> <---- With action bar
    <activity
        android:theme="@style/AppTheme.NoActionBar"> <---- No action bar
        <intent-filter>
etc...
</code>```

Title: Remove app title bar android

Body:
I know this question has been asked million times but whichever method I use is not good for me.

If I use

android:theme="@android:style/Theme.NoTitleBar"

in the manifest file, the whole theme of the app changes. If I put

requestWindowFeature(Window.FEATURE_NO_TITLE);

in the onCreate activities, it shows up shortly when starting an app.

Btw I don't have any theme selected, just using standard android.

Body:
If you have made a custom theme in styles.xml you can do this:

<style name="AppTheme" parent="android:Theme.Material.Light">
    <!-- Override the android colour scheme etc. -->
    <item name="android:colorPrimary">@color/color_primary</item>
</style>

To remove the Action bar and title add to styles.xml:

<style name="AppTheme.NoActionBar">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then in your AndroidManifest.xml you can use your custom theme with or without the action bar

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"> <---- With action bar
    <activity
        android:theme="@style/AppTheme.NoActionBar"> <---- No action bar
        <intent-filter>
etc...


问:
Django - JQuery AJAX : How to filter "POST"-ed json on "GET"?
When passing a JSON to Django views, it's supposed to be using POST. Using GET will append a long URL that would throw a long URI error.

I am trying to implement a filter on objects in JSON type of functionality using ajax. I have two filter options, by text and by dropdown, where the users can filter one or the other or both.

To do this I pass these two data using GET.

So essentially its:

JSON : POST

filter1 & filter2 : GET

The main problem is, where I can't keep the POST-ed json (ofcourse, since its POST) but its also unconventional to make a global variable in Python (not like in Java) so I can't keep it until GET gets called so the filters passed can use it on those objects (not directly from the models).

Thank you so much in advance for giving suggestions!

答: Django Maintain Session in a very good way you can use Django Session Variables there Or u Can Pass the filter data in Post along with your data </p>


问:
How to get active kernel name in Jupyter notebook
I would like to make a notebook that prints the active kernel name.
I registered multiple venvs as kernels using the

```<code>python -m ipykernel install --user --name <kernel_name>
</code>```

In the notebook I would like to print some metadata about the active kernel.

How can one get the name of the active kernel?

EDIT:

Here are the particular versions in my stack

```<code>ipykernel==4.5.2
ipython==5.3.0
jupyter==1.0.0
</code>```

nevertheless, the question should be answered in general.

答:
One way to do this is using Javascript within the notebook, and executing some code to make the string available in Python:

```<code>%%javascript
var kernel = Jupyter.notebook.kernel
kernel.execute('kernel_name = ' + '"' + kernel.name + '"')
</code>```

Then you have the kernel name in Python:

```<code>print(kernel_name)
# my-kernel
</code>```

As an added bonus, you can use the jupyter_client module to find more information about the kernel once you have its name:

```<code>from jupyter_client import kernelspec
spec = kernelspec.get_kernel_spec(kernel_name)
print(spec.resource_dir)
# /path/to/my/kernel
</code>```

Body:
I would like to make a notebook that prints the active kernel name.
I registered multiple venvs as kernels using the

python -m ipykernel install --user --name <kernel_name>

In the notebook I would like to print some metadata about the active kernel.

How can one get the name of the active kernel?

EDIT:

Here are the particular versions in my stack

ipykernel==4.5.2
ipython==5.3.0
jupyter==1.0.0

nevertheless, the question should be answered in general.

Body:
One way to do this is using Javascript within the notebook, and executing some code to make the string available in Python:

%%javascript
var kernel = Jupyter.notebook.kernel
kernel.execute('kernel_name = ' + '"' + kernel.name + '"')

Then you have the kernel name in Python:

print(kernel_name)
# my-kernel

As an added bonus, you can use the jupyter_client module to find more information about the kernel once you have its name:

from jupyter_client import kernelspec
spec = kernelspec.get_kernel_spec(kernel_name)
print(spec.resource_dir)
# /path/to/my/kernel


问:
Question regarding C loops
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

```<code>for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}
</code>```

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}
</code>```

Thanks!
Amit

答:
Two things:

I'm assuming the l.0 is a type and your l is actually a 1.

Secondly, why are you using k in your for loop instead of using i?  Try using this instead:

```<code>for (i=0; i<nrow; i++) {
    dat[i]=1.0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Question regarding C loops

Body:
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}

Thanks!
Amit

Body:
Two things:

I'm assuming the l.0 is a type and your l is actually a 1.

Secondly, why are you using k in your for loop instead of using i?  Try using this instead:

for (i=0; i<nrow; i++) {
    dat[i]=1.0;
}


问:
Iteration over the dictionary and extracting values
I have a dictionary (result_dict) as follows.

```<code>{'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0',
</code>```

This contains more than 150 usernames (e.g. 11333216@N05) . I want to extract 'mobileurl' for each user and create a dataframe containing username and mobileurl columns. I couldn't find a way to iterate each user and extract his mobileurl as indexing is impossible. However, I have extract the mobileurl for one of the users as follows.

```<code>result_dict['76617062@N08']["person"]["mobileurl"]['_content']

'https://m.flickr.com/photostream.gne?id=76524249'
</code>```

Would be grateful if someone can help, as I'm a bit new to python.

答:
I think you could also try to do it more of a pandas way instead of pure dictionary iteration. it's not necessarily the fastest but given you are new to python and pandas, I think it's good thing to know that pandas can handle this well.

I am assuming you are using pandas DataFrame, not just dictionary. you could easily achieve the same purpose without converting your json to pandas DataFrame. i.e. other answers will work even if you are not a pandas DataFrame. they are also valid python dictionary syntax.

```<code>urls = result_dict[result_dict.index=='person'].apply(lambda x: x['mobileurl']['_content'])
</code>```

here we have selected all rows that have the index as person and then we tried to apply a function (lambda is the anonymous function we'll be using) to each
person. In this case, we are extracting out the urls using the lambda function, then pandas converted the result back to a pandas DataFrame (or Series) for you to use.

normally I would also care about how fast my iteration is.

(following are done in IPython, a nice tool you could use to do many things in python. %%timeit is a magic function provided by IPython for you to calculate
the time your codes could take)

```<code>%timeit
urls = result_dict[result_dict.index=='person'].apply(lambda x: x['mobileurl']['_content'])

1000 loops, best of 3: 133 us per loop (us = microsecond, 10e-6)
</code>```

@SamC provided the fast solution here I can let you know. but like i said, you don't need a DataFrame to use his solution. it'll also work for plain dictionary.

Body:
I have a dictionary (result_dict) as follows.

{'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0',

This contains more than 150 usernames (e.g. 11333216@N05) . I want to extract 'mobileurl' for each user and create a dataframe containing username and mobileurl columns. I couldn't find a way to iterate each user and extract his mobileurl as indexing is impossible. However, I have extract the mobileurl for one of the users as follows.

result_dict['76617062@N08']["person"]["mobileurl"]['_content']

'https://m.flickr.com/photostream.gne?id=76524249'

Would be grateful if someone can help, as I'm a bit new to python.

Body:
I think you could also try to do it more of a pandas way instead of pure dictionary iteration. it's not necessarily the fastest but given you are new to python and pandas, I think it's good thing to know that pandas can handle this well.

I am assuming you are using pandas DataFrame, not just dictionary. you could easily achieve the same purpose without converting your json to pandas DataFrame. i.e. other answers will work even if you are not a pandas DataFrame. they are also valid python dictionary syntax.

urls = result_dict[result_dict.index=='person'].apply(lambda x: x['mobileurl']['_content'])

here we have selected all rows that have the index as person and then we tried to apply a function (lambda is the anonymous function we'll be using) to each
person. In this case, we are extracting out the urls using the lambda function, then pandas converted the result back to a pandas DataFrame (or Series) for you to use.

normally I would also care about how fast my iteration is.

(following are done in IPython, a nice tool you could use to do many things in python. %%timeit is a magic function provided by IPython for you to calculate
the time your codes could take)

%timeit
urls = result_dict[result_dict.index=='person'].apply(lambda x: x['mobileurl']['_content'])

1000 loops, best of 3: 133 us per loop (us = microsecond, 10e-6)

@SamC provided the fast solution here I can let you know. but like i said, you don't need a DataFrame to use his solution. it'll also work for plain dictionary.


问:
Packing ext type in C++ with Msgpack
I am looking for a sample how to pack ext types with msgpack in C++ as I am not sure about how to do this.

The only information I found is located in this section https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_packer#pack-manually.

Assumed I want to pack an object of type Foo as a msgpack ext type with an adaptor class template. How to use pack_ext and pack_ext_body? Do I have to create a "sub packer" within the template, pack my Foo data manually and then pass size of the binary data and the data itself to pack_extand pack_ext_body? It would be create if some C++ expert could give me a minimal example.

```<code>MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
    namespace adaptor {
        template<>
        struct pack<Foo> {
            template <typename Stream>
            packer<Stream>& operator()(msgpack::packer<Stream>& o, Foo const& v) const {
                // how to use ?
                o.pack_ext(size_t l, int8_t type);
                o.pack_ext_body(const char* b, size_t l);
            }
       }
 }
</code>```

}

Thanks in advance!

答:
You can use msgpack::type::ext or msgpack::type::ext_ref.

They are defined at https://github.com/msgpack/msgpack-c/blob/master/include/msgpack/v1/adaptor/ext.hpp

Here is an example for msgpack::type::ext:

```<code>#include <sstream>
#include <cassert>

#include <msgpack.hpp>

int main() {
    std::string val = "ABC";
    msgpack::type::ext e1(42, val.data(), val.size());

    assert(e1.type() == 42);
    assert(e1.size() == 3);
    assert(e1.data()[0] == 'A');
    assert(e1.data()[1] == 'B');
    assert(e1.data()[2] == 'C');

    std::stringstream ss;
    msgpack::pack(ss, e1);

    auto oh = msgpack::unpack(ss.str().data(), ss.str().size());
    auto e2 = oh.get().as<msgpack::type::ext>();
    assert(e1 == e2);
}
</code>```

Live demo:
https://wandbox.org/permlink/ESmreWNBqDdXbKSf

You can also use msgpack::type::ext_ref.
It can avoid copy operation but you need to keep the original buffer, in this case val and oh.

```<code>#include <sstream>
#include <cassert>

#include <msgpack.hpp>

int main() {
    std::string val = "\x2a"; // type 42
    val += "ABC";
    msgpack::type::ext_ref e1(val.data(), val.size());

    assert(e1.type() == 42);
    assert(e1.size() == 3);
    assert(e1.data()[0] == 'A');
    assert(e1.data()[1] == 'B');
    assert(e1.data()[2] == 'C');

    std::stringstream ss;
    msgpack::pack(ss, e1);

    auto oh = msgpack::unpack(ss.str().data(), ss.str().size());
    auto e2 = oh.get().as<msgpack::type::ext_ref>();
    assert(e1 == e2);
}
</code>```

Live demo:
https://wandbox.org/permlink/uYr5MFjLJqPHQgj6

Title: Packing ext type in C++ with Msgpack

Body:
I am looking for a sample how to pack ext types with msgpack in C++ as I am not sure about how to do this.

The only information I found is located in this section https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_packer#pack-manually.

Assumed I want to pack an object of type Foo as a msgpack ext type with an adaptor class template. How to use pack_ext and pack_ext_body? Do I have to create a "sub packer" within the template, pack my Foo data manually and then pass size of the binary data and the data itself to pack_extand pack_ext_body? It would be create if some C++ expert could give me a minimal example.

MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
    namespace adaptor {
        template<>
        struct pack<Foo> {
            template <typename Stream>
            packer<Stream>& operator()(msgpack::packer<Stream>& o, Foo const& v) const {
                // how to use ?
                o.pack_ext(size_t l, int8_t type);
                o.pack_ext_body(const char* b, size_t l);
            }
       }
 }

}

Thanks in advance!

Body:
You can use msgpack::type::ext or msgpack::type::ext_ref.

They are defined at https://github.com/msgpack/msgpack-c/blob/master/include/msgpack/v1/adaptor/ext.hpp

Here is an example for msgpack::type::ext:

#include <sstream>
#include <cassert>

#include <msgpack.hpp>

int main() {
    std::string val = "ABC";
    msgpack::type::ext e1(42, val.data(), val.size());

    assert(e1.type() == 42);
    assert(e1.size() == 3);
    assert(e1.data()[0] == 'A');
    assert(e1.data()[1] == 'B');
    assert(e1.data()[2] == 'C');

    std::stringstream ss;
    msgpack::pack(ss, e1);

    auto oh = msgpack::unpack(ss.str().data(), ss.str().size());
    auto e2 = oh.get().as<msgpack::type::ext>();
    assert(e1 == e2);
}

Live demo:
https://wandbox.org/permlink/ESmreWNBqDdXbKSf

You can also use msgpack::type::ext_ref.
It can avoid copy operation but you need to keep the original buffer, in this case val and oh.

#include <sstream>
#include <cassert>

#include <msgpack.hpp>

int main() {
    std::string val = "\x2a"; // type 42
    val += "ABC";
    msgpack::type::ext_ref e1(val.data(), val.size());

    assert(e1.type() == 42);
    assert(e1.size() == 3);
    assert(e1.data()[0] == 'A');
    assert(e1.data()[1] == 'B');
    assert(e1.data()[2] == 'C');

    std::stringstream ss;
    msgpack::pack(ss, e1);

    auto oh = msgpack::unpack(ss.str().data(), ss.str().size());
    auto e2 = oh.get().as<msgpack::type::ext_ref>();
    assert(e1 == e2);
}

Live demo:
https://wandbox.org/permlink/uYr5MFjLJqPHQgj6


问:
Designing java project for monoliths and microservices at same time
I would like to know how you divide project modules in java for monolith with possibility of transforming modules to micro-services later?

My personal naming looks like this:

```<code>com.company.shopapp.product
...product.domain (ddd, services, repositories, entities, aggregates, command handlers - everything with package scope)
...product.api (everything with public scope)
...product.controller (CQRS endpoints for commands in web perspective - (package scope))
...product.query(CQRS - package scope)

com.company.shopapp.sales
- domain
- api
- controller
- query
</code>```

What we have here is basically product management context and sales context as packages.

Modules communicate each other using public interfaces (api package) only. In my project I use "..api.ProductFacade" to centralize communication points.

When my "sales" module grow i will turn it into microservice by implementing "..api.ProductFacade" interface as a "rest" or "soap" client and on the other side I will create Endpoint/RestController based on ProductFacade interface.
Package "com.company.shopapp.product.api" will be transformed into extended library and added to both projects.

Edit:
I can achive this out of the box using @Feign library.
https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html#spring-cloud-feign-inheritance

The whole idea feels nice, but maybe you have better way to design project and ensure that breaking it into micro-services will not break whole application.

答:
I think your module structure is good. But I would suggest you create a real 'multi module' project (link). This way, using code from another module will generate a compile-error. This will help you to keep your good intentions!

In order to do this, you'll have to split each module in a private (implementations) and public (api, only interfaces) module (By doing this, you don't need an 'api'-package).
An implementation module can depend on any public-module, but not a private-module.

If you wire your application together in the private module, with dependency injection, the private modules will have no 'internal' dependencies!
The private modules will not have any 'compile-time' dependencies, only  'runtime' dependencies.

Here quick module dependency graph:

I hope you find this usefull!

Edit:
You will need an extra module only to bootstrap the application!

Body:
I would like to know how you divide project modules in java for monolith with possibility of transforming modules to micro-services later?

My personal naming looks like this:

com.company.shopapp.product
...product.domain (ddd, services, repositories, entities, aggregates, command handlers - everything with package scope)
...product.api (everything with public scope)
...product.controller (CQRS endpoints for commands in web perspective - (package scope))
...product.query(CQRS - package scope)

com.company.shopapp.sales
- domain
- api
- controller
- query

What we have here is basically product management context and sales context as packages.

Modules communicate each other using public interfaces (api package) only. In my project I use "..api.ProductFacade" to centralize communication points.

When my "sales" module grow i will turn it into microservice by implementing "..api.ProductFacade" interface as a "rest" or "soap" client and on the other side I will create Endpoint/RestController based on ProductFacade interface.
Package "com.company.shopapp.product.api" will be transformed into extended library and added to both projects.

Edit:
I can achive this out of the box using @Feign library.
https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html#spring-cloud-feign-inheritance

The whole idea feels nice, but maybe you have better way to design project and ensure that breaking it into micro-services will not break whole application.


问:
Copy cell data from TableView to clipboard
I have a TableView with -depending on user input- 4 to 10 columns. I want to be able to copy selected cells to the system clipboard. I tried this piece of code that I found in SO, but position.getColumn() always returns -1, so it doesn´t work. Also, table.getSelectionModel().getSelectedCells() returns only as many items as there are rows. I expected it to return one item per cell instead. Can someone point out my error?

```<code>TableView<TableEntry> table = new TableView<>();
        //copy to clipboard
        table.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.C && e.isControlDown()) {
                StringBuilder clipboardString = new StringBuilder();

                ObservableList<TablePosition> positionList = table.getSelectionModel().getSelectedCells();

                int prevRow = -1;

                for (TablePosition position : positionList) {

                    int row = position.getRow();
                    int col = position.getColumn();

                    Object cell = (Object) table.getColumns().get(col).getCellData(row);

                    // null-check: provide empty string for nulls
                    if (cell == null) {
                        cell = "";
                    }

                    // determine whether we advance in a row (tab) or a column
                    // (newline).
                    if (prevRow == row) {

                        clipboardString.append('\t');

                    } else if (prevRow != -1) {

                        clipboardString.append('\n');

                    }

                    // create string from cell
                    String text = cell.toString();

                    // add new item to clipboard
                    clipboardString.append(text);

                    // remember previous
                    prevRow = row;
                }

                // create clipboard content
                final ClipboardContent clipboardContent = new ClipboardContent();
                clipboardContent.putString(clipboardString.toString());

                // set clipboard content
                Clipboard.getSystemClipboard().setContent(clipboardContent);
            }

        });
</code>```

答:
James_D nailed it in the comment; the cell selection needs to be enabled:</p>

```<code>table.getSelectionModel().setCellSelectionEnabled(true)
</code>```

Body:
I have a TableView with -depending on user input- 4 to 10 columns. I want to be able to copy selected cells to the system clipboard. I tried this piece of code that I found in SO, but position.getColumn() always returns -1, so it doesn´t work. Also, table.getSelectionModel().getSelectedCells() returns only as many items as there are rows. I expected it to return one item per cell instead. Can someone point out my error?

TableView<TableEntry> table = new TableView<>();
        //copy to clipboard
        table.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.C && e.isControlDown()) {
                StringBuilder clipboardString = new StringBuilder();

                ObservableList<TablePosition> positionList = table.getSelectionModel().getSelectedCells();

                int prevRow = -1;

                for (TablePosition position : positionList) {

                    int row = position.getRow();
                    int col = position.getColumn();

                    Object cell = (Object) table.getColumns().get(col).getCellData(row);

                    // null-check: provide empty string for nulls
                    if (cell == null) {
                        cell = "";
                    }

                    // determine whether we advance in a row (tab) or a column
                    // (newline).
                    if (prevRow == row) {

                        clipboardString.append('\t');

                    } else if (prevRow != -1) {

                        clipboardString.append('\n');

                    }

                    // create string from cell
                    String text = cell.toString();

                    // add new item to clipboard
                    clipboardString.append(text);

                    // remember previous
                    prevRow = row;
                }

                // create clipboard content
                final ClipboardContent clipboardContent = new ClipboardContent();
                clipboardContent.putString(clipboardString.toString());

                // set clipboard content
                Clipboard.getSystemClipboard().setContent(clipboardContent);
            }

        });

Body:
James_D nailed it in the comment; the cell selection needs to be enabled:

table.getSelectionModel().setCellSelectionEnabled(true)


问:
Building an answer file
I am trying to automate the running of a diagcab file via command line or PowerShell. I understand you can run a diagcab via command line from the details here, however I am unsure how to compose the answer file to use.

The Diagcab file is MicrosoftEasyFix25010.mini.diagcab

答: The answer from here: https://superuser.com/questions/871822/creating-an-answer-file-for-windowsupdatediagnostic-diagcab-in-eclipse-wtp is to use the Get-TroubleshootingPack cmdlet to generate it.</p>

Title: Building an answer file


问:
Python threading stuck after 1 loop
working on some threading with python 3 having two things running at the same time.
Here is the script i was testing with.

```<code>from threading import Thread
import time as t
x=1
z=1
var=0
def firstFunction():
    global var
    while x == 1:

        var += 1
        t.sleep(1)
def secondFunction():

    while z == 1:
            print(var)
    t.sleep(1)
add=Thread(target=firstFunction)
see=Thread(target=secondFunction)
add.start()
see.start()
</code>```

For some reason when I run it you exprect it to count up, right?
but it just says

1

and doesn't end or say error, but if i try a script that has the script ask if you want to see the var it works fine. Any way i can get this to work without the asking? Here is the code with the asking.

```<code>from threading import Thread
import time as t
x=1
z=1
var=0
def firstFunction():
    global var
    while x == 1:
        var += 1
        t.sleep(1)
def secondFunction():

    while z == 1:
            see1=input("See var? : ")
            if see1 == "y":
                print(var)
            elif seel == "n":
                print("ok")
            else:
                print("not option")
add=Thread(target=firstFunction)
see=Thread(target=secondFunction)
add.start()
see.start()
</code>```

答:
When you run your code like this, the main thread will reach the end and terminate directly after starting both child threads.

You have to wait until the threads are complete. .join() will do that and so you just add these lines to the very end your your programm

```<code>add.join()
see.join()
</code>```

and the main thread will wait until both threads are finished.

Be aware that unlucky constellations of threads and joins can lead to a deadlock.

Title: Python threading stuck after 1 loop

Body:
working on some threading with python 3 having two things running at the same time.
Here is the script i was testing with.

from threading import Thread
import time as t
x=1
z=1
var=0
def firstFunction():
    global var
    while x == 1:

        var += 1
        t.sleep(1)
def secondFunction():

    while z == 1:
            print(var)
    t.sleep(1)
add=Thread(target=firstFunction)
see=Thread(target=secondFunction)
add.start()
see.start()

For some reason when I run it you exprect it to count up, right?
but it just says

1

and doesn't end or say error, but if i try a script that has the script ask if you want to see the var it works fine. Any way i can get this to work without the asking? Here is the code with the asking.

from threading import Thread
import time as t
x=1
z=1
var=0
def firstFunction():
    global var
    while x == 1:
        var += 1
        t.sleep(1)
def secondFunction():

    while z == 1:
            see1=input("See var? : ")
            if see1 == "y":
                print(var)
            elif seel == "n":
                print("ok")
            else:
                print("not option")
add=Thread(target=firstFunction)
see=Thread(target=secondFunction)
add.start()
see.start()

Body:
When you run your code like this, the main thread will reach the end and terminate directly after starting both child threads.

You have to wait until the threads are complete. .join() will do that and so you just add these lines to the very end your your programm

add.join()
see.join()

and the main thread will wait until both threads are finished.

Be aware that unlucky constellations of threads and joins can lead to a deadlock.


问:
Printing 1 to 1000 without loop or conditionals
Task: Print numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.

How would you do that using C or C++?

答:
I've reformulated the great routine proposed by Bill to make it more universal:

```<code>void printMe ()
{
    int i = 1;
    startPrintMe:
    printf ("%d\n", i);
    void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000);
    goto *labelPtr;
    exitPrintMe:
}
</code>```

UPDATE: The second approach needs 2 functions:

```<code>void exitMe(){}
void printMe ()
{
    static int i = 1; // or 1001
    i = i * !!(1001 - i) + !(1001 - i); // makes function reusable
    printf ("%d\n", i);
    (typeof(void (*)())[]){printMe, exitMe} [!(1000-i++)](); // :)
}
</code>```

For both cases you can initiate printing by simply calling

```<code>printMe();
</code>```

Has been tested for GCC 4.2.

Body:
I've reformulated the great routine proposed by Bill to make it more universal:

void printMe ()
{
    int i = 1;
    startPrintMe:
    printf ("%d\n", i);
    void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000);
    goto *labelPtr;
    exitPrintMe:
}

UPDATE: The second approach needs 2 functions:

void exitMe(){}
void printMe ()
{
    static int i = 1; // or 1001
    i = i * !!(1001 - i) + !(1001 - i); // makes function reusable
    printf ("%d\n", i);
    (typeof(void (*)())[]){printMe, exitMe} [!(1000-i++)](); // :)
}

For both cases you can initiate printing by simply calling

printMe();

Has been tested for GCC 4.2.


问:
Creating a page for every product in a website
I'm designing a website for shopping.

When I click a product from the products page, I want to get a page only containing information about that one product but do I have to create a new page separately for every product on the products page?

I only know some javascript and jquery. I don't know PHP.

答:
It seems you only have experience working with static pages. Which is to be expected as you've said you are a beginner. I suggest adding PHP to your question tags and getting some help on that.

With PHP or other server side technologies you can generate dynamic page content compared to static. You would make the markup as a template, then on the server your code would generate what goes inside the mark-up and the page will be served.

If you are using web hosting that has PHP support, try changing your page extension to .php and adding:

```<code><?php echo date(DATE_RFC2822); ?>
</code>```

By refreshing the page you will see the output will change as the time changes.

By using server side scripting you could put all your product information in a CSV (comma seperetaed values file) and retrieve your product listings from the CSV files with their individual links etc.

The PHP documentation is a great place to start: http://php.net/manual/en/getting-started.php

PHP is not the only server-side scripting technology, in fact as you've started learning JavaScript you could even look into to alternatives like NodeJS etc. You are at the point where you now must start working with dynamic content which everyone gets to at some point of learning front-end technology.

Body:
It seems you only have experience working with static pages. Which is to be expected as you've said you are a beginner. I suggest adding PHP to your question tags and getting some help on that.

With PHP or other server side technologies you can generate dynamic page content compared to static. You would make the markup as a template, then on the server your code would generate what goes inside the mark-up and the page will be served.

If you are using web hosting that has PHP support, try changing your page extension to .php and adding:

<?php echo date(DATE_RFC2822); ?>

By refreshing the page you will see the output will change as the time changes.

By using server side scripting you could put all your product information in a CSV (comma seperetaed values file) and retrieve your product listings from the CSV files with their individual links etc.

The PHP documentation is a great place to start: http://php.net/manual/en/getting-started.php

PHP is not the only server-side scripting technology, in fact as you've started learning JavaScript you could even look into to alternatives like NodeJS etc. You are at the point where you now must start working with dynamic content which everyone gets to at some point of learning front-end technology.


问:
Changing binwidth of density histogram so that probabilities sum up to 1
I have already found numerous of questions to it, but somehow it did not really help me. I do not understand how to change the binwidth in a density histogram in ggplot2, so that the probabilities sum up to 1. It seems like it only works if the binwidth is exactly 1.
Here is an example:

```<code>set.seed(1)
df = data.frame("data" = runif(1000, min=0, max=100))

a = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y=..density..),colour="black", fill = "white",
    breaks=seq(0, 100, by = 50))

b = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y =..density..),
             breaks=seq(0, 100, by = 30),
             col="black",
             fill="white")
c = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y =..density..),
             breaks=seq(0, 100, by = 10),
             col="black",
             fill="white")

d = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y =..density..),
             breaks=seq(0, 100, by = 1),
             col="black",
             fill="white")

grid.arrange(a,b,c,d, ncol= 2)
</code>```

If you look at the probability axis, you can see that the first three graphs must be wrong. These are not the right histograms as the bins do not sum up to 1. The y-axis even does not change significantly according to the histogram a, b, c or d. I also tried to replace the "breaks" command by the "binwidth" command, but it is even worse then.
I would also like to know how you can count the probabilities of the single bins of a histogram to proof that it sums up to 1 or not?

Thanks for any help.

答:
Simulate some data:

```<code>library(ggplot2)
library(dplyr)

set.seed(1)
df = data.frame("data" = runif(1000, min=0, max=100))
</code>```

The first plot you can get is:

```<code># y axis has the density estimate values
ggplot(data = df, aes(x = data))+
  geom_histogram(aes(y=..density..),colour="black", fill = "white",
                 breaks=seq(0, 100, by = 50))
</code>```

This plot has the density estimates on the y axis. Those values correspond to the density plot and not to the bars you created. You can see this version where the density plot is overlayed:

```<code># y axis has the density estimate values and the density plot
ggplot(data = df, aes(x = data))+
  geom_histogram(aes(y=..density..),colour="black", fill = "white",
                 breaks=seq(0, 100, by = 50)) +
  geom_density(aes(data), col="red")
</code>```

A way to interpret this is that each point on the red line has a probability to be selected and that's on the y axis (i.e. lots of points means that probabilities tend closer to zero).

You can get what you want with this:

```<code># y axis has the probabilities of each bar (bar counts / all counts)
ggplot(data = df, aes(x = data))+
  geom_histogram(aes(y=..count../sum(..count..)),colour="black", fill = "white",
                 breaks=seq(0, 100, by = 50))
</code>```

Another way to do the above, while keeping the data (for future usage or just check probabilities sum to 1) is this:

```<code># assign the breaks
breaks = cut(df$data, seq(0, 100, by = 50))

# count observations in each bar and probability of each bar
df %>%
  mutate(Breaks = breaks) %>%
  count(Breaks) %>%
  mutate(Prc = n/sum(n))

# # A tibble: 2 x 3
#     Breaks     n   Prc
#     <fctr> <int> <dbl>
# 1   (0,50]   520  0.52
# 2 (50,100]   480  0.48

# plot the above
df %>%
  mutate(Breaks = breaks) %>%
  count(Breaks) %>%
  mutate(Prc = n/sum(n)) %>%
  ggplot(aes(Breaks, Prc)) + geom_col()
</code>```

Body:
I have already found numerous of questions to it, but somehow it did not really help me. I do not understand how to change the binwidth in a density histogram in ggplot2, so that the probabilities sum up to 1. It seems like it only works if the binwidth is exactly 1.
Here is an example:

set.seed(1)
df = data.frame("data" = runif(1000, min=0, max=100))

a = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y=..density..),colour="black", fill = "white",
    breaks=seq(0, 100, by = 50))

b = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y =..density..),
             breaks=seq(0, 100, by = 30),
             col="black",
             fill="white")
c = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y =..density..),
             breaks=seq(0, 100, by = 10),
             col="black",
             fill="white")

d = ggplot(data = df, aes(x = data))+
    geom_histogram(aes(y =..density..),
             breaks=seq(0, 100, by = 1),
             col="black",
             fill="white")

grid.arrange(a,b,c,d, ncol= 2)

If you look at the probability axis, you can see that the first three graphs must be wrong. These are not the right histograms as the bins do not sum up to 1. The y-axis even does not change significantly according to the histogram a, b, c or d. I also tried to replace the "breaks" command by the "binwidth" command, but it is even worse then.
I would also like to know how you can count the probabilities of the single bins of a histogram to proof that it sums up to 1 or not?

Thanks for any help.

Body:
Simulate some data:

library(ggplot2)
library(dplyr)

set.seed(1)
df = data.frame("data" = runif(1000, min=0, max=100))

The first plot you can get is:

# y axis has the density estimate values
ggplot(data = df, aes(x = data))+
  geom_histogram(aes(y=..density..),colour="black", fill = "white",
                 breaks=seq(0, 100, by = 50))

This plot has the density estimates on the y axis. Those values correspond to the density plot and not to the bars you created. You can see this version where the density plot is overlayed:

# y axis has the density estimate values and the density plot
ggplot(data = df, aes(x = data))+
  geom_histogram(aes(y=..density..),colour="black", fill = "white",
                 breaks=seq(0, 100, by = 50)) +
  geom_density(aes(data), col="red")

A way to interpret this is that each point on the red line has a probability to be selected and that's on the y axis (i.e. lots of points means that probabilities tend closer to zero).

You can get what you want with this:

# y axis has the probabilities of each bar (bar counts / all counts)
ggplot(data = df, aes(x = data))+
  geom_histogram(aes(y=..count../sum(..count..)),colour="black", fill = "white",
                 breaks=seq(0, 100, by = 50))

Another way to do the above, while keeping the data (for future usage or just check probabilities sum to 1) is this:

# assign the breaks
breaks = cut(df$data, seq(0, 100, by = 50))

# count observations in each bar and probability of each bar
df %>%
  mutate(Breaks = breaks) %>%
  count(Breaks) %>%
  mutate(Prc = n/sum(n))

# # A tibble: 2 x 3
#     Breaks     n   Prc
#     <fctr> <int> <dbl>
# 1   (0,50]   520  0.52
# 2 (50,100]   480  0.48

# plot the above
df %>%
  mutate(Breaks = breaks) %>%
  count(Breaks) %>%
  mutate(Prc = n/sum(n)) %>%
  ggplot(aes(Breaks, Prc)) + geom_col()


问:
Laguerre's method to obtain poly roots
I have to write using Laguerre's method a piece of code to find real and complex roots of poly:
f(x)=a4x4+a3x3+a2x2+a1x+a0 , [a4 a3 a2 a1 a0]=[-2 5 5 2 1]
I got something:

```<code>function y = laguerre (x,coef)
tol = 10^(-10);
%polynomial order
n = length(coef);
i = 0;
while (abs(polyval(coef,x)) > tol)
i = i + 1
x
polyval(coef,x)
%second derivative
a=polyval(polyder(polyder(coef)), x);
%first derivative
b=polyval(polyder(coef), x);
%polynomial value
c=polyval(coef, x);
%square root
r = sqrt((n-1)*[(n-1)*b^2-n*a*c]);
d1 = b + r;
d2 = b - r;
%highest abs value denominator chosen
if (abs(d1) > abs(d2))
    d = d1;
else
    d = d2;
end
%next iteration value obtained
z = n*c/d;
x = x - z;
end
i = i + 1
x
polyval(coef,x)
y = x;
return
end
</code>```

and I want to draw and/ or obtain my roots:

```<code>coef = [-2 5 5 2 1];
fh = @poly;
%diary on
%plot of the function
figure(1);
fplot(fh, [-500 500]);
hold on;
figure(2);
fplot(fh, [-1.5 3]);
hold on;
%roots obtained using MM2
%z1(1) = MM2(-500,coef);
%z1(2) = MM2(500,coef);
%z1(3) = MM2(1 + i, coef);
%z1(4) = MM2(0 - 2i, coef);
%roots obtained using Laguerre's
%z2(1) = laguerre(-500,coef);
z2(2) = laguerre(500,coef);
%z2(3) = laguerre(1 + i, coef);
%z2(4) = laguerre(0 - 2i, coef);
%additional points on plot
p = [z1(1) z2(2)];
plot(p,[0 0],'r*');
legend('function','zeros');
hold off;
figure(1);
plot(p,[0 0],'r*');
plot([-500 500],[0 0], 'b*');
legend('function','zeros','START points');
diary off;
hold off;
</code>```

As you see, some part of code is commented because I really don't know how to move on. I got many warnings. I got one error in 1st part of the code. I am looking for some tips or direction what to do.

答:
Your code works perfectly well, you should get the roots

```<code>x=-500     =>  x=-0.6694729, p(x)=-8.882D-16 in 9 steps
x= 500     =>  x=3.3489712, p(x)=1.621D-14 in 8 steps
x=1 + i    =>  x=-0.0897491+i*0.4636332, p(x)=i*8.327D-17 in 4 steps
x=0 - 2i   =>  x=-0.0897491-i*0.4636332, p(x)=i*5.551D-17 in 4 steps
</code>```

To illustrate the bigger picture, the iteration map for the Laguerre method with initial values in [-4,4]+[-4,4]*i looks like

Every color shade represents one step. There is nothing nefarious in this polynomial preventing convergence of the method.

To compare with, the Halley iteration map is

and the Newton fractal

Title: Laguerre's method to obtain poly roots

Body:
I have to write using Laguerre's method a piece of code to find real and complex roots of poly:
f(x)=a4x4+a3x3+a2x2+a1x+a0 , [a4 a3 a2 a1 a0]=[-2 5 5 2 1]
I got something:

function y = laguerre (x,coef)
tol = 10^(-10);
%polynomial order
n = length(coef);
i = 0;
while (abs(polyval(coef,x)) > tol)
i = i + 1
x
polyval(coef,x)
%second derivative
a=polyval(polyder(polyder(coef)), x);
%first derivative
b=polyval(polyder(coef), x);
%polynomial value
c=polyval(coef, x);
%square root
r = sqrt((n-1)*[(n-1)*b^2-n*a*c]);
d1 = b + r;
d2 = b - r;
%highest abs value denominator chosen
if (abs(d1) > abs(d2))
    d = d1;
else
    d = d2;
end
%next iteration value obtained
z = n*c/d;
x = x - z;
end
i = i + 1
x
polyval(coef,x)
y = x;
return
end

and I want to draw and/ or obtain my roots:

coef = [-2 5 5 2 1];
fh = @poly;
%diary on
%plot of the function
figure(1);
fplot(fh, [-500 500]);
hold on;
figure(2);
fplot(fh, [-1.5 3]);
hold on;
%roots obtained using MM2
%z1(1) = MM2(-500,coef);
%z1(2) = MM2(500,coef);
%z1(3) = MM2(1 + i, coef);
%z1(4) = MM2(0 - 2i, coef);
%roots obtained using Laguerre's
%z2(1) = laguerre(-500,coef);
z2(2) = laguerre(500,coef);
%z2(3) = laguerre(1 + i, coef);
%z2(4) = laguerre(0 - 2i, coef);
%additional points on plot
p = [z1(1) z2(2)];
plot(p,[0 0],'r*');
legend('function','zeros');
hold off;
figure(1);
plot(p,[0 0],'r*');
plot([-500 500],[0 0], 'b*');
legend('function','zeros','START points');
diary off;
hold off;

As you see, some part of code is commented because I really don't know how to move on. I got many warnings. I got one error in 1st part of the code. I am looking for some tips or direction what to do.

Body:
Your code works perfectly well, you should get the roots

x=-500     =>  x=-0.6694729, p(x)=-8.882D-16 in 9 steps
x= 500     =>  x=3.3489712, p(x)=1.621D-14 in 8 steps
x=1 + i    =>  x=-0.0897491+i*0.4636332, p(x)=i*8.327D-17 in 4 steps
x=0 - 2i   =>  x=-0.0897491-i*0.4636332, p(x)=i*5.551D-17 in 4 steps

To illustrate the bigger picture, the iteration map for the Laguerre method with initial values in [-4,4]+[-4,4]*i looks like

Every color shade represents one step. There is nothing nefarious in this polynomial preventing convergence of the method.

To compare with, the Halley iteration map is

and the Newton fractal


问:
SendWait and Variable
I am sending keys in IE automation process. First I press Ctrl+S (Save), then I want to save WebPage as MHT file named as variable $currentDate.

```<code>[System.Windows.Forms.SendKeys]::SendWait('^{s}')
Start-Sleep -m 500
[System.Windows.Forms.SendKeys]::SendWait('{$currentDate}')
</code>```

What is the correct format of usage variable in SendWait('{}')?

I've tried both ('{'"$currentDate"'}') and ('{"$currentDate"}')

答:
Read and follow About Quoting Rules article:

When you enclose a string in double quotation marks (a
  double-quoted string), variable names that are preceded by a dollar
  sign ($) are replaced with the variable's value before the string is
  passed to the command for processing.

…

When you enclose a string in single-quotation marks (a
  single-quoted string), the string is passed to the command exactly as
  you type it. No substitution is performed.

Example:

```<code>$currentdate = (get-date).ToString('yyyyMMdd-HHmm')
$currentdate
"$currentdate"
'$currentdate'
[System.Windows.Forms.SendKeys]::SendWait("SendWait=$currentdate")
</code>```

Output in an open Powershell prompt:

PS D:\PShell> D:\PShell\SO\47649742.ps1
20171205-1454
20171205-1454
$currentdate
PS D:\PShell> SendWait=20171205-1454
```

Title: SendWait and Variable

Body:
I am sending keys in IE automation process. First I press Ctrl+S (Save), then I want to save WebPage as MHT file named as variable $currentDate.

[System.Windows.Forms.SendKeys]::SendWait('^{s}')
Start-Sleep -m 500
[System.Windows.Forms.SendKeys]::SendWait('{$currentDate}')

What is the correct format of usage variable in SendWait('{}')?

I've tried both ('{'"$currentDate"'}') and ('{"$currentDate"}')

Body:
Read and follow About Quoting Rules article:

When you enclose a string in double quotation marks (a
  double-quoted string), variable names that are preceded by a dollar
  sign ($) are replaced with the variable's value before the string is
  passed to the command for processing.

…

When you enclose a string in single-quotation marks (a
  single-quoted string), the string is passed to the command exactly as
  you type it. No substitution is performed.

Example:

$currentdate = (get-date).ToString('yyyyMMdd-HHmm')
$currentdate
"$currentdate"
'$currentdate'
[System.Windows.Forms.SendKeys]::SendWait("SendWait=$currentdate")

Output in an open Powershell prompt:

PS D:\PShell> D:\PShell\SO\47649742.ps1
20171205-1454
20171205-1454
$currentdate
PS D:\PShell> SendWait=20171205-1454


问:
Non-null variable is being called null?
```<code>protected var categoryXML:XML;
protected var categoryArr:ArrayCollection;
protected var categoryList:IList;

for (var i:int=0;i<getLength(categoryXML.category);i++) {
   trace(categoryXML.category[i].name);
   categoryArr[i] = categoryXML.category[i].name;
}
</code>```

I'm having trouble with this bit of code...

The trace here works great, and I get the response I expect, but when I try to add it to the categoryArr variable, I get yelled at and told it's null.

What could cause the difference here?

Thanks!

答:
So, if you are getting that there is a null reference at that line, it is because categoryArr is probably null.  You need to initialize it, like @www0x0k suggested.

I will also suggest that you probably don't want to use indexes in this way.  It assumes too much about the length of the particular ArrayCollection without any bounds checking.  Consider code like this instead:

```<code>categoryArr = new ArrayCollection();
for each(var category in categoryXML.category) {
   trace(category.name);
   categoryArr.addItem(category.name);
}
</code>```

Title: Non-null variable is being called null?

Body:
protected var categoryXML:XML;
protected var categoryArr:ArrayCollection;
protected var categoryList:IList;

for (var i:int=0;i<getLength(categoryXML.category);i++) {
   trace(categoryXML.category[i].name);
   categoryArr[i] = categoryXML.category[i].name;
}

I'm having trouble with this bit of code...

The trace here works great, and I get the response I expect, but when I try to add it to the categoryArr variable, I get yelled at and told it's null.

What could cause the difference here?

Thanks!

Body:
So, if you are getting that there is a null reference at that line, it is because categoryArr is probably null.  You need to initialize it, like @www0x0k suggested.

I will also suggest that you probably don't want to use indexes in this way.  It assumes too much about the length of the particular ArrayCollection without any bounds checking.  Consider code like this instead:

categoryArr = new ArrayCollection();
for each(var category in categoryXML.category) {
   trace(category.name);
   categoryArr.addItem(category.name);
}


问:
How in SonataAdminBundle get current admin class?
How in SonataAdminBundle
get the current admin class without using AdminPool?

Now I'm trying to do it like this

```<code>    $entityClass = get_class($entity);
    $adminClass = $this->adminPool->getAdminByClass($entityClass);
</code>```

But this method has a problem. If the entity is associated with several classes of the admin, an exception will be thrown.
Is there a way to find out what exactly the admin service should handle the current route?

Thanks!

答:
If you have multiple admins registered for this entity's class, nothing can choose the correct one for you.

You can still get a specific admin with the method Pool::getAdminByAdminCode(string $code).

For example, an usage for you could be:

```<code>if ($entityClass === MultipleAdminRegisteredEntity::class) {
    $admin = $this->adminPool->getAdminById('specific_admin_id');
} else {
    $entityClass = get_class($entity);
    $admin = $this->adminPool->getAdminByClass($entityClass);
}
</code>```

Please pay attention to the fact that the Pool::getAdminByClass(string $class) returns an Admin and not a class string: you named your variable $adminClass which suggests you made this confusion.

Also note that there is an open issue on Github here: https://github.com/sonata-project/SonataAdminBundle/issues/3908 to determine a way to be able define default admins when there are more than one admin for an entity, so that the Pool:getAdminByClass() method doesn't throw an exception. Nobody seems to have care enough about this to implement it, feel free to contribute there if you want.

Body:
How in SonataAdminBundle
get the current admin class without using AdminPool?

Now I'm trying to do it like this

    $entityClass = get_class($entity);
    $adminClass = $this->adminPool->getAdminByClass($entityClass);

But this method has a problem. If the entity is associated with several classes of the admin, an exception will be thrown.
Is there a way to find out what exactly the admin service should handle the current route?

Thanks!

Body:
If you have multiple admins registered for this entity's class, nothing can choose the correct one for you.

You can still get a specific admin with the method Pool::getAdminByAdminCode(string $code).

For example, an usage for you could be:

if ($entityClass === MultipleAdminRegisteredEntity::class) {
    $admin = $this->adminPool->getAdminById('specific_admin_id');
} else {
    $entityClass = get_class($entity);
    $admin = $this->adminPool->getAdminByClass($entityClass);
}

Please pay attention to the fact that the Pool::getAdminByClass(string $class) returns an Admin and not a class string: you named your variable $adminClass which suggests you made this confusion.

Also note that there is an open issue on Github here: https://github.com/sonata-project/SonataAdminBundle/issues/3908 to determine a way to be able define default admins when there are more than one admin for an entity, so that the Pool:getAdminByClass() method doesn't throw an exception. Nobody seems to have care enough about this to implement it, feel free to contribute there if you want.


问:
Javascript Array Map by Object Attributes
I have a dynamic rendering component, that renders sub-components as follows. I`m making the component inside another object now and i could not re-write the render part.

Rendering

```<code>{this.props.components.map((Component, i) => (
  <div className="formGroup" key={i}>
     <Component id={Component.componentName + "_id"} name={Component.componentName} ref={component => { this.componentRefs.push(component); console.log("Loaded component " + component.componentName); }} key={i} />
  </div>
))}
</code>```

For now i have a brute array of components such as

```<code>this.props.components = [MyComponent1, MyComponent2];
</code>```

However, i`m changing this in a way i have the component wrapped inside an object, such as

```<code>this.props.components = [{type: MyComponent1, name:"yolo"}, {type: MyComponent2, name:"yala"},];
</code>```

so the component itself is inside this object typeattribute.

I didnt managed to re-write the render part of this component to loop for this type attribute instead of the object itself.

答:
Just deconstruct the type property off the object on mapping:

```<code>{this.props.components.map(({ type: MyComponent }, i) => (
    <div className="formGroup" key={i}>
        <MyComponent id={Component.componentName + "_id"}
            name={Component.componentName}
            ref={component => {
                this.componentRefs.push(component);
                console.log("Loaded component " + component.componentName);
            }}
            key={i} />
    </div>
))}
</code>```

Body:
I have a dynamic rendering component, that renders sub-components as follows. I`m making the component inside another object now and i could not re-write the render part.

Rendering

{this.props.components.map((Component, i) => (

     <Component id={Component.componentName + "_id"} name={Component.componentName} ref={component => { this.componentRefs.push(component); console.log("Loaded component " + component.componentName); }} key={i} />

))}

For now i have a brute array of components such as

this.props.components = [MyComponent1, MyComponent2];

However, i`m changing this in a way i have the component wrapped inside an object, such as

this.props.components = [{type: MyComponent1, name:"yolo"}, {type: MyComponent2, name:"yala"},];

so the component itself is inside this object typeattribute.

I didnt managed to re-write the render part of this component to loop for this type attribute instead of the object itself.

Body:
Just deconstruct the type property off the object on mapping:

{this.props.components.map(({ type: MyComponent }, i) => (
    <div className="formGroup" key={i}>
        <MyComponent id={Component.componentName + "_id"}
            name={Component.componentName}
            ref={component => {
                this.componentRefs.push(component);
                console.log("Loaded component " + component.componentName);
            }}
            key={i} />
    </div>
))}


问:
Externally link to specific tabPanel in Shiny App
It's possible to use anchor links in flat Shiny apps relatively easily - https://stackoverflow.com/a/28605517/1659890.

However, is it possible for an external link to target a specific tabPanel of a navbarPage in a Shiny app?

Consider the following test app:
UI:

```<code>shinyUI(navbarPage(
  "Anchor Test",
  tabPanel(
    "Panel 1", fluidPage(HTML(
      paste(
        "<p>I'm the first panel</p>","<p><a href='#irisPlotUI'>Link to irisPlotUI in panel 2</a></p>",
        "<a href='#panel2'>Link to panel 2</a>",sep = ""
      )
    ))
  ),
  tabPanel("Panel 2", fluidPage(
    "I'm the second panel", uiOutput("irisPlotUI")
  ),
  value = "#panel2"),
  tabPanel("Panel 3", "I'm a table!!!")
</code>```

Server:

```<code>shinyServer(function(input, output) {
  output$irisPlotUI <- renderUI(plotOutput("irisPlot"))
  output$irisPlot <- renderPlot(plot(iris$Sepal.Length))
  })
</code>```

Using the method from the linked answer doesn't work, the id of irisPlotUI is correct but is a child of the tabPanel that the plot lives in.

The data-value of the tabPanel is given the value of "panel2" through the use of the argument value, however the Shiny app continues to give the tabPanel a unique id that I don't know how to target.

I've examined the source of deployed Shiny apps, for instance https://martinjhnhadley.shinyapps.io/AnchorLinks, and found the actual link to the tabPanel: https://internal.shinyapps.io/martinjhnhadley/AnchorLinks/?initialWidth=1074&childId=shinyapp#tab-8850-2

However, navigating directly to this link does not direct me to the tab either.

Are anchor links my only option in targeting parts of the app or is there a Shiny specific solution?

If not, how might I insert a script such as shown here https://stackoverflow.com/a/15637801/1659890 to allow javascript to be executed when landing on the Shiny app to select the tabPanel in a similar manner to this https://groups.google.com/d/msg/shiny-discuss/sJlasQf71fY/RW7Xc8F02IoJ

Solution thanks to daattali

Using daattali's answer I was able to find the following also from him - https://github.com/rstudio/shiny/issues/772#issuecomment-112919149

The following achieves exactly my needs, note that I have chosen to keep with the /?url= convention he used:

UI.R

```<code>shinyUI(
  navbarPage( "test", id = 'someID',
              tabPanel("tab1", h1("page1")),

              navbarMenu( "menu",
                          tabPanel('tab2a',  value='nested1', h1("page2a")),
                          tabPanel('tab2b',  value='nested2', h1("page2b")),
                          tabPanel('tab_sub',  "foobar")
              ),
              tabPanel("tab3", h1("page3"))
  ))
</code>```

SERVER.R

```<code>url1 <- url2 <- ""

shinyServer(function(input, output, session) {

  values <- reactiveValues(myurl = c(), parent_tab = "")

  observe({
    # make sure this is called on pageload (to look at the query string)
    # and whenever any tab is successfully changed.
    # If you want to stop running this code after the initial load was
    # successful so that further manual tab changes don't run this,
    # maybe just have some boolean flag for that.

    input$someID
    input$tab_sub_tabs
    query <- parseQueryString(session$clientData$url_search)
    url <- query$url
    if (is.null(url)) {
      url <- ""
    }

    # "depth" is how many levels the url in the query string is
    depth <- function(x) length(unlist(strsplit(x,"/")))

    # if we reached the end, done!
    if (length(values$myurl) == depth(url)) {
      return()
    }
    # base case - need to tell it what the first main nav name is
    else if (length(values$myurl) == 0) {
      values$parent_tab <- "someID"
    }
    # if we're waiting for a tab switch but the UI hasn't updated yet
    else if (is.null(input[[values$parent_tab]])) {
      return()
    }
    # same - waiting for a tab switch
    else if (tail(values$myurl, 1) != input[[values$parent_tab]]) {
      return()
    }
    # the UI is on the tab that we last switched to, and there are more
    # tabs to switch inside the current tab
    # make sure the tabs follow the naming scheme
    else {
      values$parent_tab <- paste0(tail(values$myurl, 1), "_tabs")
    }

    # figure out the id/value of the next tab
    new_tab <- unlist(strsplit(url, "/"))[length(values$myurl)+1]

    # easy peasy.
    updateTabsetPanel(session, values$parent_tab, new_tab)
    values$myurl <- c(values$myurl, new_tab)
  })
})
</code>```

答:
I found the other answer a little difficult to follow so I created the example below. To navigate to the Data Availability tab, place "?a=b" to at the end of your url. For example if hosting the app on port 7436 the following link will take you directly to the Data Availability page. http://127.0.0.1:7436/?a=b</p>

```<code>library(shinydashboard)
library(shiny)
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(id = "container",
      menuItem("Channels", tabName = "lt_channels"),
      menuItem("Data Availability", tabName = "data_avail")
    )),
  dashboardBody(
    tabItems(
      tabItem(tabName = "lt_channels",
              h1("Test Fail")),
      tabItem(tabName = "data_avail",
              h1("Test Pass"))
    )
  )
)

server <- function(session, input, output){
  observe({
    query <- parseQueryString(session$clientData$url_search)
    query1 <- paste(names(query), query, sep = "=", collapse=", ")
    print(query1)
    if(query1 == "a=b"){
      updateTabItems(session, inputId = "container", selected = "data_avail")
    }
  })
}
shinyApp(ui = ui, server = server)
</code>```

Body:
It's possible to use anchor links in flat Shiny apps relatively easily - https://stackoverflow.com/a/28605517/1659890.

However, is it possible for an external link to target a specific tabPanel of a navbarPage in a Shiny app?

Consider the following test app:
UI:

shinyUI(navbarPage(
  "Anchor Test",
  tabPanel(
    "Panel 1", fluidPage(HTML(
      paste(
        "
I'm the first panel
","
Link to irisPlotUI in panel 2
",
        "Link to panel 2",sep = ""
      )
    ))
  ),
  tabPanel("Panel 2", fluidPage(
    "I'm the second panel", uiOutput("irisPlotUI")
  ),
  value = "#panel2"),
  tabPanel("Panel 3", "I'm a table!!!")

Server:

shinyServer(function(input, output) {
  output$irisPlotUI <- renderUI(plotOutput("irisPlot"))
  output$irisPlot <- renderPlot(plot(iris$Sepal.Length))
  })

Using the method from the linked answer doesn't work, the id of irisPlotUI is correct but is a child of the tabPanel that the plot lives in.

The data-value of the tabPanel is given the value of "panel2" through the use of the argument value, however the Shiny app continues to give the tabPanel a unique id that I don't know how to target.

I've examined the source of deployed Shiny apps, for instance https://martinjhnhadley.shinyapps.io/AnchorLinks, and found the actual link to the tabPanel: https://internal.shinyapps.io/martinjhnhadley/AnchorLinks/?initialWidth=1074&childId=shinyapp#tab-8850-2

However, navigating directly to this link does not direct me to the tab either.

Are anchor links my only option in targeting parts of the app or is there a Shiny specific solution?

If not, how might I insert a script such as shown here https://stackoverflow.com/a/15637801/1659890 to allow javascript to be executed when landing on the Shiny app to select the tabPanel in a similar manner to this https://groups.google.com/d/msg/shiny-discuss/sJlasQf71fY/RW7Xc8F02IoJ

Solution thanks to daattali

Using daattali's answer I was able to find the following also from him - https://github.com/rstudio/shiny/issues/772#issuecomment-112919149

The following achieves exactly my needs, note that I have chosen to keep with the /?url= convention he used:

UI.R

shinyUI(
  navbarPage( "test", id = 'someID',
              tabPanel("tab1", h1("page1")),

              navbarMenu( "menu",
                          tabPanel('tab2a',  value='nested1', h1("page2a")),
                          tabPanel('tab2b',  value='nested2', h1("page2b")),
                          tabPanel('tab_sub',  "foobar")
              ),
              tabPanel("tab3", h1("page3"))
  ))

SERVER.R

url1 <- url2 <- ""

shinyServer(function(input, output, session) {

  values <- reactiveValues(myurl = c(), parent_tab = "")

  observe({
    # make sure this is called on pageload (to look at the query string)
    # and whenever any tab is successfully changed.
    # If you want to stop running this code after the initial load was
    # successful so that further manual tab changes don't run this,
    # maybe just have some boolean flag for that.

    input$someID
    input$tab_sub_tabs
    query <- parseQueryString(session$clientData$url_search)
    url <- query$url
    if (is.null(url)) {
      url <- ""
    }

    # "depth" is how many levels the url in the query string is
    depth <- function(x) length(unlist(strsplit(x,"/")))

    # if we reached the end, done!
    if (length(values$myurl) == depth(url)) {
      return()
    }
    # base case - need to tell it what the first main nav name is
    else if (length(values$myurl) == 0) {
      values$parent_tab <- "someID"
    }
    # if we're waiting for a tab switch but the UI hasn't updated yet
    else if (is.null(input[[values$parent_tab]])) {
      return()
    }
    # same - waiting for a tab switch
    else if (tail(values$myurl, 1) != input[[values$parent_tab]]) {
      return()
    }
    # the UI is on the tab that we last switched to, and there are more
    # tabs to switch inside the current tab
    # make sure the tabs follow the naming scheme
    else {
      values$parent_tab <- paste0(tail(values$myurl, 1), "_tabs")
    }

    # figure out the id/value of the next tab
    new_tab <- unlist(strsplit(url, "/"))[length(values$myurl)+1]

    # easy peasy.
    updateTabsetPanel(session, values$parent_tab, new_tab)
    values$myurl <- c(values$myurl, new_tab)
  })
})

Body:
I found the other answer a little difficult to follow so I created the example below. To navigate to the Data Availability tab, place "?a=b" to at the end of your url. For example if hosting the app on port 7436 the following link will take you directly to the Data Availability page. http://127.0.0.1:7436/?a=b

library(shinydashboard)
library(shiny)
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(id = "container",
      menuItem("Channels", tabName = "lt_channels"),
      menuItem("Data Availability", tabName = "data_avail")
    )),
  dashboardBody(
    tabItems(
      tabItem(tabName = "lt_channels",
              h1("Test Fail")),
      tabItem(tabName = "data_avail",
              h1("Test Pass"))
    )
  )
)

server <- function(session, input, output){
  observe({
    query <- parseQueryString(session$clientData$url_search)
    query1 <- paste(names(query), query, sep = "=", collapse=", ")
    print(query1)
    if(query1 == "a=b"){
      updateTabItems(session, inputId = "container", selected = "data_avail")
    }
  })
}
shinyApp(ui = ui, server = server)

ContentLicense: CC BY-SA 4.0