问:
How to use virtualbox in a Windows 10 azure virtual machine
I've been reading about it, and I don't know if there is anyway of doing it.

I want to create a Virtualbox virtual machine inside another virtual machine I created in azure, and I don't have Hyper-V activated.

My virtual machine doesn't have a BIOS to access and enable it, and I read that not all virtual machines in azure allow nested virtualization.

The virtual machine I have right now is a B1ms standard and what I read is that I need a V3 machine to virtualize a virtual machine inside  the azure one. Is that true? I don't want to spend money just creating it and then not beeing able to do it.

Thanks :)

答:
This can be done using Nested virtualization in Azure. And yes you heard it right that not all Azure Virtual Machines in Azure allow this and you would need V3 VMs. Make sure to choose a VM size large enough to support the demands of a guest virtual machine.
For costing, you can either create a trial Azure account that would give you a credit of $200. Or if you have got a Visual studio Pro or Enterprise license, you are eligible for free monthly credits that you can use for exploring Azure.</p>


来源: stackexchange

问:
R: getting hex colors from numeric values - how to define midpoint in gradient scale
I have a numeric vector and I would like to convert it to hex color codes. The colors should follow a gradient distribution from its possible minimum (red; 0), via a mid value which I define (the mean, black), to its possible max (green; 1).

With ggplot I would use the scale_*_gradientn function. But now I need the actual hex values, and I am struggling to calculate them.

library(tidyverse)
#> Warning: package 'dplyr' was built under R version 3.6.2

data <- data.frame("a"=runif(100),
                   "b"=runif(100))

# ggplot example ----------------------------------------------------------

data <- data.frame("a"=runif(100),
                   "b"=runif(100))

mean_a <- mean(data$a)

ggplot(data)+
  geom_point(aes(x=a,
                 y=b,
                 color=a),
             stat="identity")+
  scale_color_gradientn(colors=c("red","black","green"),
                        values=c(0, mean_a, 1))+
  theme(legend.position = NULL)
```

<p><img src="https://i.imgur.com/YLGyHd2.png" alt=""></p>

<p>Mapping the <code>scale_color_gradientn</code> function is apparently not the way forward:</p>

<pre class="lang-r prettyprint-override"><code>data %>%
  mutate(color_values=map(a, scale_color_gradientn,
                          colors=c("red","black","green"),
                          values=c(0, mean_a, 1))) %>%
  head()
#>           a         b                      color_values
#> 1 0.2863037 0.9902960 <environment: 0x000000001d002f30>
#> 2 0.6169960 0.9527580 <environment: 0x000000001d038798>
#> 3 0.3126825 0.8807853 <environment: 0x000000001d06e098>
#> 4 0.5464037 0.2307841 <environment: 0x000000001d0a39a8>
#> 5 0.5162976 0.8147066 <environment: 0x000000001d0d92a8>
#> 6 0.7519632 0.6821084 <environment: 0x000000001d10cc98>
</code>```

Created on 2020-02-17 by the reprex package (v0.3.0)

I came across this SO entry on the colorRamp function, however, it seems that it does not provide any option to define a manual 'mid' point.

I also came accross this post on colorspace package, which allows for the definition of a midpoint. However, again, I fail to apply it outside of ggplot.

Grateful for any hint!

答:
You can get the hex values that follow the gradient of your colorbar in a ggplot as follows:

gg_build() solution

```<code>    set.seed(1)
    data <- data.frame("a"=runif(100),"b"=runif(100))

    mean_a <- mean(data$a)

    p1 <- ggplot(data)+
      geom_point(aes(x=a,
        y=b,
        color=a),
        stat="identity")+
      scale_color_gradientn(
        colors=c("red","black","green"),
        values=c(0, mean_a, 1))+
      theme(legend.position = NULL)

    # get plot build
    build <- ggplot_build(p1)

    # select hex value and x-value data
    hex_df <- build$data[[1]][, c("colour", "x")]

    # order hex value data to follow x-axis
    hex_df_ordered <- hex_df[order(hex_df$x),]
</code>```

scales::gradient_n_pal() solution

Here is perhaps the approach you want using the scales package function gradient_n_pal, which is called by scale_color_gradientn:

```<code>    library(ggplot2)
    library(scales)
    library(ggpubr)

    # create data
    set.seed(1)
    data <- data.frame("a"=runif(100), "b"=runif(100))
    #get mean_a
    mean_a <- mean(data$a)
    # order the data by a
    data <- data[order(data$a),]
    # encode the values in a character variable for reference
    data$a_char <- as.character(data$a)

    # use the scales::gradient_n_pal to create a palette function
    pal <- scales::gradient_n_pal(colours = c("red","black","green"),
      values= c(0, mean_a, 1))
    # use data in a to generate palette-generated values in the data
    data$hex_from_scales <- pal(data$a)

    # plot with scale_color_gradientn
    p1 <- ggplot(data)+
      geom_point(aes(x=a,
        y=b,
        color=a),
        stat="identity", show.legend = F)+
      scale_color_gradientn(colors=c("red","black","green"),values=c(0, mean_a, 1))+
      ggtitle("Using scale_color_gradientn ")+
      theme(legend.position = NULL)

    # plot with scale_color_manual and gradient_n_pal generated hex values
    p2 <- ggplot(data)+
      geom_point(aes(x=a,
        y=b,
        color=a_char),
        stat="identity", show.legend = F)+
      scale_color_manual(values = data$hex_from_scales)+
      ggtitle("Using gradient_n_pal")+
      theme(legend.position = NULL)

    plots <- ggpubr::ggarrange(p1, p2, ncol = 2)
</code>```

This code generates these plots:

Conclusion

Judging by the similarity of the two plots, it seems like you can get the hex values of your numeric vector with this snippet:

```<code>        # create a palette function
        pal <- scales::gradient_n_pal(colours = c("red","black","green"),values= c(0, mean_a, 1))
        # get palette-generated values from your vector
        data$hex_from_scales <- pal(data$a)
</code>```

It is also notable that this solution generates slightly different hex codes as the ggplot_build() solution proposed above. My eyes tell me the differences are slight. Seeing is believing!

ContentLicense: CC BY-SA 4.0

Body:
I have a numeric vector and I would like to convert it to hex color codes. The colors should follow a gradient distribution from its possible minimum (red; 0), via a mid value which I define (the mean, black), to its possible max (green; 1).

With ggplot I would use the scale_*_gradientn function. But now I need the actual hex values, and I am struggling to calculate them.

library(tidyverse)
#> Warning: package 'dplyr' was built under R version 3.6.2

data <- data.frame("a"=runif(100),
                   "b"=runif(100))

# ggplot example ----------------------------------------------------------

data <- data.frame("a"=runif(100),
                   "b"=runif(100))

mean_a <- mean(data$a)

ggplot(data)+
  geom_point(aes(x=a,
                 y=b,
                 color=a),
             stat="identity")+
  scale_color_gradientn(colors=c("red","black","green"),
                        values=c(0, mean_a, 1))+
  theme(legend.position = NULL)

Mapping the scale_color_gradientn function is apparently not the way forward:

data %>%
  mutate(color_values=map(a, scale_color_gradientn,
                          colors=c("red","black","green"),
                          values=c(0, mean_a, 1))) %>%
  head()
#>           a         b                      color_values
#> 1 0.2863037 0.9902960 <environment: 0x000000001d002f30>
#> 2 0.6169960 0.9527580 <environment: 0x000000001d038798>
#> 3 0.3126825 0.8807853 <environment: 0x000000001d06e098>
#> 4 0.5464037 0.2307841 <environment: 0x000000001d0a39a8>
#> 5 0.5162976 0.8147066 <environment: 0x000000001d0d92a8>
#> 6 0.7519632 0.6821084 <environment: 0x000000001d10cc98>

Created on 2020-02-17 by the reprex package (v0.3.0)

I came across this SO entry on the colorRamp function, however, it seems that it does not provide any option to define a manual 'mid' point.

I also came accross this post on colorspace package, which allows for the definition of a midpoint. However, again, I fail to apply it outside of ggplot.

Grateful for any hint!

Body:
You can get the hex values that follow the gradient of your colorbar in a ggplot as follows:

gg_build() solution

    set.seed(1)
    data <- data.frame("a"=runif(100),"b"=runif(100))

    mean_a <- mean(data$a)

    p1 <- ggplot(data)+
      geom_point(aes(x=a,
        y=b,
        color=a),
        stat="identity")+
      scale_color_gradientn(
        colors=c("red","black","green"),
        values=c(0, mean_a, 1))+
      theme(legend.position = NULL)

    # get plot build
    build <- ggplot_build(p1)

    # select hex value and x-value data
    hex_df <- build$data[[1]][, c("colour", "x")]

    # order hex value data to follow x-axis
    hex_df_ordered <- hex_df[order(hex_df$x),]

scales::gradient_n_pal() solution

Here is perhaps the approach you want using the scales package function gradient_n_pal, which is called by scale_color_gradientn:

    library(ggplot2)
    library(scales)
    library(ggpubr)

    # create data
    set.seed(1)
    data <- data.frame("a"=runif(100), "b"=runif(100))
    #get mean_a
    mean_a <- mean(data$a)
    # order the data by a
    data <- data[order(data$a),]
    # encode the values in a character variable for reference
    data$a_char <- as.character(data$a)

    # use the scales::gradient_n_pal to create a palette function
    pal <- scales::gradient_n_pal(colours = c("red","black","green"),
      values= c(0, mean_a, 1))
    # use data in a to generate palette-generated values in the data
    data$hex_from_scales <- pal(data$a)

    # plot with scale_color_gradientn
    p1 <- ggplot(data)+
      geom_point(aes(x=a,
        y=b,
        color=a),
        stat="identity", show.legend = F)+
      scale_color_gradientn(colors=c("red","black","green"),values=c(0, mean_a, 1))+
      ggtitle("Using scale_color_gradientn ")+
      theme(legend.position = NULL)

    # plot with scale_color_manual and gradient_n_pal generated hex values
    p2 <- ggplot(data)+
      geom_point(aes(x=a,
        y=b,
        color=a_char),
        stat="identity", show.legend = F)+
      scale_color_manual(values = data$hex_from_scales)+
      ggtitle("Using gradient_n_pal")+
      theme(legend.position = NULL)

    plots <- ggpubr::ggarrange(p1, p2, ncol = 2)

This code generates these plots:

Conclusion

Judging by the similarity of the two plots, it seems like you can get the hex values of your numeric vector with this snippet:

        # create a palette function
        pal <- scales::gradient_n_pal(colours = c("red","black","green"),values= c(0, mean_a, 1))
        # get palette-generated values from your vector
        data$hex_from_scales <- pal(data$a)

It is also notable that this solution generates slightly different hex codes as the ggplot_build() solution proposed above. My eyes tell me the differences are slight. Seeing is believing!


问:
django url tag with dynamic app_label
i'm trying to create a dynamic url tag for my class based listview. it's needed for a delete button on every list item it loops over. the issue is that I use this template in multiple apps and want to reuse it.
what currently works:
[filename.html]

```<code>{% for file in object_list %}
      <tr>
        <td>{{file.stream}} </td>
        <td>{{file.regExpFilename}}</td>
        <form class="delete-form" method="POST" action="{% url 'MyApp1:filenames_delete' pk=file.stream %}">
            <button type="submit" value="delete" class="btn-delete"
              onclick="return confirm('Are you sure to delete {{file.stream}} {{file.regExpFile}}?')">
              Delete
            </button>
</code>```

core.urls.py

```<code>"Filename":[
            path('filenames/', views.FilenameView.as_view(), name='filenames'),
            path('filenames/create', views.FilenameCreateView.as_view(), name='filenames_create'),
            path('filenames/delete/<pk>', views.FilenameDeleteView.as_view(), name='filenames_delete'),
</code>```

core.views.filenames.py

```<code>class FilenameView(generic.ListView):

    def get_context_data(self, **kwargs) -> dict:
        model_name = self.model._meta.model_name
        context = super().get_context_data(**kwargs)
        app_label = self.model._meta.app_label
        context["create_url"] = reverse("{}:filenames_create".format(app_label))
        return context
</code>```

But I want to remove the 'MyApp' to make it reusable for multiple apps.

Many Thanks,

答:
You can create custom template processor:

```<code>def apps_context_processor(request):
    return {
        'item_delete_url': reverse(f'{request.resolver_match.app_name}:filenames_delete')
    }
</code>```

And then use this in your template url tag.

Title: django url tag with dynamic app_label

Body:
i'm trying to create a dynamic url tag for my class based listview. it's needed for a delete button on every list item it loops over. the issue is that I use this template in multiple apps and want to reuse it.
what currently works:
[filename.html]

{% for file in object_list %}

        {{file.stream}}
        {{file.regExpFilename}}
        <form class="delete-form" method="POST" action="{% url 'MyApp1:filenames_delete' pk=file.stream %}">
            <button type="submit" value="delete" class="btn-delete"
              onclick="return confirm('Are you sure to delete {{file.stream}} {{file.regExpFile}}?')">
              Delete
            </button>

core.urls.py

"Filename":[
            path('filenames/', views.FilenameView.as_view(), name='filenames'),
            path('filenames/create', views.FilenameCreateView.as_view(), name='filenames_create'),
            path('filenames/delete/<pk>', views.FilenameDeleteView.as_view(), name='filenames_delete'),

core.views.filenames.py

class FilenameView(generic.ListView):

    def get_context_data(self, **kwargs) -> dict:
        model_name = self.model._meta.model_name
        context = super().get_context_data(**kwargs)
        app_label = self.model._meta.app_label
        context["create_url"] = reverse("{}:filenames_create".format(app_label))
        return context

But I want to remove the 'MyApp' to make it reusable for multiple apps.

Many Thanks,

Body:
You can create custom template processor:

def apps_context_processor(request):
    return {
        'item_delete_url': reverse(f'{request.resolver_match.app_name}:filenames_delete')
    }

And then use this in your template url tag.


问:
How to use bottom navigator 'OnTap' in flutter
I have an app where i have a list(for eg news).And in the bottom toolbar i have a previous and next button.what i want to do is if i am on **third news and i clicked on the previous button it should go on second news.**I have made the toolbar and will attach the code below.I have added full code for better understanding.Thank you.</p>

```<code>class Newsdetail extends StatefulWidget {
 String  value_image, value_description, value_title;
  int index;

  Newsdetail(
      {Key key,
      @required this.value_image,
      this.value_description,
      this.value_title,
      this.index})
      : super(key: key);

  @override
  _newsdetail createState() => _newsdetail();
}

class _newsdetail extends State<Newsdetail> {
  int _currentindex=0;
  _newsdetail();
  var tabs =[];

    loadyourNews() async {

setState(() {

  tabs = [
  Container(
    child: SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: Column(
        children: <Widget>[
          Padding(padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(child:
                Image.network(widget.value_image))
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Row(
                    children: <Widget>[
                      IconButton(
                          icon: Image.asset('images/facebook.png',),
                          padding: EdgeInsets.all(0.0),
                          onPressed: () {
                            _openFacebook();
                          }),
                      IconButton(
                        icon: Image.asset('images/twitter.png',),
                        padding: EdgeInsets.all(0.0),
                        onPressed: () {
                          _openTwitter();
                        },
                      ),
                      IconButton(
                        icon: Image.asset(
                          'images/whatsappicon.png', width: 180.0,
                          height: 180.0,),
                        padding: EdgeInsets.all(4.0),
                        onPressed: () {
                          _openWhatsapp();
                        },
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    widget.value_title,
                    style: TextStyle(
                        fontSize: 22.0, fontWeight: FontWeight.bold),
                  ),
                ),

              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                    child: Text(
                      widget.value_description,
                      style: TextStyle(fontSize: 20.0),
                    )),
              ],
            ),
          ),
        ],
      ),
    ),
  )
];
});

  }

  @override
  void initState() {
    super.initState();
    loadyourNews();
  }
@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(0,0,5.0,0),
            child: SizedBox(
                width: 30,
                child: FlatButton(
                    padding: EdgeInsets.all(0),
                    onPressed: (){},
                    child: Text('A+',style: TextStyle(
                        fontSize: 22.0,color: Colors.white
                    ),))),
          ),

          Padding(
            padding: EdgeInsets.fromLTRB(0,0,38.0,0),
            child: SizedBox(
                width: 30,
                child:FlatButton(
                  padding: EdgeInsets.all(0),
                  onPressed: (){},
                  child: Text('A-',style: TextStyle(
                      fontSize: 15.0,color: Colors.white
                  ),),

                )),
          )

        ],
      ),
      body: tabs[_currentindex],

      bottomNavigationBar:BottomNavigationBar(
        currentIndex: _currentindex,
        backgroundColor: Color(0xFF125688),
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_back),
            title: Text('Previous',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_forward),
            title: Text('Next',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
        ],
        onTap: (index){
          setState(() {
            if (index == 0) {
              _currentindex = (_currentindex - 1) % tabs.length;
              if (_currentindex < 0) _currentindex += _currentindex;
            } else
              _currentindex = (_currentindex + 1) % tabs.length;
          });

        },
      ),

    );
  }
</code>```

答: Use Navigator.push and Navigator.pop for next and previous button respectively.</p>

Body:
I have an app where i have a list(for eg news).And in the bottom toolbar i have a previous and next button.what i want to do is if i am on **third news and i clicked on the previous button it should go on second news.**I have made the toolbar and will attach the code below.I have added full code for better understanding.Thank you.

class Newsdetail extends StatefulWidget {
 String  value_image, value_description, value_title;
  int index;

  Newsdetail(
      {Key key,
      @required this.value_image,
      this.value_description,
      this.value_title,
      this.index})
      : super(key: key);

  @override
  _newsdetail createState() => _newsdetail();
}

class _newsdetail extends State<Newsdetail> {
  int _currentindex=0;
  _newsdetail();
  var tabs =[];

    loadyourNews() async {

setState(() {

  tabs = [
  Container(
    child: SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: Column(
        children: <Widget>[
          Padding(padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(child:
                Image.network(widget.value_image))
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Row(
                    children: <Widget>[
                      IconButton(
                          icon: Image.asset('images/facebook.png',),
                          padding: EdgeInsets.all(0.0),
                          onPressed: () {
                            _openFacebook();
                          }),
                      IconButton(
                        icon: Image.asset('images/twitter.png',),
                        padding: EdgeInsets.all(0.0),
                        onPressed: () {
                          _openTwitter();
                        },
                      ),
                      IconButton(
                        icon: Image.asset(
                          'images/whatsappicon.png', width: 180.0,
                          height: 180.0,),
                        padding: EdgeInsets.all(4.0),
                        onPressed: () {
                          _openWhatsapp();
                        },
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    widget.value_title,
                    style: TextStyle(
                        fontSize: 22.0, fontWeight: FontWeight.bold),
                  ),
                ),

              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                    child: Text(
                      widget.value_description,
                      style: TextStyle(fontSize: 20.0),
                    )),
              ],
            ),
          ),
        ],
      ),
    ),
  )
];
});

  }

  @override
  void initState() {
    super.initState();
    loadyourNews();
  }
@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(0,0,5.0,0),
            child: SizedBox(
                width: 30,
                child: FlatButton(
                    padding: EdgeInsets.all(0),
                    onPressed: (){},
                    child: Text('A+',style: TextStyle(
                        fontSize: 22.0,color: Colors.white
                    ),))),
          ),

          Padding(
            padding: EdgeInsets.fromLTRB(0,0,38.0,0),
            child: SizedBox(
                width: 30,
                child:FlatButton(
                  padding: EdgeInsets.all(0),
                  onPressed: (){},
                  child: Text('A-',style: TextStyle(
                      fontSize: 15.0,color: Colors.white
                  ),),

                )),
          )

        ],
      ),
      body: tabs[_currentindex],

      bottomNavigationBar:BottomNavigationBar(
        currentIndex: _currentindex,
        backgroundColor: Color(0xFF125688),
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_back),
            title: Text('Previous',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_forward),
            title: Text('Next',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
        ],
        onTap: (index){
          setState(() {
            if (index == 0) {
              _currentindex = (_currentindex - 1) % tabs.length;
              if (_currentindex < 0) _currentindex += _currentindex;
            } else
              _currentindex = (_currentindex + 1) % tabs.length;
          });

        },
      ),

    );
  }


问:
Error Cannot reconfigure existing key "excel"
I tried to do a cake i18n extract and i got this error.

```<code>Exception: Cannot reconfigure existing key "excel" in [C:\wamp64\www\boyma2\vendor\cakephp\cakephp\src\Core\StaticConfigTrait.php, line 88]
</code>```

I don't know why that mistake comes out and now he doesn't let me make a cake bake all

答: Looks like you are setting "excel" key configuration value again. Please refer to this link here.</p>

Body:
I tried to do a cake i18n extract and i got this error.

Exception: Cannot reconfigure existing key "excel" in [C:\wamp64\www\boyma2\vendor\cakephp\cakephp\src\Core\StaticConfigTrait.php, line 88]

I don't know why that mistake comes out and now he doesn't let me make a cake bake all


问:
Unable to pass the JobParameters Value to the tasklet in Spring Batch
I already followed link: Pass JobParameters and ExecutionContext to @Bean Tasklet?, but still facing issue while passing the jobParameters value to the tasklet.

I've developed a code like below:

JobConfiguration.java

```<code>@Component
public class JobConfiguration implements ApplicationContextAware{

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobExplorer jobExplorer;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private JobRegistry jobRegistry;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    @StepScope
    public Tasklet tasklet(@Value("#{jobParameters['name']}") String name) {
        System.out.println("NAME VALUE  = "+name);
        return (contribution, chunkContext) -> {
            System.out.println(String.format("The job run for %s", name));
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("job")
                .start(stepBuilderFactory.get("step1")
                        .tasklet(tasklet(null))
                        .build())
                .build();
    }
}
</code>```

JobLaunchingController.java

```<code>@RestController
public class JobLaunchingController {
    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job job;

    @PostMapping("/")
    @ResponseStatus(value = HttpStatus.ACCEPTED)
    public void launch(@RequestParam("name") String name) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
        JobParameters jobParameters = new JobParametersBuilder()
                .addString("name", name)
                .toJobParameters();
        JobExecution jobExecution = this.jobLauncher.run(job, jobParameters);
        System.out.println("STATUS = "+jobExecution.getStatus());
    }
}
</code>```

Logs:

```<code>2018-12-13 23:09:35.930  INFO 20004 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-12-13 23:09:35.930  INFO 20004 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2018-12-13 23:09:35.938  INFO 20004 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
2018-12-13 23:09:55.046  INFO 20004 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job]] launched with the following parameters: [{name=foo}]
2018-12-13 23:09:55.414  INFO 20004 --- [nio-8080-exec-1] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
The job run for null
2018-12-13 23:09:55.672  INFO 20004 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job]] completed with the following parameters: [{name=foo}] and the following status: [COMPLETED]
STATUS = COMPLETED
</code>```

StartingAJobApplication.java

```<code>@SpringBootApplication
@EnableBatchProcessing
public class StartingAJobApplication {

    public static void main(String[] args) {
        SpringApplication.run(StartingAJobApplication.class, args);
    }
}
</code>```

CURL:

curl --data 'name=foo' localhost:8080

答:
When you implement “execute” method, you have SetpContribution and ChunkContext as parameters. You have to use ChunkContext to get jobParameter.</p>

```<code>  @Override
  public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {

    JobParameters jobParameters = chunkContext.getStepContext().getStepExecution().getJobParameters();

      ...
}
</code>```

Body:
I already followed link: Pass JobParameters and ExecutionContext to @Bean Tasklet?, but still facing issue while passing the jobParameters value to the tasklet.

I've developed a code like below:

JobConfiguration.java

@Component
public class JobConfiguration implements ApplicationContextAware{

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobExplorer jobExplorer;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private JobRegistry jobRegistry;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    @StepScope
    public Tasklet tasklet(@Value("#{jobParameters['name']}") String name) {
        System.out.println("NAME VALUE  = "+name);
        return (contribution, chunkContext) -> {
            System.out.println(String.format("The job run for %s", name));
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("job")
                .start(stepBuilderFactory.get("step1")
                        .tasklet(tasklet(null))
                        .build())
                .build();
    }
}

JobLaunchingController.java

@RestController
public class JobLaunchingController {
    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job job;

    @PostMapping("/")
    @ResponseStatus(value = HttpStatus.ACCEPTED)
    public void launch(@RequestParam("name") String name) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
        JobParameters jobParameters = new JobParametersBuilder()
                .addString("name", name)
                .toJobParameters();
        JobExecution jobExecution = this.jobLauncher.run(job, jobParameters);
        System.out.println("STATUS = "+jobExecution.getStatus());
    }
}

Logs:

2018-12-13 23:09:35.930  INFO 20004 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-12-13 23:09:35.930  INFO 20004 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2018-12-13 23:09:35.938  INFO 20004 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
2018-12-13 23:09:55.046  INFO 20004 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job]] launched with the following parameters: [{name=foo}]
2018-12-13 23:09:55.414  INFO 20004 --- [nio-8080-exec-1] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
The job run for null
2018-12-13 23:09:55.672  INFO 20004 --- [nio-8080-exec-1] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=job]] completed with the following parameters: [{name=foo}] and the following status: [COMPLETED]
STATUS = COMPLETED

StartingAJobApplication.java

@SpringBootApplication
@EnableBatchProcessing
public class StartingAJobApplication {

    public static void main(String[] args) {
        SpringApplication.run(StartingAJobApplication.class, args);
    }
}

CURL:

curl --data 'name=foo' localhost:8080

Body:
When you implement “execute” method, you have SetpContribution and ChunkContext as parameters. You have to use ChunkContext to get jobParameter.

  @Override
  public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {

    JobParameters jobParameters = chunkContext.getStepContext().getStepExecution().getJobParameters();

      ...
}


问:
How do I generate array values in Vue.js and show them?
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div>
        <h2> {{ player.ap }} </h2>
        <h2> {{ player.df }} </h2>
        <h2> {{ player.iq }} </h2>
    </div>
</template></code>```

答:
Here is a dynamic array value display :</p>

```<code><template>
  <div>
    <h2 v-for="player in players" v-bind:key="player.prop2">{{ player.prop1 }}</h2>
  </div>
</template>

<script>
export default {
  name: "FrontPage",
  data: function() {
    return {
      players: [{ prop1:this.ngen(), prop2:0},
                { prop1:this.ngen(), prop2:1},
                { prop1:this.ngen(), prop2:2}]
    };
  },
  methods: {
    ngen: function() {
      return Math.random();
    }
  }
};
</script>
</code>```

Body:
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}

<template>

 {{ player.ap }}

 {{ player.df }}

 {{ player.iq }}

</template>

Body:
Here is a dynamic array value display :

<template>
  <div>
    <h2 v-for="player in players" v-bind:key="player.prop2">{{ player.prop1 }}</h2>
  </div>
</template>

<script>
export default {
  name: "FrontPage",
  data: function() {
    return {
      players: [{ prop1:this.ngen(), prop2:0},
                { prop1:this.ngen(), prop2:1},
                { prop1:this.ngen(), prop2:2}]
    };
  },
  methods: {
    ngen: function() {
      return Math.random();
    }
  }
};
</script>


问:
What is pip's `--no-cache-dir` good for?
I've recently seen the --no-cache-dir being used in a Docker file. I've never seen that flag before and the help is not explaining it:

```<code> --no-cache-dir              Disable the cache.
</code>```

Question: What is cached?

Question: What is the cache used for?

Question: Why would I want to disable it?

答:
I get permission error for installation of some pip packages if I don't use --no-cache-dir option.

```<code>Building wheels for collected packages: pyyaml, bottleneck, nvidia-ml-py3
  WARNING: Building wheel for pyyaml failed: [Errno 13] Permission denied: '/home/user/.cache/pip/wheels/b1'
  WARNING: Building wheel for bottleneck failed: [Errno 13] Permission denied: '/home/user/.cache/pip/wheels/92'
  WARNING: Building wheel for nvidia-ml-py3 failed: [Errno 13] Permission denied: '/home/user/.cache/pip/wheels/7f'
</code>```

chown /.cache folder didn't help for some reason but with --no-cache-dir it works ok.

ContentLicense: CC BY-SA 3.0

Body:
I've recently seen the --no-cache-dir being used in a Docker file. I've never seen that flag before and the help is not explaining it:

 --no-cache-dir              Disable the cache.

Question: What is cached?

Question: What is the cache used for?

Question: Why would I want to disable it?

Body:
I get permission error for installation of some pip packages if I don't use --no-cache-dir option.

Building wheels for collected packages: pyyaml, bottleneck, nvidia-ml-py3
  WARNING: Building wheel for pyyaml failed: [Errno 13] Permission denied: '/home/user/.cache/pip/wheels/b1'
  WARNING: Building wheel for bottleneck failed: [Errno 13] Permission denied: '/home/user/.cache/pip/wheels/92'
  WARNING: Building wheel for nvidia-ml-py3 failed: [Errno 13] Permission denied: '/home/user/.cache/pip/wheels/7f'

chown /.cache folder didn't help for some reason but with --no-cache-dir it works ok.


问:
Replacing a number in a string with jquery
I have a string which has a number in it that I would like to replace with another number.

ie

```<code><a href="" id="my_link">blah blah 32 blah blah</a>
</code>```

I know there is only going to be 1 number in this string.

I can get this far:

```<code>var my_string = $('a#my_link').text();
</code>```

But basically I don't know how to then perform a search on my_string for a numeral and replace that number with something else.

Is that possible with jQuery?

Thanks for any ideas.

答:
If you need extract number and then replace with other value.

```<code>let temp ="<polygon points=' 42,4874 936,4874 936,3434 42,3434'></polygon>"
temp.replace(/(\d+)/g,v=>v*10)
</code>```

multiply by 10 to each number

result will be "<polygon points=' 420,48740 9360,48740 9360,34340 420,34340'></polygon>"

ContentLicense: CC BY-SA 2.5

Body:
I have a string which has a number in it that I would like to replace with another number.

ie

blah blah 32 blah blah

I know there is only going to be 1 number in this string.

I can get this far:

var my_string = $('a#my_link').text();

But basically I don't know how to then perform a search on my_string for a numeral and replace that number with something else.

Is that possible with jQuery?

Thanks for any ideas.

Body:
If you need extract number and then replace with other value.

let temp ="<polygon points=' 42,4874 936,4874 936,3434 42,3434'></polygon>"
temp.replace(/(\d+)/g,v=>v*10)

multiply by 10 to each number

result will be "<polygon points=' 420,48740 9360,48740 9360,34340 420,34340'></polygon>"


问:
How to read binary data from dicom file?
How to read raw image data from uncompressed DICOM file and dump it to a file. I just use the following code for compressed files. using dcmtk library

```<code>dataSet->findAndGetElement(DCM_PixelData, element);
pixDataElem = OFstatic_cast(DcmPixelData*, element);

DcmPixelSequence *pixelSequence = NULL;
E_TransferSyntax tran_Syntax = EXS_Unknown;
const DcmRepresentationParameter *representation = NULL;

// Find the key that is needed to access the right representation of the data within DCMTK
pixDataElem->getOriginalRepresentationKey(tran_Syntax, representation);
//pixDataElem->getCurrentRepresentationKey(tran_Syntax, representation);

// Access original data representation and get result within pixel sequence
pixDataElem->getEncapsulatedRepresentation(tran_Syntax, representation, pixelSequence);

    DcmPixelItem *pixelItem = NULL;
    //Access the First frame by skipping the offset table...
    pixelSequence->getItem(pixelItem, 1);

    Uint8 *pixels = NULL;
    pixDataElem = (DcmPixelData*)pixelItem;
    pixDataElem->getUint8Array(pixels);
    Uint8 *pixels = NULL;
    pixDataElem->getUint8Array(pixels);
    //Writing the Raw data to a file...
    FILE *file;
    file = fopen("D:\\DicomImage.jpeg", "wb");
    fwrite(pixels, sizeof(char), imageSize, file);
    cout << "File write Completed and the File is closed Successfully" << endl;
</code>```

How can I raw image data from the uncompressed files with many frames in c++ using dcmtk library.....?

答:
If you know that the images are not compressed, then you could access the first frame's raw data in this way with Imebra:

```<code>imebra::DataSet loadedDataSet = imebra::CodecFactory::Load("pathToFileName);

size_t imageWidth = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::Columns_0028_0011), 0);
size_t imageHeight = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::Rows_0028_0010), 0);
size_t channels = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::SamplesPerPixel_0028_0002), 0);
size_t allocatedBits = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::BitsAllocated_0028_0100), 0);
size_t totalSizeBytes = (imageWidth * imageHeight * allocatedBits * channels + 7) / 8;

ReadingDataHandlerNumeric rawData = loadedDataSet.getReadingDataHandlerNumeric(TagId(PixelData_7FE0_0010), 0);

size_t dataSize(0);
const char* pMemory = rawData.data(&dataSize);
// Now pMemory points to the raw data, dataSize holds the memory size
</code>```

If you need the second frame or the images are compressed then you should use imebra::DataSet::getImage() and let imebra find the proper memory area and decompress the image for you.

Please note that consecutive uncompressed images are not aligned on byte boundary but the first bit of the second frame may be on the same byte containing the last bit of the first frame. For compressed images you may have to deal with a offset table pointing to the buffers containing the images.

Disclaimer: I'm the author of Imebra.

Body:
How to read raw image data from uncompressed DICOM file and dump it to a file. I just use the following code for compressed files. using dcmtk library

dataSet->findAndGetElement(DCM_PixelData, element);
pixDataElem = OFstatic_cast(DcmPixelData*, element);

DcmPixelSequence *pixelSequence = NULL;
E_TransferSyntax tran_Syntax = EXS_Unknown;
const DcmRepresentationParameter *representation = NULL;

// Find the key that is needed to access the right representation of the data within DCMTK
pixDataElem->getOriginalRepresentationKey(tran_Syntax, representation);
//pixDataElem->getCurrentRepresentationKey(tran_Syntax, representation);

// Access original data representation and get result within pixel sequence
pixDataElem->getEncapsulatedRepresentation(tran_Syntax, representation, pixelSequence);

    DcmPixelItem *pixelItem = NULL;
    //Access the First frame by skipping the offset table...
    pixelSequence->getItem(pixelItem, 1);

    Uint8 *pixels = NULL;
    pixDataElem = (DcmPixelData*)pixelItem;
    pixDataElem->getUint8Array(pixels);
    Uint8 *pixels = NULL;
    pixDataElem->getUint8Array(pixels);
    //Writing the Raw data to a file...
    FILE *file;
    file = fopen("D:\\DicomImage.jpeg", "wb");
    fwrite(pixels, sizeof(char), imageSize, file);
    cout << "File write Completed and the File is closed Successfully" << endl;

How can I raw image data from the uncompressed files with many frames in c++ using dcmtk library.....?

Body:
If you know that the images are not compressed, then you could access the first frame's raw data in this way with Imebra:

imebra::DataSet loadedDataSet = imebra::CodecFactory::Load("pathToFileName);

size_t imageWidth = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::Columns_0028_0011), 0);
size_t imageHeight = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::Rows_0028_0010), 0);
size_t channels = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::SamplesPerPixel_0028_0002), 0);
size_t allocatedBits = loadedDataSet.getUint32(imebra::TagId(imebra::tagId_t::BitsAllocated_0028_0100), 0);
size_t totalSizeBytes = (imageWidth * imageHeight * allocatedBits * channels + 7) / 8;

ReadingDataHandlerNumeric rawData = loadedDataSet.getReadingDataHandlerNumeric(TagId(PixelData_7FE0_0010), 0);

size_t dataSize(0);
const char* pMemory = rawData.data(&dataSize);
// Now pMemory points to the raw data, dataSize holds the memory size

If you need the second frame or the images are compressed then you should use imebra::DataSet::getImage() and let imebra find the proper memory area and decompress the image for you.

Please note that consecutive uncompressed images are not aligned on byte boundary but the first bit of the second frame may be on the same byte containing the last bit of the first frame. For compressed images you may have to deal with a offset table pointing to the buffers containing the images.

Disclaimer: I'm the author of Imebra.


问:
Auto select value of dropdown
i have an dropdown like this:

```<code><select id="cbvms" name="cbvms" class="SelectList">
        <?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected=\"".$value."\">".$value."</option>";
            else
                //echo "<option value=\"".$key."\">".$value."</option>";
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>
    and in my database i have an option value like this ....
</code>```

VM name:

```<code> 172.125.4.186
 172.125.4.101
 172.125.4.194
 172.125.4.126
 172.125.4.167
 172.125.4.102
 172.125.4.171
 172.125.4.118
 172.125.4.169
 Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101
 salman
 saman
 172.125.4.198
 172.125.4.200
 172.125.4.189
 172.125.4.191
</code>```

now i want when some one select any option value as shown as above my dropdown autosize

for example: when user select 172.125.4.169 then its fit on the size of dropdown, or when the user select "Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101" then its also fit on the dropdown.

Right now if the VM name is long, the drop down field for Select VM goes out of range....

答:
use this</p>

```<code><select id="cbvms" name="cbvms" class="SelectList" style="width:120px;">
</code>```

Title: Auto select value of dropdown

Body:
i have an dropdown like this:

<select id="cbvms" name="cbvms" class="SelectList">
        <?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected=\"".$value."\">".$value."</option>";
            else
                //echo "<option value=\"".$key."\">".$value."</option>";
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>
    and in my database i have an option value like this ....

VM name:

 172.125.4.186
 172.125.4.101
 172.125.4.194
 172.125.4.126
 172.125.4.167
 172.125.4.102
 172.125.4.171
 172.125.4.118
 172.125.4.169
 Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101
 salman
 saman
 172.125.4.198
 172.125.4.200
 172.125.4.189
 172.125.4.191

now i want when some one select any option value as shown as above my dropdown autosize

for example: when user select 172.125.4.169 then its fit on the size of dropdown, or when the user select "Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101" then its also fit on the dropdown.

Right now if the VM name is long, the drop down field for Select VM goes out of range....

Body:
use this

<select id="cbvms" name="cbvms" class="SelectList" style="width:120px;">


问:
Developing a J2ME application on Ubuntu in the current year?
I recently dug out an old phone that runs J2ME applications and would like to write applications for it, in my attempts to get the SDK running with Netbeans and figure out the emulator I've hit many roadblocks caused by various compatibility issues due to the toolchain being so old.

So my question is this: What is the most straightforward, minimalist way for me to compile a J2ME hello world application. I don't need an IDE and am fine without an emulator, I just want to use Ubuntu to produce a .jar that will run on my phone.

答:
Two years ago I used the following steps to develop with emulator.

Download JDK 1.6 32 bits, uncompress, mv to /usr/lib/jvm/, chown to root.

Download Sun Java Wireless Toolkit 2.5.2_01, install and set java executable path to /usr/lib/jvm/jdk1.6.0_45/bin

```<code>sudo apt-get install libxi6:i386 libxt6:i386
./WTK2.5.2/bin/ktoolbar
</code>```

From this point onwards you can focus on how ktoolbar handles projects. IDE project setup should use CLDC and MIDP libs under ktoolbar folder structure.

Body:
Two years ago I used the following steps to develop with emulator.

Download JDK 1.6 32 bits, uncompress, mv to /usr/lib/jvm/, chown to root.

Download Sun Java Wireless Toolkit 2.5.2_01, install and set java executable path to /usr/lib/jvm/jdk1.6.0_45/bin

sudo apt-get install libxi6:i386 libxt6:i386
./WTK2.5.2/bin/ktoolbar

From this point onwards you can focus on how ktoolbar handles projects. IDE project setup should use CLDC and MIDP libs under ktoolbar folder structure.


问:
git rebase could not execute editor
I'm attempting to squash some git commits using rebase. When I run this:

```<code>git rebase -i HEAD
</code>```

I get this error:

```<code>/usr/lib/git-core/git-rebase: 1: eval: /usr/bin/mate: not found
Could not execute editor
</code>```

I've attempted to change the git config editor variable but I haven't gotten it to work. Right now my config file shows the following:

```<code>[core]
    editor = /usr/bin/vim
</code>```

I'm running Ubuntu 13.04

Any ideas?

答:
As additional measure you can look at the sequence.editor config option:

```<code>[sequence]
    editor = /usr/bin/vim
</code>```

or override it's behavior with GIT_SEQUENCE_EDITOR=/usr/bin/vim env variable.

More details you can find on: git-config.txt-sequenceeditor

Title: git rebase could not execute editor

Body:
I'm attempting to squash some git commits using rebase. When I run this:

git rebase -i HEAD

I get this error:

/usr/lib/git-core/git-rebase: 1: eval: /usr/bin/mate: not found
Could not execute editor

I've attempted to change the git config editor variable but I haven't gotten it to work. Right now my config file shows the following:

[core]
    editor = /usr/bin/vim

I'm running Ubuntu 13.04

Any ideas?

Body:
As additional measure you can look at the sequence.editor config option:

[sequence]
    editor = /usr/bin/vim

or override it's behavior with GIT_SEQUENCE_EDITOR=/usr/bin/vim env variable.

More details you can find on: git-config.txt-sequenceeditor


问:
Optimize this for-loop procedure to avoid a program crash
I'm struggling trying to perform an operation in R without it crashing. I give you a reproducible example. I have X:

```<code>X <- data.frame(V1 = c("chr1", "chr1", "chr1", "chr1", "chr1"),
                Start = c(0, 1001, 3002, 4059, 6581),
                Stop = c(1000, 3001, 4058, 6580, 7002),
                A = c(10, 4, 5, 6, 9),
                B = c(923, 39, 5, 9, 93),
                C = c(239, 2, 13, 4, 5))
</code>```

And I want to perform this operation:

```<code>for (row in 1:nrow(X)){
  X$A <- (X$A / (X[row, "Stop"] - X[row, "Start"])) * mean(X$Stop - X$Start)
  X$B <- (X$B / (X[row, "Stop"] - X[row, "Start"])) * mean(X$Stop - X$Start)
  X$C <- (X$C / (X[row, "Stop"] - X[row, "Start"])) * mean(X$Stop - X$Start)
}
</code>```

My problem appears when my document is a lot larger (like 2.000.000 rows). Is there any way to do this operation faster in such a large data.frame?

答:
If you are NOT going to overwrite the whole column with updated values every iteration, you might want to consider these solutions as well. data.table copes pretty well with big datasets.

```<code>library(data.table)      # loads library
setDT(X)                 # converts data.frame to data.table
cols = c("A", "B", "C")  # defines the columns to update
avg.diff = X[, mean(Stop - Start)]   # caclulates average difference between Stop and Start
X[, (cols) := lapply(.SD, function(x) {avg.diff * x / (Stop - Start)}), .SDcols = cols]  # makes calculations
</code>```

Or the same, but a bit easier to understand:

```<code>X[, `:=`(
  A = avg.diff * A / (Stop - Start),
  B = avg.diff * B / (Stop - Start),
  C = avg.diff * C / (Stop - Start)
)]
</code>```

Feel free to adjust these solutions according to your needs.

Body:
I'm struggling trying to perform an operation in R without it crashing. I give you a reproducible example. I have X:

X <- data.frame(V1 = c("chr1", "chr1", "chr1", "chr1", "chr1"),
                Start = c(0, 1001, 3002, 4059, 6581),
                Stop = c(1000, 3001, 4058, 6580, 7002),
                A = c(10, 4, 5, 6, 9),
                B = c(923, 39, 5, 9, 93),
                C = c(239, 2, 13, 4, 5))

And I want to perform this operation:

for (row in 1:nrow(X)){
  X$A <- (X$A / (X[row, "Stop"] - X[row, "Start"])) * mean(X$Stop - X$Start)
  X$B <- (X$B / (X[row, "Stop"] - X[row, "Start"])) * mean(X$Stop - X$Start)
  X$C <- (X$C / (X[row, "Stop"] - X[row, "Start"])) * mean(X$Stop - X$Start)
}

My problem appears when my document is a lot larger (like 2.000.000 rows). Is there any way to do this operation faster in such a large data.frame?

Body:
If you are NOT going to overwrite the whole column with updated values every iteration, you might want to consider these solutions as well. data.table copes pretty well with big datasets.

library(data.table)      # loads library
setDT(X)                 # converts data.frame to data.table
cols = c("A", "B", "C")  # defines the columns to update
avg.diff = X[, mean(Stop - Start)]   # caclulates average difference between Stop and Start
X[, (cols) := lapply(.SD, function(x) {avg.diff * x / (Stop - Start)}), .SDcols = cols]  # makes calculations

Or the same, but a bit easier to understand:

X[, `:=`(
  A = avg.diff * A / (Stop - Start),
  B = avg.diff * B / (Stop - Start),
  C = avg.diff * C / (Stop - Start)
)]

Feel free to adjust these solutions according to your needs.


问:
Page redirects incorrectly if a user is logged in
I'm currently working on a login functionality of a web application.

I have the "Login Page" when I load the http://localhost:8080/test/, which can only be accessed if a user is not logged in.
Once the user is successfully logged in, he should now see the "Welcome Page" on http://localhost:8080/test/welcome, displaying a "Name" link.
Clicking the "Name" link should go to http://localhost:8080/test/welcome/name.
If the user have not logged out but visited the http://localhost:8080/test/, he should be redirected to "Welcome Page".

(The function is like the Facebook app. If you haven't logged out on Tab 1, you can still view your News Feed if you visited Facebook on Tab 2 of your browser.)

Here's the problem. While logged in, I'm able to load the "Welcome Page" when I visited http://localhost:8080/test/.
However, when I clicked on the "Name" link on the "Welcome Page", I was just redirected to http://localhost:8080/test/welcome, which is the link for the "Welcome Page". It seems that it just reloaded the page.

Here are some code sample:

Login.tsx

```<code><Switch>
    {checkLoginUserId() != null ?
        <Redirect to="/welcome" />
        : <Redirect to="/" />}
</Switch>
<Route path="/welcome" component={Welcome} />
<Route exact path="/" component={Login} />
</code>```

Welcome.tsx

```<code><Route exact={true} path="/welcome" component={Welcome} />
<Route path="/welcome/name" component={Name} />
</code>```

I don't know why it goes to the other route. It seems that the answer to my problem is very easy but I cannot pinpoint the culprit.

答:
Try something like this. Add you condition inside the render prop of Route. Also, add the Route inside the switch.

```<code> <Switch>
   <Route
     exact
     path="/welcome/:name"
     render={props => checkLoginUserId() != null ? (<Redirect to="/welcome" />) : (<Login {...props} />)}
  />
</code>```

Body:
I'm currently working on a login functionality of a web application.

I have the "Login Page" when I load the http://localhost:8080/test/, which can only be accessed if a user is not logged in.
Once the user is successfully logged in, he should now see the "Welcome Page" on http://localhost:8080/test/welcome, displaying a "Name" link.
Clicking the "Name" link should go to http://localhost:8080/test/welcome/name.
If the user have not logged out but visited the http://localhost:8080/test/, he should be redirected to "Welcome Page".

(The function is like the Facebook app. If you haven't logged out on Tab 1, you can still view your News Feed if you visited Facebook on Tab 2 of your browser.)

Here's the problem. While logged in, I'm able to load the "Welcome Page" when I visited http://localhost:8080/test/.
However, when I clicked on the "Name" link on the "Welcome Page", I was just redirected to http://localhost:8080/test/welcome, which is the link for the "Welcome Page". It seems that it just reloaded the page.

Here are some code sample:

Login.tsx

<Switch>
    {checkLoginUserId() != null ?
        <Redirect to="/welcome" />
        : <Redirect to="/" />}
</Switch>
<Route path="/welcome" component={Welcome} />
<Route exact path="/" component={Login} />

Welcome.tsx

<Route exact={true} path="/welcome" component={Welcome} />
<Route path="/welcome/name" component={Name} />

I don't know why it goes to the other route. It seems that the answer to my problem is very easy but I cannot pinpoint the culprit.

Body:
Try something like this. Add you condition inside the render prop of Route. Also, add the Route inside the switch.

 <Switch>
   <Route
     exact
     path="/welcome/:name"
     render={props => checkLoginUserId() != null ? (<Redirect to="/welcome" />) : (<Login {...props} />)}
  />


问:
How to convert values from 0: 270 to 0:1023 in Python?
Hi i need help with my script for Arduino with Python
I have python script it put out angle between 0-270
I need to convert this value to servo-read-able in meaning 0-1023
Can some one from community help me
Thanks</p>

答:
I And i have one more question.
I look on Internet but i cant find anything.
I work on quadruped robot i need some way if i stop my robot in some angle. Then i reboot him i get this position as home as 0,0 but i hook up on servo potenciometr. Is there any command in arduino to Updates servo posion by potenciometr value converted to angle but dont move the servo ex.[servo start: 0°,0°- now is on 70°,50° but it doest move] i hope you understood me</p>


问:
How to display a circle avatar image in flutter?
When using the folloing code I would expect a circle avatar image but getting an oval. I tried different parameters like width and height on the Container but that didn't help.</p>

```<code> appBar: AppBar(
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: new Icon(Icons.star_border, color: Colors.black),
          onPressed: () => {},
        ),
        actions: <Widget>[
          Container(
            //height: 25.0,
            // width: 25.0,
            child: CircleAvatar(
              backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
            )
            /*
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: NetworkImage(
                      'https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c')),
            ),*/
          ),
        ],
</code>```

答:
You are receiving an oval shape because you are using the CircleAvatar widget in Appbar widget which has limited height.

Try adding a parameter radius inside CircleAvatar Widget
it will return the circle shape you want for the image.

try changing radius size value, according to your need.

```<code>CircleAvatar(
          backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
         radius: 15.0
        )
</code>```

Body:
When using the folloing code I would expect a circle avatar image but getting an oval. I tried different parameters like width and height on the Container but that didn't help.

 appBar: AppBar(
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: new Icon(Icons.star_border, color: Colors.black),
          onPressed: () => {},
        ),
        actions: <Widget>[
          Container(
            //height: 25.0,
            // width: 25.0,
            child: CircleAvatar(
              backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
            )
            /*
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: NetworkImage(
                      'https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c')),
            ),*/
          ),
        ],

Body:
You are receiving an oval shape because you are using the CircleAvatar widget in Appbar widget which has limited height.

Try adding a parameter radius inside CircleAvatar Widget
it will return the circle shape you want for the image.

try changing radius size value, according to your need.

CircleAvatar(
          backgroundImage: NetworkImage('https://lh3.googleusercontent.com/a-/AAuE7mChgTiAe-N8ibcM3fB_qvGdl2vQ9jvjYv0iOOjB=s96-c'),
         radius: 15.0
        )


问:
How to catch the Laravel response after terminating the kernel?
I want to catch the response of a Laravel application after termination to check if it has the status code 404.
In that case, I want to bootstrap another framework with the same request.

Because I try to bootstrap another framework I really want to make sure that Laravel is completely terminated.

How can I do that?

答:
In your public/index.php file you will see $response->send() code. You can wrap it in one if statement like this:

```<code>
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

if($response->getStatusCode() !== 404) {
    $response->send();
    $kernel->terminate($request, $response);
} else {
    // Boot Your Another framework here
}
</code>```

I wrote entire index.php file here.

Hope this helps you

Body:
In your public/index.php file you will see $response->send() code. You can wrap it in one if statement like this:

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

if($response->getStatusCode() !== 404) {
    $response->send();
    $kernel->terminate($request, $response);
} else {
    // Boot Your Another framework here
}

I wrote entire index.php file here.

Hope this helps you


问:
How to ignore case in String.replace
```<code>string sentence = "We know it contains 'camel' word.";
// Camel can be in different cases:
string s1 = "CAMEL";
string s2 = "CaMEL";
string s3 = "CAMeL";
// ...
string s4 = "Camel";
// ...
string s5 = "camel";
</code>```

How to replace 'camel' in sentence with 'horse' despite of string.Replace doesn't support ignoreCase on left string?

答:
You could also use String.IndexOf

http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx

You may get slightly better performance doing it this way than with RegExpressions (I abhor them because they're not intuitive and easy to screw up, although this simple .Net function call abstracts the actual messy RegEx, and doesn't provide much room for error), but that's probably not a concern for you; computers are REALLY fast these days, right? :)  The overload for IndexOf that takes a StringComparison object allows you to optionally ignore case, and because IndexOf returns the first occurrence from at a specified position, you'll have to code a loop to process a string having multiple occurrences.

Title: How to ignore case in String.replace

Body:
string sentence = "We know it contains 'camel' word.";
// Camel can be in different cases:
string s1 = "CAMEL";
string s2 = "CaMEL";
string s3 = "CAMeL";
// ...
string s4 = "Camel";
// ...
string s5 = "camel";

How to replace 'camel' in sentence with 'horse' despite of string.Replace doesn't support ignoreCase on left string?


问:
How to bind ProgressBar visibility with ImageView using databinding
Can any one tell me how to bind progressbar visibility with imageview using databinding when image upload so hide progress bar </p>

答:
If you change progressbar visibility using databinding, then you can change imageview visibility using same logic, but inverted.
Code snipped of layout may help to offer concrete solution</p>


问:
Save with "Retry as Sudo" using keyboard commands
Anytime I try to save a file (using Ctrl+S) that requires elevated permissions, I get the popup with the button to "Retry as Sudo". This is fine, but there does not seem to be any way to select "Retry as Sudo" using the keyboard. I have to use the mouse to actually click the "Retry as Sudo" button. I have tried tabbing, but cannot seem to select this button without using the mouse. Does anyone know if there is anyway to save a file as sudo without using the mouse?</p>

答:
From https://github.com/microsoft/vscode/issues/90661#issuecomment-586422989:

Create keyboard shortcut for command notifications.focusToasts

When the Retry as Sudo toaster appears you can now:

Press the assigned shortcut

Press Tab

Press Enter


问:
How can I access views from layout containing merge tag is included in another layout?
I use Android Studio 3.6-RC1 and build tools version 3.6.0-rc01 and encountered an issue with ViewBinding feature:

I have activity_test.xml file with the following markup:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/view_merged"
        layout="@layout/merge_view" />
</LinearLayout>
</code>```

And merge_view.xml with following markup:

```<code><merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Merge view" />
</merge>
</code>```

Activity code looks like the following:

```<code>class TestActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityTestBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.viewMerged.label.text = "New text"

    }
}
</code>```

Problem is when I try to access TextView from merged layout, the app throws an exception with the message java.lang.NullPointerException: Missing required view with ID: viewMerged.

The generated binding class looks like the following:

```<code>public final class ActivityTestBinding implements ViewBinding {
  @NonNull
  private final LinearLayout rootView;

  @NonNull
  public final MergeViewBinding viewMerged;

  private ActivityTestBinding(@NonNull LinearLayout rootView,
      @NonNull MergeViewBinding viewMerged) {
    this.rootView = rootView;
    this.viewMerged = viewMerged;
  }

  @Override
  @NonNull
  public LinearLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityTestBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityTestBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_test, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityTestBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    String missingId;
    missingId: {
      View viewMerged = rootView.findViewById(R.id.view_merged);
      if (viewMerged == null) {
        missingId = "viewMerged";
        break missingId;
      }
      MergeViewBinding viewMergedBinding = MergeViewBinding.bind(viewMerged);
      return new ActivityTestBinding((LinearLayout) rootView, viewMergedBinding);
    }
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}
</code>```

Am I missing something or there is no way to access views from included layouts with  tags or it is not yet shipped in Android Studio 3.6-RC1?

答:
I wrote an article about using ViewBinding with <merge> tag which you can find here

Basically, what you need to do is

Don't give <include> tag any ID.

Call bind() method of generated merge layout binding, passing the root view of the layout you included your layout in.

Access your view from the object of merge binding

For example, you have merge_view.xml so you'll have MergeViewBinding class generated and this is how you will access the view from this layout.

```<code>class TestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityTestBinding.inflate(layoutInflater)
        val mergeBinding = MergeViewBinding.bind(binding.root)
        setContentView(binding.root)
        mergeBinding.label.text = "New text"
    }
}
</code>```

Body:
I use Android Studio 3.6-RC1 and build tools version 3.6.0-rc01 and encountered an issue with ViewBinding feature:

I have activity_test.xml file with the following markup:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/view_merged"
        layout="@layout/merge_view" />
</LinearLayout>

And merge_view.xml with following markup:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Merge view" />
</merge>

Activity code looks like the following:

class TestActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityTestBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.viewMerged.label.text = "New text"

    }
}

Problem is when I try to access TextView from merged layout, the app throws an exception with the message java.lang.NullPointerException: Missing required view with ID: viewMerged.

The generated binding class looks like the following:

public final class ActivityTestBinding implements ViewBinding {
  @NonNull
  private final LinearLayout rootView;

  @NonNull
  public final MergeViewBinding viewMerged;

  private ActivityTestBinding(@NonNull LinearLayout rootView,
      @NonNull MergeViewBinding viewMerged) {
    this.rootView = rootView;
    this.viewMerged = viewMerged;
  }

  @Override
  @NonNull
  public LinearLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityTestBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityTestBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_test, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityTestBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    String missingId;
    missingId: {
      View viewMerged = rootView.findViewById(R.id.view_merged);
      if (viewMerged == null) {
        missingId = "viewMerged";
        break missingId;
      }
      MergeViewBinding viewMergedBinding = MergeViewBinding.bind(viewMerged);
      return new ActivityTestBinding((LinearLayout) rootView, viewMergedBinding);
    }
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}

Am I missing something or there is no way to access views from included layouts with  tags or it is not yet shipped in Android Studio 3.6-RC1?

Body:
I wrote an article about using ViewBinding with <merge> tag which you can find here

Basically, what you need to do is

Don't give <include> tag any ID.

Call bind() method of generated merge layout binding, passing the root view of the layout you included your layout in.

Access your view from the object of merge binding

For example, you have merge_view.xml so you'll have MergeViewBinding class generated and this is how you will access the view from this layout.

class TestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityTestBinding.inflate(layoutInflater)
        val mergeBinding = MergeViewBinding.bind(binding.root)
        setContentView(binding.root)
        mergeBinding.label.text = "New text"
    }
}


问:
how to convert Final_Unique column into a header values in pandas
sample image to check the data

SAMPLE DATA

```<code>Actual_Data     Final_Unique
8,8,8,8,8,8,        8,8
6,7,7,7,6,7,        6,7
2,12,3,4,12,12,     7,7
14,14,14,14,14,14,  7,6
1,1,12,2,2,4,       2,12
6,8,8,8,8,12,       12,3
6,6,6,6,3,14,       3,4
1,14,14,1,1,2,      4,12
1,1,1,1,1,14,       12,12
</code>```

i am trying this

newdf = a.pivot(index='Actual_Data', columns='Final_Unique')

i have 2 column actual data and final_unique column in actual i have 44000 rows and final_unique has 266 rows i want to get the 266 column and actual data to stay same as it and count how many time actual data appears in the header

error getting

duplicate data exist can't reshape

output expected

```<code>ACTUAL DATA          8,8  6,7  7,7   7,6  2,12

8,8,8,8,8,8,          3   0    0      0    0

6,7,7,7,6,7,          0    2    1     1    0

2,12,3,4,12,12,       0    0    0     0    1
</code>```

答:
pivot_table allows an aggregate function, so if you only add on column containing 1 to you dataframe, you could get the expected result:

```<code>newdf = a.assign(val=1).pivot_table(values='val', index='Actual_Data',
                                    columns='Final_Unique', aggfunc=sum, fill_value=0
                                    ).reset_index().rename_axis(None, axis=1)
</code>```

With the sample data it gives:

```<code>          Actual_Data  12,12  12,3  2,12  3,4  4,12  6,7  7,6  7,7  8,8
0       1,1,1,1,1,14,      1     0     0    0     0    0    0    0    0
1       1,1,12,2,2,4,      0     0     1    0     0    0    0    0    0
2      1,14,14,1,1,2,      0     0     0    0     1    0    0    0    0
3  14,14,14,14,14,14,      0     0     0    0     0    0    1    0    0
4     2,12,3,4,12,12,      0     0     0    0     0    0    0    1    0
5       6,6,6,6,3,14,      0     0     0    1     0    0    0    0    0
6        6,7,7,7,6,7,      0     0     0    0     0    1    0    0    0
7       6,8,8,8,8,12,      0     1     0    0     0    0    0    0    0
8        8,8,8,8,8,8,      0     0     0    0     0    0    0    0    1
</code>```

From you comments, the two columns of the original a dataframe are not directly related but are in fact two independant Series, and you just want to know how many times a Final_Unique value occurs in a Actual_Data one.

This code should give it:

```<code>newdf = a[['Actual_Data']]
for col in set(a['Final_Unique'].dropna()):
    newdf[col] = newdf.Actual_Data.str.findall('(^|,)'+col+'(?=,)').apply(len)
</code>```

The result is:

```<code>          Actual_Data  8,8  12,3  12,12  7,7  2,12  6,7  4,12  3,4  7,6
0        8,8,8,8,8,8,    3     0      0    0     0    0     0    0    0
1        6,7,7,7,6,7,    0     0      0    1     0    2     0    0    1
2     2,12,3,4,12,12,    0     1      1    0     2    0     1    1    0
3  14,14,14,14,14,14,    0     0      0    0     0    0     0    0    0
4       1,1,12,2,2,4,    0     0      0    0     0    0     0    0    0
5       6,8,8,8,8,12,    2     0      0    0     0    0     0    0    0
6       6,6,6,6,3,14,    0     0      0    0     0    0     0    0    0
7      1,14,14,1,1,2,    0     0      0    0     0    0     0    0    0
8       1,1,1,1,1,14,    0     0      0    0     0    0     0    0    0
</code>```

The rationale behind the above code is:

compute the list of columns from the Final_Unique columns: the set will automatically remove duplicates (but will break order) and dropna() will remove empty values

create a new dataframe from the Actual_Data column.

add columns to that dataframe from the list computed at previous step and for each column

use str.findall and an appropriate regex to find non overlapping sequence containing the column name after a comma or at beginning of string and followed  by a comma - that last comma not being included in the matched string to allow consecutive sequences to be correctly counted, hence the (?=...)

apply the len function to tranform that list in a simple count

Body:
sample image to check the data

SAMPLE DATA

Actual_Data     Final_Unique
8,8,8,8,8,8,        8,8
6,7,7,7,6,7,        6,7
2,12,3,4,12,12,     7,7
14,14,14,14,14,14,  7,6
1,1,12,2,2,4,       2,12
6,8,8,8,8,12,       12,3
6,6,6,6,3,14,       3,4
1,14,14,1,1,2,      4,12
1,1,1,1,1,14,       12,12

i am trying this

newdf = a.pivot(index='Actual_Data', columns='Final_Unique')

i have 2 column actual data and final_unique column in actual i have 44000 rows and final_unique has 266 rows i want to get the 266 column and actual data to stay same as it and count how many time actual data appears in the header

error getting

duplicate data exist can't reshape

output expected

ACTUAL DATA          8,8  6,7  7,7   7,6  2,12

8,8,8,8,8,8,          3   0    0      0    0

6,7,7,7,6,7,          0    2    1     1    0

2,12,3,4,12,12,       0    0    0     0    1

Body:
pivot_table allows an aggregate function, so if you only add on column containing 1 to you dataframe, you could get the expected result:

newdf = a.assign(val=1).pivot_table(values='val', index='Actual_Data',
                                    columns='Final_Unique', aggfunc=sum, fill_value=0
                                    ).reset_index().rename_axis(None, axis=1)

With the sample data it gives:

          Actual_Data  12,12  12,3  2,12  3,4  4,12  6,7  7,6  7,7  8,8
0       1,1,1,1,1,14,      1     0     0    0     0    0    0    0    0
1       1,1,12,2,2,4,      0     0     1    0     0    0    0    0    0
2      1,14,14,1,1,2,      0     0     0    0     1    0    0    0    0
3  14,14,14,14,14,14,      0     0     0    0     0    0    1    0    0
4     2,12,3,4,12,12,      0     0     0    0     0    0    0    1    0
5       6,6,6,6,3,14,      0     0     0    1     0    0    0    0    0
6        6,7,7,7,6,7,      0     0     0    0     0    1    0    0    0
7       6,8,8,8,8,12,      0     1     0    0     0    0    0    0    0
8        8,8,8,8,8,8,      0     0     0    0     0    0    0    0    1

From you comments, the two columns of the original a dataframe are not directly related but are in fact two independant Series, and you just want to know how many times a Final_Unique value occurs in a Actual_Data one.

This code should give it:

newdf = a[['Actual_Data']]
for col in set(a['Final_Unique'].dropna()):
    newdf[col] = newdf.Actual_Data.str.findall('(^|,)'+col+'(?=,)').apply(len)

The result is:

          Actual_Data  8,8  12,3  12,12  7,7  2,12  6,7  4,12  3,4  7,6
0        8,8,8,8,8,8,    3     0      0    0     0    0     0    0    0
1        6,7,7,7,6,7,    0     0      0    1     0    2     0    0    1
2     2,12,3,4,12,12,    0     1      1    0     2    0     1    1    0
3  14,14,14,14,14,14,    0     0      0    0     0    0     0    0    0
4       1,1,12,2,2,4,    0     0      0    0     0    0     0    0    0
5       6,8,8,8,8,12,    2     0      0    0     0    0     0    0    0
6       6,6,6,6,3,14,    0     0      0    0     0    0     0    0    0
7      1,14,14,1,1,2,    0     0      0    0     0    0     0    0    0
8       1,1,1,1,1,14,    0     0      0    0     0    0     0    0    0

The rationale behind the above code is:

compute the list of columns from the Final_Unique columns: the set will automatically remove duplicates (but will break order) and dropna() will remove empty values

create a new dataframe from the Actual_Data column.

add columns to that dataframe from the list computed at previous step and for each column

use str.findall and an appropriate regex to find non overlapping sequence containing the column name after a comma or at beginning of string and followed  by a comma - that last comma not being included in the matched string to allow consecutive sequences to be correctly counted, hence the (?=...)

apply the len function to tranform that list in a simple count


问:
Text selection depending on the phone
In my app, I have an EditText where the user can select a part of the text. The problem is that the selection behavior is different depending on the phone : with one, the user can select normally, but with another one the user must tap on the text indicator and then tap on "Select All".

How can I set the behavior like the first one as default ? And why the behavior is different between phones ?

Thank you for your answers, have a nice day !

EDIT :

Now I select the word which contains the cursor with this method :

```<code>fun EditText.selectCurrentWord() {
    val textSpan = text
    val selection = selectionStart
    val pattern = Pattern.compile("\\w+")
    val matcher = pattern.matcher(textSpan)
    var start: Int
    var end: Int

    while (matcher.find()) {
        start = matcher.start()
        end = matcher.end()

        if (selection in start..end) {
            setSelection(start, end)
            break
        }
    }
}
</code>```

But now the problem is that cursors at the start and end of selection doesn't appear...

The EditText is selectable and isCursorVisible is set to true.

答:
You can try using a Button to select the text using

```<code>EditText myET = findViewById(R.id.myET);
Button selectBtn = findViewById(R.id.selectBtn);

selectBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myET.setSelectAllOnFocus(true);
        myET.selectAll();
    }
});

</code>```

You can open context menu using

```<code>openContextMenu(myET);
</code>```

You can also get the position of starting and end point of cursor

```<code>myET.getSelectionStart();
myET.getSelectionEnd();
</code>```

Referring answers

Getting cursor position

Select Text programmatically

Update 1

Add this in your button click, this seems to work, but sometimes you have to click 2 times you can tweak this

```<code>myET.performLongClick();
myET.setSelection(0, myET.length());
</code>```

Hope this will help!

Title: Text selection depending on the phone

Body:
In my app, I have an EditText where the user can select a part of the text. The problem is that the selection behavior is different depending on the phone : with one, the user can select normally, but with another one the user must tap on the text indicator and then tap on "Select All".

How can I set the behavior like the first one as default ? And why the behavior is different between phones ?

Thank you for your answers, have a nice day !

EDIT :

Now I select the word which contains the cursor with this method :

fun EditText.selectCurrentWord() {
    val textSpan = text
    val selection = selectionStart
    val pattern = Pattern.compile("\\w+")
    val matcher = pattern.matcher(textSpan)
    var start: Int
    var end: Int

    while (matcher.find()) {
        start = matcher.start()
        end = matcher.end()

        if (selection in start..end) {
            setSelection(start, end)
            break
        }
    }
}

But now the problem is that cursors at the start and end of selection doesn't appear...

The EditText is selectable and isCursorVisible is set to true.

Body:
You can try using a Button to select the text using

EditText myET = findViewById(R.id.myET);
Button selectBtn = findViewById(R.id.selectBtn);

selectBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myET.setSelectAllOnFocus(true);
        myET.selectAll();
    }
});

You can open context menu using

openContextMenu(myET);

You can also get the position of starting and end point of cursor

myET.getSelectionStart();
myET.getSelectionEnd();

Referring answers

Getting cursor position

Select Text programmatically

Update 1

Add this in your button click, this seems to work, but sometimes you have to click 2 times you can tweak this

myET.performLongClick();
myET.setSelection(0, myET.length());

Hope this will help!


问:
jquery selector problem
I'm using this code:

```<code>$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})
</code>```

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

```<code><fieldset>
        <input checked="checked" />
        <label></label>
        <div class="toggle_box">
            <div class="switch" state="on"></div>
        </div>
    </fieldset>
    <fieldset>
        <input/>
        <label></label>
        <div class="toggle_box">
            <div class="switch"></div>
        </div>
    </fieldset>
</code>```

答:
The statement in the if statement is setting your checkboxes to checked. Particularly, this statement: $(this).attr('checked','checked').

Instead you can do if($(this).prop('checked'))

Read more about the jQuery Prop method.

Alternatively, you can do, this.checked which will access the DOM directly or with jQuery, $(this).is(':checked').

Title: jquery selector problem

Body:
I'm using this code:

$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

<fieldset>
        <input checked="checked" />

    </fieldset>
    <fieldset>
        <input/>

    </fieldset>


问:
How to refresh/update a variable in Makefile?
I have this Makefile:

```<code>CFLAGS = -ffreestanding -O2 -nostdlib -lgcc
BUILD_DIR = ../build
BIN = $(BUILD_DIR)/os.bin
LINKER_SCRIPT = linker.ld
OBJ_FILES := $(shell find $(BUILD_DIR) -iname '*.o')

.PHONY: all

all:
    @make -C boot
    @make -C kernel
    $(CC) -T $(LINKER_SCRIPT) -o $(BIN) $(CFLAGS) $(OBJ_FILES)

</code>```

After compiling (doing make in boot and kernel directories) there should be files with .o extension, however OBJ_FILES is empty. Only after calling make again OBJ_FILES contains the .o files paths which are needed to link. So my question is how do I update OBJ_FILES after compiling in the boot and kernel directories, because OBJ_FILES doesn't update/refresh.

答:
So my question is how do I update OBJ_FILES after compiling in the boot and kernel directories, because OBJ_FILES doesn't update/refresh.

OBJ_FILES variable won't change its value once make started executing the rules.

See 3.7 How make Reads a Makefile for full details:

GNU make does its work in two distinct phases. During the first phase it reads all the makefiles, included makefiles, etc. and internalizes all the variables and their values and implicit and explicit rules, and builds a dependency graph of all the targets and their prerequisites. During the second phase, make uses this internalized data to determine which targets need to be updated and run the recipes necessary to update them.

It’s important to understand this two-phase approach because it has a direct impact on how variable and function expansion happens; this is often a source of some confusion when writing makefiles.

What you can do instead is restart make once it built kernel and boot:

```<code>all: $(BIN)

$(BIN) : $(OBJ_FILES)
    $(CC) -T $(LINKER_SCRIPT) -o $@ $(CFLAGS) $(OBJ_FILES)

Makefile :
    @$(MAKE) -C boot
    @$(MAKE) -C kernel
    touch $@ # <---- Causes the Makefile to be re-read.

.PHONY: all
</code>```

Body:
I have this Makefile:

CFLAGS = -ffreestanding -O2 -nostdlib -lgcc
BUILD_DIR = ../build
BIN = $(BUILD_DIR)/os.bin
LINKER_SCRIPT = linker.ld
OBJ_FILES := $(shell find $(BUILD_DIR) -iname '*.o')

.PHONY: all

all:
    @make -C boot
    @make -C kernel
    $(CC) -T $(LINKER_SCRIPT) -o $(BIN) $(CFLAGS) $(OBJ_FILES)

After compiling (doing make in boot and kernel directories) there should be files with .o extension, however OBJ_FILES is empty. Only after calling make again OBJ_FILES contains the .o files paths which are needed to link. So my question is how do I update OBJ_FILES after compiling in the boot and kernel directories, because OBJ_FILES doesn't update/refresh.

Body:
So my question is how do I update OBJ_FILES after compiling in the boot and kernel directories, because OBJ_FILES doesn't update/refresh.

OBJ_FILES variable won't change its value once make started executing the rules.

See 3.7 How make Reads a Makefile for full details:

GNU make does its work in two distinct phases. During the first phase it reads all the makefiles, included makefiles, etc. and internalizes all the variables and their values and implicit and explicit rules, and builds a dependency graph of all the targets and their prerequisites. During the second phase, make uses this internalized data to determine which targets need to be updated and run the recipes necessary to update them.

It’s important to understand this two-phase approach because it has a direct impact on how variable and function expansion happens; this is often a source of some confusion when writing makefiles.

What you can do instead is restart make once it built kernel and boot:

all: $(BIN)

$(BIN) : $(OBJ_FILES)
    $(CC) -T $(LINKER_SCRIPT) -o $@ $(CFLAGS) $(OBJ_FILES)

Makefile :
    @$(MAKE) -C boot
    @$(MAKE) -C kernel
    touch $@ # <---- Causes the Makefile to be re-read.

.PHONY: all


问:
Cassandra: Are SS table created for replicated data
Suppose we have 3 node cluster in Cassandra and replication factor is 2.

During the compaction process, the replicated data of some other primary node also get compacted during the node compaction process.

For example, If node 1 is range partitioned for 1-10 and node 2 and node 3 are replicas for node 1. When we initiate the compaction process on node 2, will the SS table of node 2 have replicated the replication data of node 1?

TIA

答:
The data replication happens either in real-time, when you write data, or via hints, if node was offline, or via explicit repair operation (although repair is the special type of compaction).

Compaction process is independent on every node - there are different factors that could lead to flushes happening on different times, different size of the data, etc.  Compaction of data on one node won't send data to other nodes, until it's a validation compaction triggered via repair.

I recommend to read DSE Architecture guide, that explains how data is replicated, etc.

P.S. in your example, if you have RF=2, then only one node will be the replica for Node1...


答:
```<code>$('fieldset input[type=checkbox]').each(function ()  {if($(this).attr('checked') == 'checked')){
var switches = $(this).parent().find('.switch');
$(switches).attr('state','on')
$(switches).css({'left':"52px"});
$(switches).parent().css({'background-position': "147px -37px"});
}})
</code>```

Title: jquery selector problem


问:
unable to get jsonEncode in magento2
Magento has its own json encode and decode functions:

```<code>Mage::helper('core')->jsonEncode($array);
</code>```

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?

答:
```<code> use Magento\Framework\Json\Helper\Data;

 protected $jsonHelper;

 public function __construct(
          Data $jsonHelper
        ) {

         $this->jsonHelper = $jsonHelper;

        }

 protected function jsonResponse()
    {
     $this->jsonHelper->jsonEncode($array);
    }
</code>```

Title: unable to get jsonEncode in magento2

Body:
Magento has its own json encode and decode functions:

Mage::helper('core')->jsonEncode($array);

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?


问:
Sagemaker LDA topic model - how to access the params of the trained model? Also is there a simple way to capture coherence
I'm new to Sagemaker and am running some tests to measure the performance of NTM and LDA on AWS compared with LDA mallet and native Gensim LDA model.

I'm wanting to inspect the trained models on Sagemaker and look at stuff like what words have the highest contribution for each topic. And also to get a measure of model coherence.

I have been able to successfully get what words have the highest contribution for each topic for NTM on Sagemaker by downloading the output file untarring it and unzipping to expose 3 files params, symbol.json and meta.json.

However, when I try to do the same process for LDA, the untarred output file cannot be unzipped.

Maybe I'm missing something or should do something different for LDA compared with NTM but I have not been able to find any documentation on this. Also, anyone found a simple way to calculate model coherence?

Any assistance would be greatly appreciated!

答:
Regarding coherence, there's no default implementation in sagemaker AFAIK.

You can implement you own metric like this:

```<code>from itertools import combinations
from sklearn.metrics.pairwise import cosine_similarity

def calculate_coherence(topic_vectors):
    similarity_sum = 0.0
    num_combinations = 0
    for pair in combinations(topic_vectors, 2):
        similarity = cosine_similarity([pair[0]], [pair[1]])
        similarity_sum = similarity_sum + similarity
        num_combinations = num_combinations + 1
    return float(similarity_sum / num_combinations)
</code>```

and get the coherence for your real model like:

```<code>print(calculate_coherence(beta.asnumpy()))
</code>```

Some intuitive tests for coherence as follows:

```<code>predictions = [[0.0, 0.0, 0.0],
               [0.0, 1.0, 0.0],
               [0.0, 0.0, 1.0],
               [1.0, 0.0, 0.0]]

assert calculate_coherence(predictions) == 0.0, "Expected incoherent"

predictions = [[0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0]]

assert calculate_coherence(predictions) == 1.0, "Expected coherent"

predictions = [[0.0, 0.0, 1.0],
               [0.0, 0.0, 1.0],
               [1.0, 0.0, 0.0],
               [1.0, 0.0, 0.0],
               [0.0, 1.0, 0.0],
               [0.0, 1.0, 0.0]]
assert calculate_coherence(predictions) == 0.2, "Expected partially coherent"
</code>```

Futher reading:

http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf

Body:
Regarding coherence, there's no default implementation in sagemaker AFAIK.

You can implement you own metric like this:

from itertools import combinations
from sklearn.metrics.pairwise import cosine_similarity

def calculate_coherence(topic_vectors):
    similarity_sum = 0.0
    num_combinations = 0
    for pair in combinations(topic_vectors, 2):
        similarity = cosine_similarity([pair[0]], [pair[1]])
        similarity_sum = similarity_sum + similarity
        num_combinations = num_combinations + 1
    return float(similarity_sum / num_combinations)

and get the coherence for your real model like:

print(calculate_coherence(beta.asnumpy()))

Some intuitive tests for coherence as follows:

predictions = [[0.0, 0.0, 0.0],
               [0.0, 1.0, 0.0],
               [0.0, 0.0, 1.0],
               [1.0, 0.0, 0.0]]

assert calculate_coherence(predictions) == 0.0, "Expected incoherent"

predictions = [[0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0]]

assert calculate_coherence(predictions) == 1.0, "Expected coherent"

predictions = [[0.0, 0.0, 1.0],
               [0.0, 0.0, 1.0],
               [1.0, 0.0, 0.0],
               [1.0, 0.0, 0.0],
               [0.0, 1.0, 0.0],
               [0.0, 1.0, 0.0]]
assert calculate_coherence(predictions) == 0.2, "Expected partially coherent"

Futher reading:

http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf