问:
How assign the name of a check box to a cell in Excel
I have created a check box in excel and I would like that when I click on the check box name be assigned to a cell in another sheet.

how can i do that?

Here is what I tried but I get an error 424

```<code>Private Sub checkbox1_click()
Worksheets("Produits").Range("A1") = checkbox1.Caption
End Sub
</code>```

Ps: I use Office2019

答:
For the sake of simplicity I will assume that your checkbox is located in a worksheet named Test . I will also assume that when the checkbox is unchecked the corresponding cell should be emptied.

For an ActiveX type of checkbox, named CheckBox1, your code should be located in the same worksheet as the checkbox and should look like so:

```<code>Option Explicit
Sub CheckBox1_Click()

Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets("Produits")
If CheckBox1.Value Then
    sht.Range("A1") = CheckBox1.Caption
Else
    sht.Range("A1").ClearContents
End If
End Sub
</code>```

For a Form Control type of checkbox, named Check Box 2, your code should be located in a module and should look like so:

```<code>Option Explicit

Sub CheckBox2_Click()
Dim cb As CheckBox
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Set sht1 = ThisWorkbook.Worksheets("Test")
Set sht2 = ThisWorkbook.Worksheets("Produits")

Set cb = sht1.CheckBoxes("Check Box 2") 'whatever the name of your checkbox is...

If cb.Value = 1 Then
    sht2.Range("A2") = cb.Caption
Else
    sht2.Range("A2").ClearContents
End If
End Sub
</code>```

Body:
I have created a check box in excel and I would like that when I click on the check box name be assigned to a cell in another sheet.

how can i do that?

Here is what I tried but I get an error 424

Private Sub checkbox1_click()
Worksheets("Produits").Range("A1") = checkbox1.Caption
End Sub

Ps: I use Office2019

Body:
For the sake of simplicity I will assume that your checkbox is located in a worksheet named Test . I will also assume that when the checkbox is unchecked the corresponding cell should be emptied.

For an ActiveX type of checkbox, named CheckBox1, your code should be located in the same worksheet as the checkbox and should look like so:

Option Explicit
Sub CheckBox1_Click()

Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets("Produits")
If CheckBox1.Value Then
    sht.Range("A1") = CheckBox1.Caption
Else
    sht.Range("A1").ClearContents
End If
End Sub

For a Form Control type of checkbox, named Check Box 2, your code should be located in a module and should look like so:

Option Explicit

Sub CheckBox2_Click()
Dim cb As CheckBox
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Set sht1 = ThisWorkbook.Worksheets("Test")
Set sht2 = ThisWorkbook.Worksheets("Produits")

Set cb = sht1.CheckBoxes("Check Box 2") 'whatever the name of your checkbox is...

If cb.Value = 1 Then
    sht2.Range("A2") = cb.Caption
Else
    sht2.Range("A2").ClearContents
End If
End Sub


来源: stackexchange

问:
I want to add active class to menu and submenu by using PHP. I have added it ib submenu but on main menu I am having problems
```<code><li class="nav-item  <?php if($page=='userforms'){echo 'active';}?>

    <a href="javascript:;" class="nav-link nav-toggle" style="">
        <i class="icon-layers"></i>
        <span class="title">Userforms</span>
        <span class="arrow open"></span>
    </a>

    <ul class="sub-menu" style="display: block;">
        <li class="nav-item <?php if($page=='newproduct'){echo 'active';}?>">
            <a href="add.php" class="nav-link ">
                <span class="title">New Product</span>
            </a>
        </li>

        <li class="nav-item  <?php if($page=='stockin'){echo 'active';}?>">
            <a href="StockIn.php" class="nav-link ">
                <span class="title">Stock In</span>
            </a>
        </li>

        <li class="nav-item  <?php if($page=='stockout'){echo 'active';}?>">
            <a href="StockOut.php" class="nav-link ">
                <span class="title">Stock Out</span>
            </a>
        </li>

    </ul>

</li>

<?php $page = 'stockin'; include('includes/header.php');
include('includes/navbar.php');
?>
</code>```

I want to add active class to menu and submenu by using PHP. I have added it ib submenu but on main menu I am having problems. I want both menu to be selected Main menu and Sub Menu.

I want both menu to be selected

答:
Replace

```<code><li class="nav-item  <?php if($page=='userforms'){echo 'active';}?>
</code>```

With

```<code><li class="nav-item <?php if ($page == 'userforms' || $page == 'stockin' || $page == 'newproduct' || $page == 'stockout') echo 'active'; ?>">
</code>```

Then, both menu link will be active and also you had a typo mistake in
 tag

ContentLicense: CC BY-SA 4.0

Body:
<li class="nav-item  <?php if($page=='userforms'){echo 'active';}?>

        Userforms

        <li class="nav-item <?php if($page=='newproduct'){echo 'active';}?>">

                New Product

        <li class="nav-item  <?php if($page=='stockin'){echo 'active';}?>">

                Stock In

        <li class="nav-item  <?php if($page=='stockout'){echo 'active';}?>">

                Stock Out

<?php $page = 'stockin'; include('includes/header.php');
include('includes/navbar.php');
?>

I want to add active class to menu and submenu by using PHP. I have added it ib submenu but on main menu I am having problems. I want both menu to be selected Main menu and Sub Menu.

I want both menu to be selected

Body:
Replace

<li class="nav-item  <?php if($page=='userforms'){echo 'active';}?>

With

<li class="nav-item <?php if ($page == 'userforms' || $page == 'stockin' || $page == 'newproduct' || $page == 'stockout') echo 'active'; ?>">

Then, both menu link will be active and also you had a typo mistake in <li> tag


问:
How to update the rows of a table using dialog box
I have been going through the below Plunker,

plunker link here

Here If I try to edit , the new record is added above instead of updating the current ,

How can I update the current edited row for the same example instead adding a new one?

I have tried deleting the row and update the new in the deleted place , but this idea is not correct tmk

Any guiding links or any help is much appreciated ....TIA

答:
From your code I understand you want to update the model (variable aData). It would be a better idea to use data binding but if you want to edit it you can use:

```<code>aData.map(function(item) {
if (item.ID==id){
    item.Name = name;
    item.Age = age;
    item.Salary = sal;
}
return item; });
</code>```

This is probably not the efficient way to do it and it consider you have unique ids.
Also don't use the function unshift() because it add new value (doesn't update the existent).The record is added above because you actually add a new element (see link).

Body:
From your code I understand you want to update the model (variable aData). It would be a better idea to use data binding but if you want to edit it you can use:

aData.map(function(item) {
if (item.ID==id){
    item.Name = name;
    item.Age = age;
    item.Salary = sal;
}
return item; });

This is probably not the efficient way to do it and it consider you have unique ids.
Also don't use the function unshift() because it add new value (doesn't update the existent).The record is added above because you actually add a new element (see link).


问:
Laravel storage disk put gives internal server error 500 on live server | no logs are created
I am saving image files to disk. After that I create a ZIP and download it. Everything works fine on localhost.

On the live server I get:

```<code>Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at webmaster@example.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.
</code>```

The error occurs if I want to save an image to the storage:

```<code>$user = DB::connection('mysql_live')->table('users')->where('id', $userid)->first();
Storage::disk('gdpr')->put($user->picture, file_get_contents(env('AVATAR_PHOTO_SRC') . $user->picture));
</code>```

env('AVATAR_PHOTO_SRC') is the absoulte path to the image, example: https://example.com/uploads/thumb/

There is no log file created. And the size of the zip is less then 1MB, images are even smaller.

What is happening here?

EDIT

$user->picture is the name of the file. example: example.jpg.

The file does exist and can be opened for example in the browser. Remember everything works fine on localhost.

EDIT

I found a log in try, catch:

```<code>file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0
</code>```

EDIT

PHP ini cant be modified on a shared server. I will need an alternative way to store the image.

答:
From PHP : www.php.net/manual/en/filesystem.configuration.php

allow_url_fopen boolean

This option enables the URL-aware fopen wrappers that enable accessing
  URL object like files. Default wrappers are provided for the access of
  remote files using the ftp or http protocol, some extensions like zlib
  may register additional wrappers.

So you may need to enable allow_url_fopen=1 in your php.ini to enable ftp or http protocol.

Body:
I am saving image files to disk. After that I create a ZIP and download it. Everything works fine on localhost.

On the live server I get:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at webmaster@example.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

The error occurs if I want to save an image to the storage:

$user = DB::connection('mysql_live')->table('users')->where('id', $userid)->first();
Storage::disk('gdpr')->put($user->picture, file_get_contents(env('AVATAR_PHOTO_SRC') . $user->picture));

env('AVATAR_PHOTO_SRC') is the absoulte path to the image, example: https://example.com/uploads/thumb/

There is no log file created. And the size of the zip is less then 1MB, images are even smaller.

What is happening here?

EDIT

$user->picture is the name of the file. example: example.jpg.

The file does exist and can be opened for example in the browser. Remember everything works fine on localhost.

EDIT

I found a log in try, catch:

file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0

EDIT

PHP ini cant be modified on a shared server. I will need an alternative way to store the image.


问:
Why is it recommended to use a cloud builder for yarn?
Looking at the source code for the yarn builder for Google Cloud Build I was wondering why it is recommended to use the builder rather than specifying the entrypoint.

https://github.com/GoogleCloudPlatform/cloud-builders/tree/master/yarn

Basically

```<code>steps
  - name: 'gcr.io/cloud-builders/yarn'
    args:
      - install
</code>```

vs

```<code>steps:
  - name: node:10
    entrypoint: yarn
    args:
      - install
</code>```

Is it because the cloud builder is registered with the Google Cloud Container Registry which is faster to read from within Google Cloud build?

答:
Yes, you are corrected. Indeed, it's recommended because the read from the Container Registry will be faster to be done, using the builder.

As per the code indicates, you referencing directly the Container from yarn, which will make the access faster than using an entrypoint.

Let me know if the information helped you!

Body:
Looking at the source code for the yarn builder for Google Cloud Build I was wondering why it is recommended to use the builder rather than specifying the entrypoint.

https://github.com/GoogleCloudPlatform/cloud-builders/tree/master/yarn

Basically

steps
  - name: 'gcr.io/cloud-builders/yarn'
    args:
      - install

vs

steps:
  - name: node:10
    entrypoint: yarn
    args:
      - install

Is it because the cloud builder is registered with the Google Cloud Container Registry which is faster to read from within Google Cloud build?


问:
Unit Testing for the Controllor SpringBoot Java
Need to do Unit Testing for the Controller part of the project but have got the error. Believe ModelAndVIew part cause the issue, even though I have mocked it and returned ModelAndView as it is return type of method. However, it does not work. Do not have any issue with Pom.xml, therefore, did not add it.
    ProjectController:

```<code>package com.bsptech.itcommunity.controller;

import com.bsptech.itcommunity.entity.Itproject;
import com.bsptech.itcommunity.service.inter.EmployeeProfileServiceInter;
import com.bsptech.itcommunity.service.inter.ItProjectServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(value = "/projects")
public class ProjectController {

    @Autowired
    private ItProjectServiceInter itProjectServiceInter;

    @Autowired
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @RequestMapping(method = RequestMethod.GET, path = "/{projectId}")
    public ModelAndView detail(@PathVariable("projectId") Integer projectId, ModelAndView modelAndView) {
        Itproject itproject = itProjectServiceInter.findById(projectId);
       modelAndView.addObject("itproject", itproject);
        modelAndView.setViewName("project/details");
        return modelAndView;
    }

    @GetMapping
    public ModelAndView index(ModelAndView modelAndView) {
        List<Itproject> projectList = itProjectServiceInter.findAll();
        modelAndView.addObject("projectList", projectList);
        modelAndView.setViewName("project/index");
        return modelAndView;
    }

    @RequestMapping(value = "/join", method = RequestMethod.POST)
    public String joinTeam(@RequestParam("projectId") Integer projectId){

        int result= employeeProfileServiceInter.joinProject(projectId);
        if(result==2)
            return "redirect:/projects/"+projectId+"?alreadyjoined";
        else if(result==1)
            return "redirect:/projects/"+projectId+"?joinsuccess";
        else if(result==3)
            return "redirect:/projects/"+projectId+"?alreadysent";
        else
            return "redirect:/projects?error";
    }
}
</code>```

ProjectControllerTest

```<code>@WebMvcTest(ProjectController.class)
@SpringBootTest
public class ProjectControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private ItProjectServiceInter itProjectServiceInter;

    @MockBean
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @Mock
    ModelAndView modelAndView;

    @Test
    public void detail() throws Exception {
      OngoingStubbing resultItProject =  when(itProjectServiceInter.findById(1)).thenReturn(new Itproject(1));
        when(modelAndView.addObject(resultItProject)).thenReturn(new ModelAndView("project/details"));
        RequestBuilder request = MockMvcRequestBuilders.get("/{projectId}").accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc
                .perform(request)
                .andExpect(status().isOk())
                .andExpect(content().json("project/details"))
                .andReturn();
    }

}
</code>```

```<code>Error Which I have found it:
java.lang.NullPointerException
  at com.bsp.tech.it.community.controller.ProjectControllerTest.detail(ProjectControllerTest.java:44)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
  at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
  at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code>```

When I am using

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {
</code>```

Getting an initialization error:

java.lang.IllegalStateException: Unable to find a
  @SpringBootConfiguration, you need to use @ContextConfiguration or
  @SpringBootTest(classes=...) with your test

at org.springframework.util.Assert.state(Assert.java:73)    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:149)
    at
  org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration(WebMvcTestContextBootstrapper.java:36)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:395)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:98)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:139)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:124)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:142)
    at
  org.springframework.test.context.junit4.SpringRunner.(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at
  org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at
  org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at
  org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
    at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at
  com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at
  com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

And In the pom.xml Using this dependency:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
</code>```

答:
You don't need to use both @WebMvcTest and @SpringBootTest.

Try:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {
...
}
</code>```

Body:
Need to do Unit Testing for the Controller part of the project but have got the error. Believe ModelAndVIew part cause the issue, even though I have mocked it and returned ModelAndView as it is return type of method. However, it does not work. Do not have any issue with Pom.xml, therefore, did not add it.
    ProjectController:

package com.bsptech.itcommunity.controller;

import com.bsptech.itcommunity.entity.Itproject;
import com.bsptech.itcommunity.service.inter.EmployeeProfileServiceInter;
import com.bsptech.itcommunity.service.inter.ItProjectServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(value = "/projects")
public class ProjectController {

    @Autowired
    private ItProjectServiceInter itProjectServiceInter;

    @Autowired
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @RequestMapping(method = RequestMethod.GET, path = "/{projectId}")
    public ModelAndView detail(@PathVariable("projectId") Integer projectId, ModelAndView modelAndView) {
        Itproject itproject = itProjectServiceInter.findById(projectId);
       modelAndView.addObject("itproject", itproject);
        modelAndView.setViewName("project/details");
        return modelAndView;
    }

    @GetMapping
    public ModelAndView index(ModelAndView modelAndView) {
        List<Itproject> projectList = itProjectServiceInter.findAll();
        modelAndView.addObject("projectList", projectList);
        modelAndView.setViewName("project/index");
        return modelAndView;
    }

    @RequestMapping(value = "/join", method = RequestMethod.POST)
    public String joinTeam(@RequestParam("projectId") Integer projectId){

        int result= employeeProfileServiceInter.joinProject(projectId);
        if(result==2)
            return "redirect:/projects/"+projectId+"?alreadyjoined";
        else if(result==1)
            return "redirect:/projects/"+projectId+"?joinsuccess";
        else if(result==3)
            return "redirect:/projects/"+projectId+"?alreadysent";
        else
            return "redirect:/projects?error";
    }
}

ProjectControllerTest

@WebMvcTest(ProjectController.class)
@SpringBootTest
public class ProjectControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private ItProjectServiceInter itProjectServiceInter;

    @MockBean
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @Mock
    ModelAndView modelAndView;

    @Test
    public void detail() throws Exception {
      OngoingStubbing resultItProject =  when(itProjectServiceInter.findById(1)).thenReturn(new Itproject(1));
        when(modelAndView.addObject(resultItProject)).thenReturn(new ModelAndView("project/details"));
        RequestBuilder request = MockMvcRequestBuilders.get("/{projectId}").accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc
                .perform(request)
                .andExpect(status().isOk())
                .andExpect(content().json("project/details"))
                .andReturn();
    }

}

Error Which I have found it:
java.lang.NullPointerException
  at com.bsp.tech.it.community.controller.ProjectControllerTest.detail(ProjectControllerTest.java:44)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
  at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
  at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

When I am using

@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {

Getting an initialization error:

java.lang.IllegalStateException: Unable to find a
  @SpringBootConfiguration, you need to use @ContextConfiguration or
  @SpringBootTest(classes=...) with your test

at org.springframework.util.Assert.state(Assert.java:73)    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:149)
    at
  org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration(WebMvcTestContextBootstrapper.java:36)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:395)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:98)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:139)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:124)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:142)
    at
  org.springframework.test.context.junit4.SpringRunner.(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at
  org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at
  org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at
  org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
    at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at
  com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at
  com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

And In the pom.xml Using this dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Body:
You don't need to use both @WebMvcTest and @SpringBootTest.

Try:

@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {
...
}


问:
Changing the I2C address on-the-fly of a linux device driver
I have two cameras attached to my linux system. The cameras are controlled via I2C. The device driver for a single camera is based on the i2c-core device driver. I want to switch between the two cameras. Therefore, I want to change the I2C address on the fly to control one or the other camera.

Is this reasonable? If yes, is there a function, which does that or is it necessary to detach and attach the client with i2c_detach_client and i2c_attach_client, respsectively?

Thanks for any advice, Stefan

答:
The solution listed in your comment should work. I've written a generic I2C driver before with an ioctl interface that just sets the client->addr entry and it allowed me to test the bus.

Note that i2c_detach_client and i2c_attach_client functions have been removed in the more recent kernels.

ContentLicense: CC BY-SA 3.0


问:
How do you add a character string for every second row in R?
I would like to concatenate one string to every second row for only one column:

From this:

```<code>+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B    |   22 |
| A    |   22 |
| A    |   33 |
| A    |   44 |

+------+------+
</code>```

To this (adding _a to the first col):

```<code>+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B_a  |   22 |
| A    |   22 |
| A_a  |   33 |
| A    |   44 |
+------+------+
</code>```

Thank you for your help! Preferably I would like to use paste0() or anything in the tidyverse!

答:
Using vector recycling in base R:

```<code>df$col1 <- paste0(df$col1, c("", "_a"))
df
  col1 col2
1    A   11
2  B_a   22
3    A   22
4  A_a   33
5    A   44
</code>```

Reproducible example (please provide it yourself next time):

```<code>df <- data.frame(
  col1 = c("A", "B", "A", "A", "A"),
  col2 = c(11, 22, 22, 33, 44),
  stringsAsFactors = FALSE
)
</code>```

Body:
I would like to concatenate one string to every second row for only one column:

From this:

+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B    |   22 |
| A    |   22 |
| A    |   33 |
| A    |   44 |

+------+------+

To this (adding _a to the first col):

+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B_a  |   22 |
| A    |   22 |
| A_a  |   33 |
| A    |   44 |
+------+------+

Thank you for your help! Preferably I would like to use paste0() or anything in the tidyverse!

Body:
Using vector recycling in base R:

df$col1 <- paste0(df$col1, c("", "_a"))
df
  col1 col2
1    A   11
2  B_a   22
3    A   22
4  A_a   33
5    A   44

Reproducible example (please provide it yourself next time):

df <- data.frame(
  col1 = c("A", "B", "A", "A", "A"),
  col2 = c(11, 22, 22, 33, 44),
  stringsAsFactors = FALSE
)


问:
Remove whitespaces before a character starts and before equal to(=) sign and using shell
I have one file(file1.txt)

```<code>Rahul=rahul

Vimal=vimal

   Vishal =vishal

   Rupesh =rupesh

   Aromal =aromal

   Anugrah =anugrah
</code>```

My output file should be

```<code>Rahul=rahul

Vimal=vimal

Vishal=vishal

Rupesh=rupesh

Aromal=aromal

Anugrah=anugrah
</code>```

I tried with following commands. Still not getting output as I needed.

```<code>sed 's/  */ /g' < file1.txt

sed 's/ \{1,\}/ /g' < file1.txt

sed 's/ \+ / /g' < file1.txt

sed -e "s/[[:space:]]\+/ /g" < file1.txt
</code>```

答:
You may use this sed with an alternation in your regex:

```<code>sed -E 's/^[[:blank:]]+|[[:blank:]]+(=)/\1/g' file
</code>```

\1 is back-reference for capture group #1 i.e. = in 2nd part of alternation.

```<code>Rahul=rahul

Vimal=vimal

Vishal=vishal

Rupesh=rupesh

Aromal=aromal

Anugrah=anugrah
</code>```

Body:
I have one file(file1.txt)

Rahul=rahul

Vimal=vimal

   Vishal =vishal

   Rupesh =rupesh

   Aromal =aromal

   Anugrah =anugrah

My output file should be

Rahul=rahul

Vimal=vimal

Vishal=vishal

Rupesh=rupesh

Aromal=aromal

Anugrah=anugrah

I tried with following commands. Still not getting output as I needed.

sed 's/  */ /g' < file1.txt

sed 's/ \{1,\}/ /g' < file1.txt

sed 's/ \+ / /g' < file1.txt

sed -e "s/[[:space:]]\+/ /g" < file1.txt

Body:
You may use this sed with an alternation in your regex:

sed -E 's/^[[:blank:]]+|[[:blank:]]+(=)/\1/g' file

\1 is back-reference for capture group #1 i.e. = in 2nd part of alternation.

Rahul=rahul

Vimal=vimal

Vishal=vishal

Rupesh=rupesh

Aromal=aromal

Anugrah=anugrah


问:
Only one of arguments should be allowed with CommandLineParser
Im working on a console tool which accepts some arguments and then parses to the Option class.

What I need is a property that will verify if only one of many marked fields in Option class has values (arguments were delivered).

Ex.
Its ok when we run:

my.exe -a

my.exe -b

but NOT:

my.exe

my.exe -a -b

CommandLine.OptionAttribute cannot do such a thing. What i did is:
Main class args[] got extension .Parse:

```<code>args.Parse(options)` //where options is my Options class
</code>```

inside:

```<code>CommandLine.Parser.Default.ParseArguments(args, options);
var isOnlyOneOfMany = options.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(OneOfMany)) && prop.GetValue(options) != null).Count() == 1;
</code>```

how to do this better way?

答:
Update: This solution doesn't work from version 2.8.0 because both SetName and Group are not allowed in option

You can use SetName and GroupName to achieve this behavior:

GroupName: Available from version 2.7+

An option group represents a group of options which are optional, but at least one should be available.

SetName: Available from version 1.9+

It means that you can run commands of one set at a time. You can't mix
commands of more than one set otherwise you get an error.

The new option class:

```<code>public class Options
{
    [Option('a', "aValue", Group = "Values", SetName = "ASet")]
    public bool AValue { get; set; }

    [Option('b', "aValue", Group = "Values", SetName = "BSet")]
    public bool BValue { get; set; }
}
</code>```

How to parse the args:

```<code>var options = Parser.Default.ParseArguments<Options>(args);
</code>```

Body:
Im working on a console tool which accepts some arguments and then parses to the Option class.

What I need is a property that will verify if only one of many marked fields in Option class has values (arguments were delivered).

Ex.
Its ok when we run:

my.exe -a

my.exe -b

but NOT:

my.exe

my.exe -a -b

CommandLine.OptionAttribute cannot do such a thing. What i did is:
Main class args[] got extension .Parse:

args.Parse(options)` //where options is my Options class

inside:

CommandLine.Parser.Default.ParseArguments(args, options);
var isOnlyOneOfMany = options.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(OneOfMany)) && prop.GetValue(options) != null).Count() == 1;

how to do this better way?

Body:
Update: This solution doesn't work from version 2.8.0 because both SetName and Group are not allowed in option

You can use SetName and GroupName to achieve this behavior:

GroupName: Available from version 2.7+

An option group represents a group of options which are optional, but at least one should be available.

SetName: Available from version 1.9+

It means that you can run commands of one set at a time. You can't mix
commands of more than one set otherwise you get an error.

The new option class:

public class Options
{
    [Option('a', "aValue", Group = "Values", SetName = "ASet")]
    public bool AValue { get; set; }

    [Option('b', "aValue", Group = "Values", SetName = "BSet")]
    public bool BValue { get; set; }
}

How to parse the args:

var options = Parser.Default.ParseArguments<Options>(args);


问:
How to know that last recyclerView item of first or current screen/page is loaded, any Callbacks but gets called once?
I am using a grid layout of recyclerView and have tried several options using either onLayoutCompled methods and also by onScollListner methods, tried this answer but it's stiil calling multiple times as each item keeps loading, nothing is working.

Just want to detect the last recyclerView item of the particular screen is completely loaded or visible to the user according to their screen size Or we can say that when the user's current screen is full of the recyclerView Items, any way to detect that? ANd should be called only once. Any help would be great.

Thank you for your valuable time.

答:
You can use a Sharedpref value which can be set to true in your onScrollStateChanged method based on your condition.

```<code>@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
   super.onScrollStateChanged(recyclerView, newState);

   if (newState != RecyclerView.SCROLL_STATE_IDLE) {
      return;
   }

   boolean isLastPositionVisible = mFollowingLayoutManager.findLastVisibleItemPosition() == getList().size() - 1

   if(isLastPositionVisible && getSharedPrefValue()) {
      // Call your method
      // Set sharedpref value to true.
   }

}
</code>```

Body:
You can use a Sharedpref value which can be set to true in your onScrollStateChanged method based on your condition.

@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
   super.onScrollStateChanged(recyclerView, newState);

   if (newState != RecyclerView.SCROLL_STATE_IDLE) {
      return;
   }

   boolean isLastPositionVisible = mFollowingLayoutManager.findLastVisibleItemPosition() == getList().size() - 1

   if(isLastPositionVisible && getSharedPrefValue()) {
      // Call your method
      // Set sharedpref value to true.
   }

}


问:
Switch Style Radio Button Using JavaScript
I would like to know how I can make a switch style function to change the website style between 2 styles. Here's what I have done so far. Please check. Thank you.

```<code>function switchcss() {
    document.write('<link rel="stylesheet" type"text/css" href="css/style1.css">');
    document.write('<link rel="stylesheet" type"text/css" href="css/style2.css">');
}
</code>```

http://jsfiddle.net/APbSm/

答:
Here is an implementation. It borrows much of the event handler logic from this post. YOU SHOULD NOT USE THIS CODE IN PRODUCTION. There is nothing worse than copying and pasting code you do not understand. Read and practice, when you fully understand this code you will be able to write a much better implementation that you will be able to maintain and support.

```<code><link rel="stylesheet" type="text/css" href="style1.css" id="switch_style"/>
</code>```

JS stuff:

```<code><script type="text/javascript">
(function(){
  function getEvent (e) {
    if(!e) e = window.event;
    if(e.srcElement) e.target = e.srcElement;
    return e;
  }
  function addEvent (object,type,listener,param) {
    if(object.addEventListener) {
      object.addEventListener(type,
        function(e){
          listener.call(object, e, param);
        },
        false );
    } else if(object.attachEvent) {
      object.attachEvent('on'+type,
        function(e){
          e = getEvent(e);
          listener.call(object, e, param);
        }
      );
    }
  }
  var default_style = 1,
      container = document.getElementById('switch_container'),
      controls = container.childNodes,
      styles = document.getElementById('switch_style');
  function switch_style(event){
    event = getEvent(event);
    s = event.target.getAttribute('value');
    styles.setAttribute('href, 'style' + s + '.css');
  }
  [].map.call(controls, function( e, i, l ){
    if( e.nodeType === 1 && e.getAttribute('type') === 'radio' ) {
      addEvent( e, 'click', switch_style );
    }
  })
  // bind the function to the event handler.
})()
</script>
</code>```

DOM stuff:

```<code><div id="switch_container">
  <input type="radio" name="switch" value="1"/>style 1<br/>
  <input type="radio" name="switch" value="2"/>style 2<br/>
  <input type="radio" name="switch" value="3"/>style 3<br/>
  <input type="radio" name="switch" value="4"/>style 4<br/>
  <input type="radio" name="switch" value="5"/>style 5<br/>
  <input type="radio" name="switch" value="6"/>style 6<br/>
</div>
</code>```

JSFIDDLE

Body:
I would like to know how I can make a switch style function to change the website style between 2 styles. Here's what I have done so far. Please check. Thank you.

function switchcss() {
    document.write('<link rel="stylesheet" type"text/css" href="css/style1.css">');
    document.write('<link rel="stylesheet" type"text/css" href="css/style2.css">');
}

http://jsfiddle.net/APbSm/

Body:
Here is an implementation. It borrows much of the event handler logic from this post. YOU SHOULD NOT USE THIS CODE IN PRODUCTION. There is nothing worse than copying and pasting code you do not understand. Read and practice, when you fully understand this code you will be able to write a much better implementation that you will be able to maintain and support.

<link rel="stylesheet" type="text/css" href="style1.css" id="switch_style"/>

JS stuff:

<script type="text/javascript">
(function(){
  function getEvent (e) {
    if(!e) e = window.event;
    if(e.srcElement) e.target = e.srcElement;
    return e;
  }
  function addEvent (object,type,listener,param) {
    if(object.addEventListener) {
      object.addEventListener(type,
        function(e){
          listener.call(object, e, param);
        },
        false );
    } else if(object.attachEvent) {
      object.attachEvent('on'+type,
        function(e){
          e = getEvent(e);
          listener.call(object, e, param);
        }
      );
    }
  }
  var default_style = 1,
      container = document.getElementById('switch_container'),
      controls = container.childNodes,
      styles = document.getElementById('switch_style');
  function switch_style(event){
    event = getEvent(event);
    s = event.target.getAttribute('value');
    styles.setAttribute('href, 'style' + s + '.css');
  }
  [].map.call(controls, function( e, i, l ){
    if( e.nodeType === 1 && e.getAttribute('type') === 'radio' ) {
      addEvent( e, 'click', switch_style );
    }
  })
  // bind the function to the event handler.
})()
</script>

DOM stuff:

<div id="switch_container">
  <input type="radio" name="switch" value="1"/>style 1<br/>
  <input type="radio" name="switch" value="2"/>style 2<br/>
  <input type="radio" name="switch" value="3"/>style 3<br/>
  <input type="radio" name="switch" value="4"/>style 4<br/>
  <input type="radio" name="switch" value="5"/>style 5<br/>
  <input type="radio" name="switch" value="6"/>style 6<br/>
</div>

JSFIDDLE


问:
Capturing a date from three different TextInput
I have three different TextInput, in each of one of them goes the day, month and year of birth.
How can I capture all three values and 'condense' them into a date when a button is pressed? Also, how can I validate that the numbers posted on the TextInputs are valid? (for example, the user can't put a 13 inside the month TextInput)

Here's my code:

```<code>class App extends Component { // AgeInput
state = { date: null, edad: null }

_ageCalc = (fecha) => {
  var hoy = new Date();
  var fechaNacimiento = new Date(fecha);
  var edad_ahora = hoy.getFullYear() - fechaNacimiento.getFullYear();
  var mes = hoy.getMonth() - fechaNacimiento.getMonth();

  if (mes < 0 || (mes === 0 && hoy.getDate() < fechaNacimiento.getDate())) {
    edad_ahora--;
  }

  this.setState({ edad: edad_ahora });
}

render () {
  return (
    <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled enableOnAndroid={true}
    resetScrollToCoords={{x:0, y:0}}>
      <View style={styles.topView}>
       <TouchableOpacity style={styles.img}>
         <Image source={flecha} />
       </TouchableOpacity>
      <View style={styles.topTextWrapper}>
       <Text style={styles.topTextPrimary}>Bienvenido a Neuron</Text>
         <Text style={styles.topTextSecondary}>¿O no?</Text>
       </View>
     </View>

     <View style={styles.middleView}>
      <Text style={styles.formText}>Fecha de nacimiento</Text>
      <View style={styles.formRow}>
        <View style={styles.textInputWrapper}>
          <TextInput style={styles.formInput} placeholder='DD' keyboardType='number-pad'/>
        </View>
        <View style={styles.textInputWrapper}>
          <TextInput style={styles.formInput} placeholder='MM' keyboardType='number-pad'/>
        </View>
        <View style={styles.textInputWrapper}>
          <TextInput style={styles.formInput} placeholder='AA' keyboardType='number-pad'/>
        </View>
      </View>
    </View>

    <View style={styles.buttonView}>
      <TouchableOpacity style={styles.button}>
        <Text style={styles.buttonText}>CALCULAR EDAD</Text>
      </TouchableOpacity>
    </View>

    <View style={styles.ageView}>
      <Text style={styles.ageTextPrimary}>Tu edad es:</Text>
      <Text style={styles.ageNumber}>{this.state.edad}</Text>
      <Text style={styles.ageTextSecondary}>Años</Text>
    </View>
  </KeyboardAwareScrollView>
);}}
</code>```

答:
please see below example. I think this will help you. Change this according to your requirement.

```<code>import React, { Component } from 'react';
import { Alert, View, Text, Image, TouchableOpacity, TextInput } from 'react-native';

class HomeScreen extends Component {
  state = {
    date: '',
    month: '',
    year: '',
    isErrorDate: false,
    isErrorDateLenght: false,
    isErrorMonth: false,
    isErrorMonthLength: false,
    isErrorYear: false,
    isErrorYearLength: false
  };

  onChangeDate = value => {
    this.setState({
      date: value,
      isErrorDate: false,
      isErrorDateLenght: false,
    });
  };
  onChangeMonth = value => {
    this.setState({
      month: value,
      isErrorMonth: false,
      isErrorMonthLength: false,
    });
  };
  onChangeYear = value => {
    this.setState({
      year: value,
      isErrorYear: false,
      isErrorYearLength: false
    });
  };

  checkDate = () => {
    const { date, month, year } = this.state;
    let isErrorDate = date.trim() === '' ? true : false;
    let isErrorDateLenght = date.length > 2 || !/^[0-9]+$/.test(date) || date > 31 ? true : false;
    let isErrorMonth = month.trim() === '' ? true : false;
    let isErrorMonthLength = month.length > 2 || !/^[0-9]+$/.test(month) || month > 12 ? true : false;
    let isErrorYear = year.trim() === '' ? true : false;
    let isErrorYearLength = year.length > 4 || !/^[0-9]+$/.test(year) ? true : false;
    if (
      isErrorDate ||
      isErrorDateLenght ||
      isErrorMonth ||
      isErrorMonthLength ||
      isErrorYear ||
      isErrorYearLength
    ) {
      this.setState({
        isErrorDate: isErrorDate,
        isErrorDateLenght: isErrorDateLenght,
        isErrorMonth: isErrorMonth,
        isErrorMonthLength: isErrorMonthLength,
        isErrorYear: isErrorYear,
        isErrorYearLength: isErrorYearLength
      });
      Alert.alert('invalid date /month/ year')
    } else {
      //submit date
    }

  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        {/* <KeyboardAwareScrollView scrollEnabled enableOnAndroid={true}> */}
        <View >
          <TouchableOpacity >
            <Image />
          </TouchableOpacity>
          <View >
            <Text >Bienvenido a Neuron</Text>
            <Text >¿O no?</Text>
          </View>
        </View>

        <View >
          <Text >Fecha de nacimiento</Text>
          <View >
            <View style={{ padding: 10 }} >
              <TextInput placeholder='DD' keyboardType='number-pad' value={this.state.date} onChangeText={this.onChangeDate} />
            </View>
            <View style={{ padding: 10 }}>
              <TextInput placeholder='MM' keyboardType='number-pad' value={this.state.month} onChangeText={this.onChangeMonth} />
            </View>
            <View style={{ padding: 10 }} >
              <TextInput placeholder='AA' keyboardType='number-pad' value={this.state.year} onChangeText={this.onChangeYear} />
            </View>
          </View>
        </View>

        <View >
          <TouchableOpacity style={{ padding: 10, backgroundColor: 'gray', alignItems: 'center' }} onPress={this.checkDate}>
            <Text >CALCULAR EDAD</Text>
          </TouchableOpacity>
        </View>

        <View >
          <Text >Tu edad es:</Text>
          <Text >Años</Text>
        </View>
        {/* </KeyboardAwareScrollView> */}
      </View>
    );
  }
}

export default HomeScreen;
</code>```

Feel free for doubts

Body:
I have three different TextInput, in each of one of them goes the day, month and year of birth.
How can I capture all three values and 'condense' them into a date when a button is pressed? Also, how can I validate that the numbers posted on the TextInputs are valid? (for example, the user can't put a 13 inside the month TextInput)

Here's my code:

class App extends Component { // AgeInput
state = { date: null, edad: null }

_ageCalc = (fecha) => {
  var hoy = new Date();
  var fechaNacimiento = new Date(fecha);
  var edad_ahora = hoy.getFullYear() - fechaNacimiento.getFullYear();
  var mes = hoy.getMonth() - fechaNacimiento.getMonth();

  if (mes < 0 || (mes === 0 && hoy.getDate() < fechaNacimiento.getDate())) {
    edad_ahora--;
  }

  this.setState({ edad: edad_ahora });
}

render () {
  return (
    <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled enableOnAndroid={true}
    resetScrollToCoords={{x:0, y:0}}>
      <View style={styles.topView}>
       <TouchableOpacity style={styles.img}>
         <Image source={flecha} />
       </TouchableOpacity>
      <View style={styles.topTextWrapper}>
       <Text style={styles.topTextPrimary}>Bienvenido a Neuron</Text>
         <Text style={styles.topTextSecondary}>¿O no?</Text>
       </View>
     </View>

     <View style={styles.middleView}>
      <Text style={styles.formText}>Fecha de nacimiento</Text>
      <View style={styles.formRow}>
        <View style={styles.textInputWrapper}>
          <TextInput style={styles.formInput} placeholder='DD' keyboardType='number-pad'/>
        </View>
        <View style={styles.textInputWrapper}>
          <TextInput style={styles.formInput} placeholder='MM' keyboardType='number-pad'/>
        </View>
        <View style={styles.textInputWrapper}>
          <TextInput style={styles.formInput} placeholder='AA' keyboardType='number-pad'/>
        </View>
      </View>
    </View>

    <View style={styles.buttonView}>
      <TouchableOpacity style={styles.button}>
        <Text style={styles.buttonText}>CALCULAR EDAD</Text>
      </TouchableOpacity>
    </View>

    <View style={styles.ageView}>
      <Text style={styles.ageTextPrimary}>Tu edad es:</Text>
      <Text style={styles.ageNumber}>{this.state.edad}</Text>
      <Text style={styles.ageTextSecondary}>Años</Text>
    </View>
  </KeyboardAwareScrollView>
);}}

Body:
please see below example. I think this will help you. Change this according to your requirement.

import React, { Component } from 'react';
import { Alert, View, Text, Image, TouchableOpacity, TextInput } from 'react-native';

class HomeScreen extends Component {
  state = {
    date: '',
    month: '',
    year: '',
    isErrorDate: false,
    isErrorDateLenght: false,
    isErrorMonth: false,
    isErrorMonthLength: false,
    isErrorYear: false,
    isErrorYearLength: false
  };

  onChangeDate = value => {
    this.setState({
      date: value,
      isErrorDate: false,
      isErrorDateLenght: false,
    });
  };
  onChangeMonth = value => {
    this.setState({
      month: value,
      isErrorMonth: false,
      isErrorMonthLength: false,
    });
  };
  onChangeYear = value => {
    this.setState({
      year: value,
      isErrorYear: false,
      isErrorYearLength: false
    });
  };

  checkDate = () => {
    const { date, month, year } = this.state;
    let isErrorDate = date.trim() === '' ? true : false;
    let isErrorDateLenght = date.length > 2 || !/^[0-9]+$/.test(date) || date > 31 ? true : false;
    let isErrorMonth = month.trim() === '' ? true : false;
    let isErrorMonthLength = month.length > 2 || !/^[0-9]+$/.test(month) || month > 12 ? true : false;
    let isErrorYear = year.trim() === '' ? true : false;
    let isErrorYearLength = year.length > 4 || !/^[0-9]+$/.test(year) ? true : false;
    if (
      isErrorDate ||
      isErrorDateLenght ||
      isErrorMonth ||
      isErrorMonthLength ||
      isErrorYear ||
      isErrorYearLength
    ) {
      this.setState({
        isErrorDate: isErrorDate,
        isErrorDateLenght: isErrorDateLenght,
        isErrorMonth: isErrorMonth,
        isErrorMonthLength: isErrorMonthLength,
        isErrorYear: isErrorYear,
        isErrorYearLength: isErrorYearLength
      });
      Alert.alert('invalid date /month/ year')
    } else {
      //submit date
    }

  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        {/* <KeyboardAwareScrollView scrollEnabled enableOnAndroid={true}> */}
        <View >
          <TouchableOpacity >
            <Image />
          </TouchableOpacity>
          <View >
            <Text >Bienvenido a Neuron</Text>
            <Text >¿O no?</Text>
          </View>
        </View>

        <View >
          <Text >Fecha de nacimiento</Text>
          <View >
            <View style={{ padding: 10 }} >
              <TextInput placeholder='DD' keyboardType='number-pad' value={this.state.date} onChangeText={this.onChangeDate} />
            </View>
            <View style={{ padding: 10 }}>
              <TextInput placeholder='MM' keyboardType='number-pad' value={this.state.month} onChangeText={this.onChangeMonth} />
            </View>
            <View style={{ padding: 10 }} >
              <TextInput placeholder='AA' keyboardType='number-pad' value={this.state.year} onChangeText={this.onChangeYear} />
            </View>
          </View>
        </View>

        <View >
          <TouchableOpacity style={{ padding: 10, backgroundColor: 'gray', alignItems: 'center' }} onPress={this.checkDate}>
            <Text >CALCULAR EDAD</Text>
          </TouchableOpacity>
        </View>

        <View >
          <Text >Tu edad es:</Text>
          <Text >Años</Text>
        </View>
        {/* </KeyboardAwareScrollView> */}
      </View>
    );
  }
}

export default HomeScreen;

Feel free for doubts


问:
Is there a way to save BigQuery interactive shell results to file?
Doing bq shell runs the BigQuery interactive shell. Once run, the shell can accept SQL commands and a tabular format of the results is shown.

Is there a way to save these interactive results to a file (e.g. CSV, JSON, etc...)?

答:
You can achieve this by using --format flag, where you can pass one of the following options:

pretty - formatted table output

sparse - simpler table output

prettyjson - easy-to-read JSON format

json - maximally compact JSON

csv - csv format with header

I have tested it with prettyjson format and it works fine:

```<code>bq query --format=prettyjson --use_legacy_sql=false 'SELECT name, number FROM `bigquery-public-data`.usa_names.usa_1910_current WHERE gender = "M" ORDER BY number DESC' > output.json
</code>```

By using > at the end of the command, it is possible to save the output of a command to a new file. You will be able to see the output of query in output.json file.

Another possible way to do it is writing query results to a permanent table with bq query command and then download the results to CSV/JSON.

When you run following example:

```<code>bq shell
query --use_legacy_sql=false --destination_table project_id:dataset.table 'SELECT name, number FROM `bigquery-public-data`.usa_names.usa_1910_current WHERE gender = "M" ORDER BY number DESC'
</code>```

Remember, that the destination table must be new or empty.

The results of executed query looks like this:

```<code>Waiting on bqjob_r11abc345 ... (5s) Current status: DONE
+---------+--------+
|  name   | number |
+---------+--------+
| Robert  |  10021 |
| John    |   9636 |
| Robert  |   9297 |
| ...              |
+---------+--------+
</code>```

Now, when you go to BigQuery web UI, you will be able to see results in project_id:dataset.table. After you run a SQL query, you can download the results to a file on your local machine, you can save the results to Google Drive or Google Sheets. You can download query results locally only in CSV or newline-delimited JSON format.

I recommend you to take a look for official documentation. I hope it helps you.

Body:
You can achieve this by using --format flag, where you can pass one of the following options:

pretty - formatted table output

sparse - simpler table output

prettyjson - easy-to-read JSON format

json - maximally compact JSON

csv - csv format with header

I have tested it with prettyjson format and it works fine:

bq query --format=prettyjson --use_legacy_sql=false 'SELECT name, number FROM `bigquery-public-data`.usa_names.usa_1910_current WHERE gender = "M" ORDER BY number DESC' > output.json

By using > at the end of the command, it is possible to save the output of a command to a new file. You will be able to see the output of query in output.json file.

Another possible way to do it is writing query results to a permanent table with bq query command and then download the results to CSV/JSON.

When you run following example:

bq shell
query --use_legacy_sql=false --destination_table project_id:dataset.table 'SELECT name, number FROM `bigquery-public-data`.usa_names.usa_1910_current WHERE gender = "M" ORDER BY number DESC'

Remember, that the destination table must be new or empty.

The results of executed query looks like this:

Waiting on bqjob_r11abc345 ... (5s) Current status: DONE
+---------+--------+
|  name   | number |
+---------+--------+
| Robert  |  10021 |
| John    |   9636 |
| Robert  |   9297 |
| ...              |
+---------+--------+

Now, when you go to BigQuery web UI, you will be able to see results in project_id:dataset.table. After you run a SQL query, you can download the results to a file on your local machine, you can save the results to Google Drive or Google Sheets. You can download query results locally only in CSV or newline-delimited JSON format.

I recommend you to take a look for official documentation. I hope it helps you.


答:
We can use vector recycling to subset alternate values of col1 and paste "a_" to it.

```<code>df$col1[c(FALSE, TRUE)] <- paste0(df$col1[c(FALSE, TRUE)], "_a")
df
#  col1 col2
#1    A   11
#2  B_a   22
#3    A   22
#4  A_a   33
#5    A   44
</code>```

Make sure col1 is of class character and not factor.

Title: How do you add a character string for every second row in R?

Body:
We can use vector recycling to subset alternate values of col1 and paste "a_" to it.

df$col1[c(FALSE, TRUE)] <- paste0(df$col1[c(FALSE, TRUE)], "_a")
df
#  col1 col2
#1    A   11
#2  B_a   22
#3    A   22
#4  A_a   33
#5    A   44

Make sure col1 is of class character and not factor.


问:
What happened to the J2EE jar on Maven Central?
I have a legacy project with this dependency:

```<code><dependency>
    <groupId>javax.j2ee</groupId>
    <artifactId>j2ee</artifactId>
    <version>1.4</version>
</dependency>
</code>```

Although, I can find this on Maven here, if I try to download the jar I get a 404.

So what happened to this jar? With what should I replace it?

Thanks

答:
That's an old legacy jar from the Sun days, they tended to have licensing issues that prevented them from being in Maven central. If that build ever succeeded, the jar may have been hosted in a third party Maven repository.

I found this dependency... even though the group name is different it looks to be the one: https://repo.maven.apache.org/maven2/milyn/j2ee/1.4/

If that doesn't work then your best bet is to probably find a copy of the jar somewhere, most likely on the official download site. You can then put it in your own project as a local Maven repository as described in this excellent answer. Then you can never lose access to it again.

So adapting the knowledge in that answer, the install command for the j2ee jar would look like this:

```<code>mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file  \
    -Dfile=/some/path/on/my/local/filesystem/j2ee.jar \
    -DgroupId=javax.j2ee -DartifactId=j2ee \
    -Dversion=1.4 -Dpackaging=jar \
    -DlocalRepositoryPath=${project.basedir}/local-maven-repo
</code>```

Side note: that's one long command, the way it is structured here with the slashes is just for visibility purposes.

Credit goes to Stephen C for providing the Oracle download site for the legacy j2ee 1.4 materials.

Body:
I have a legacy project with this dependency:

<dependency>
    <groupId>javax.j2ee</groupId>
    <artifactId>j2ee</artifactId>
    <version>1.4</version>
</dependency>

Although, I can find this on Maven here, if I try to download the jar I get a 404.

So what happened to this jar? With what should I replace it?

Thanks

Body:
That's an old legacy jar from the Sun days, they tended to have licensing issues that prevented them from being in Maven central. If that build ever succeeded, the jar may have been hosted in a third party Maven repository.

I found this dependency... even though the group name is different it looks to be the one: https://repo.maven.apache.org/maven2/milyn/j2ee/1.4/

If that doesn't work then your best bet is to probably find a copy of the jar somewhere, most likely on the official download site. You can then put it in your own project as a local Maven repository as described in this excellent answer. Then you can never lose access to it again.

So adapting the knowledge in that answer, the install command for the j2ee jar would look like this:

mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file  \
    -Dfile=/some/path/on/my/local/filesystem/j2ee.jar \
    -DgroupId=javax.j2ee -DartifactId=j2ee \
    -Dversion=1.4 -Dpackaging=jar \
    -DlocalRepositoryPath=${project.basedir}/local-maven-repo

Side note: that's one long command, the way it is structured here with the slashes is just for visibility purposes.

Credit goes to Stephen C for providing the Oracle download site for the legacy j2ee 1.4 materials.


问:
Where can I find docker container logs for Azure App Service
I do have a Docker container running a .net core 2 app.

The logging is configured using this code in Program.cs

```<code>public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
        })
        .UseStartup<Startup>();
</code>```

and the appsettings.json file

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
}
</code>```

Logging seems to be Ok, when running Kestrel directly, I can see the logs in the terminal. Same thing, when containerized: the command docker logs shows what I want.

Troubles arise in production, when run in as a container in Azure Web App. I cannot find any consistent docker logs.

I made attempts to visit the Log file via FTP or via the url https://[mysite].scm.azurewebsites.net/api/logs/docker the log files are almost empty for example,
https://[mysite].scm.azurewebsites.net/api/vfs/LogFiles/2018_09_09_RD0003FF74F63E_docker.log,
only container starting lines are present

Also I do have the same lines in the usual portal interface.

The question is: do docker logs are automatically output in docker.log files in Azure Web App? Is there something that I am missing?

答:
I have the same exact issue, the App Service container logs is generic and vague. This is not the same logs that Docker shows us whenever we run a container.

17/02/2020 08:59:25.186 INFO - Site: tutorial-api - Start container succeeded. Container: f8bfa7e27680c0e9551c6157f9d1c8a73c9a3e739b4f15de8586ce52809798d3
17/02/2020 08:59:30.675 INFO - Site: tutorial-api - Application Logging (Filesystem): On
17/02/2020 08:59:44.106 INFO - Site: tutorial-api - Waiting for container to be ready
17/02/2020 08:59:49.116 INFO - Site: tutorial-api - Container has exited
17/02/2020 08:59:49.117 ERROR - Site: tutorial-api - Container could not be started
17/02/2020 08:59:49.120 INFO - Site: tutorial-api - Purging after container failed to start
17/02/2020 08:59:49.120 ERROR - Site: tutorial-api - Unable to start container. Error message: Container could not be started: tutorial-api_20

"Unable to start container,  container couldn't be started"

Wow! Azure just told me every 60 seconds a minute has passed.

I understand that this is production environment, but you got to give us something!

Out of frustration, I decided to run same image in a Azure Container Instance resource, there it shows you the same detailed logs that Docker provides (see screenshot below)

Now that's what I'm talking about!

Using the error logs in Azure Container Instance, I found out that my App Service couldn't access the Sql Server resource (even though they are within the same resource group). I simply enabled the Sql Server resource to be accessed within the same resource group

Body:
I do have a Docker container running a .net core 2 app.

The logging is configured using this code in Program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
        })
        .UseStartup<Startup>();

and the appsettings.json file

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
}

Logging seems to be Ok, when running Kestrel directly, I can see the logs in the terminal. Same thing, when containerized: the command docker logs shows what I want.

Troubles arise in production, when run in as a container in Azure Web App. I cannot find any consistent docker logs.

I made attempts to visit the Log file via FTP or via the url https://[mysite].scm.azurewebsites.net/api/logs/docker the log files are almost empty for example,
https://[mysite].scm.azurewebsites.net/api/vfs/LogFiles/2018_09_09_RD0003FF74F63E_docker.log,
only container starting lines are present

Also I do have the same lines in the usual portal interface.

The question is: do docker logs are automatically output in docker.log files in Azure Web App? Is there something that I am missing?


问:
What is best way to performance and load test AWS cloud applications
Want to keep this question generic and expected answer in terms of best practice/approach/guidelines,

We need to know the best way to performance test and load test AWS cloud based applications.

What we have tried:

We used Gatling and Jmeter to execute our performance tests. These frameworks are pretty useful to test our functionality and to benchmark our applications latency and request rate.

Problem:

Performance benchmarks and limits of AWS managed services like Lambda and DDB are already specified by AWS e.g. Lambda concurrency behavior and DDB autoscaling under load etc. AWS also provides high availability and guaranteed performance of managed services.

Is it really worth executing expensive performance test and load test jobs for AWS managed services?

How to ensure that we are testing our application and not actually testing AWS limits which are already known.

What is the best practice and approach to performance test cloud based applications.

Any suggestions will help tremendously.
Thanks,

答:
It depends on how you can use the AWS infrastructure

If you don't use Auto Scaling you can treat the AWS cloud-based application as a "normal" application just deployed not on your company premises, but somewhere at Amazon

If you use Auto Scaling you might want to come up with a some form of scalability testing. AWS instances can scale up in order to adapt to the increased load but your application must be able to scale as well. So you can test:

how fast are scale-up and scale-down processes, i.e. if you rapidly increase the load do AWS/your application react fast enough or there will be performance drop

scalability factor. For example with 100 virtual users you have 50 requests per second. Ideally with 200 virtual users you should have 100 requests per second, with 300 virtual users - 150 requests per second. Response time should remain the same. But normally the situation differs from the "ideal" so it would be good to know this scalability factor.

Also if your application is behind the AWS ELB you will need to add DNS Cache Manager to your JMeter test plan otherwise you will be hitting only one backend instance while others will be idle.


问:
How do you insert a global / environment variable inside a Postman request body?
I am generating a custom email address within the pre-request script and I set it as a global environment variable, i.e.

```<code>pm.environment.set('email', email)
</code>```

My request body can be seen below:

```<code>{
  "email": "{{email}}",
  "country": "CH",
  "password": "test",
}
</code>```

However the server always returns me a 401 response, I am assuming that Postman is not resolving the variable for some reason, hence actually trying to post '{{email}}' as email parameter, which will be rejected by the server to prevent js injections.

答:
First,
pm.environment.set('email', email) this set environmental variable not as global variable.

So if you are doing pm.environment.set('email', email) like this then make sure you have selected the correct envionment while sending the request.

Second,
You can set email as global variable using pm.globals.set("variable_key", "variable_value");

Also 401 response code means Unauthorized error which means authentication for the request is not correct.

Body:
I am generating a custom email address within the pre-request script and I set it as a global environment variable, i.e.

pm.environment.set('email', email)

My request body can be seen below:

{
  "email": "{{email}}",
  "country": "CH",
  "password": "test",
}

However the server always returns me a 401 response, I am assuming that Postman is not resolving the variable for some reason, hence actually trying to post '{{email}}' as email parameter, which will be rejected by the server to prevent js injections.


问:
How to display dynamic keys and values of json data in html using php
The below values are dynamic in JSON format, which will change for every entry.
1) {"ABCD":{"Hindi":"82"},"EFGH":{"English":"78"},"IJKL":{"Urdu":"82"},"MNOP":{"Sanskrit":"78"}}

I want to display in single cell in a column, as shown below. how can i achieve that using PHP

REMARKS

ABCD: Hindi = 82,

EFGH: English = 78,

IJKL: Urdu = 82,

MNOP: Sanskrit = 78

答:
Use

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

Then, iterate over data using foreach

```<code>$final = [];
$arr = json_decode($a, true);

foreach($arr as $key => $val){

    $out = '';
      foreach($val as $k => $v){

        $out .= $k."=" .$v;

      }
     $f = $key . ":" . $out . "<br>";

    $final[] = $f;

   }
</code>```

O/P will be :

```<code>Array ( [0] => ABCD:Hindi=82
[1] => EFGH:English=78
[2] => IJKL:Urdu=82
[3] => MNOP:Sanskrit=78
)
</code>```

Body:
Use

$arr = json_decode($data, true);

Then, iterate over data using foreach

$final = [];
$arr = json_decode($a, true);

foreach($arr as $key => $val){

    $out = '';
      foreach($val as $k => $v){

        $out .= $k."=" .$v;

      }
     $f = $key . ":" . $out . "<br>";

    $final[] = $f;

   }

O/P will be :

Array ( [0] => ABCD:Hindi=82
[1] => EFGH:English=78
[2] => IJKL:Urdu=82
[3] => MNOP:Sanskrit=78
)


问:
Cannot kill process with powershell (Stop-Process)
I have a ps1 script (Windows 2008 R2) to kill process:

```<code> Stop-Process -Name "c_proc".
</code>```

c_proc is a program that runs in console mode.
After running this script c_proc does not exit, it just keeps restarting in console mode.
Another way to kill c_proc is to kill conhost.exe but it didn't work either.
c_proc can exit when you type in its console windows "exit".
How can I send the message "exit" to the console window via PowerShell or cmd?
How can I kill c_proc?

答:
This is the right code to kill the process c_proc. I found the parent process:

```<code>  Stop-Process -Name "start"
  Stop-Process -Name "c_proc"
</code>```

Body:
I have a ps1 script (Windows 2008 R2) to kill process:

 Stop-Process -Name "c_proc".

c_proc is a program that runs in console mode.
After running this script c_proc does not exit, it just keeps restarting in console mode.
Another way to kill c_proc is to kill conhost.exe but it didn't work either.
c_proc can exit when you type in its console windows "exit".
How can I send the message "exit" to the console window via PowerShell or cmd?
How can I kill c_proc?

Body:
This is the right code to kill the process c_proc. I found the parent process:

  Stop-Process -Name "start"
  Stop-Process -Name "c_proc"


问:
Merge tweets by minutes
Is it possible to merge tweets in 5 minutes intervalin R?

Bellow is a part of the tweets:

data[1:15 , ]

A tibble: 15 x 2

date                text

 1 2020-01-10 23:59:56 "Subscribe to @washingtonpost The Intersect by @abbyohlheiser for your fish content primer, then AMA because fis…

2 2020-01-10 23:59:55 "My latest EcoOptimism post asks \"Can We Be Hopeful\" about #ClimateChange in the new year. Inspiration from @G…

3 2020-01-10 23:59:47 "@MSNBC @maddow @washingtonpost @nytimes\n@CNN @CBSNews @NBCNews \nAny of y'all think this might be a slightly i…

4 2020-01-10 23:59:39 "Maybe if Golsteyn had done the right thing in the first place he wouldn't have to be concerned with getting his…

5 2020-01-10 23:59:39 ".@washingtonpost reports that today's #FireDrillFriday action was \"the start, organizers said, of broader move…

6 2020-01-10 23:59:38 "@washingtonpost Y’all are an army, alright. https://t.co/QZIYk9CTmv"

7 2020-01-10 23:56:29 "@GeorgeWillard9 @washingtonpost He was definitely a fan of killing brown and ppl with drone strikes.  Lots of M…

8 2020-01-10 23:59:38 "Thanks @petulad for this piece, covering both NoMa and the Union Station Great Hall.\nhttps://t.co/eGUPctNgoK"

9 2020-01-10 23:59:33 "\" 'Congress has long abdicated its responsibility as laid out in the Constitution to make the hard decisions w…

10 2020-01-10 23:58:45 "@OneEyeBlackJack @washingtonpost Yet another RW lie"

11 2020-01-10 23:59:24 "@chad_dawkins @washingtonpost Zero Facts"

12 2020-01-10 23:59:19 "Happy Friday!\n\nFacebook doesn’t want to face the facts https://t.co/dZykYez3Ty"

13 2020-01-10 23:59:08 "Surprise, Surprise: The DOJ’s Hillary Clinton Investigation Has Been a Bust\n\n#CorruptFourthEstate\n\n@CNN @MS…

14 2020-01-10 23:59:06 "@washingtonpost It's all a stinking commy plot. General Salami was the sacrificial lamb in plan hatch by Putin …

15 2020-01-10 23:58:49 "@ddale8 You mean Rudy Giuliani, Trump’s appointed cybersecurity expert, doesn't have it all under control? \n\n…

答:
You can use the function floor_date from the lubridate package for this. Just specify the minutes. Example below uses 1 minute, but change the 1 into 5 and you round down to the nearest 5 minutes.

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

df1 %>%
  mutate(date = floor_date(date, unit = "1 minutes")) %>%
  group_by(date) %>%
  summarise(text = paste(text, collapse = " "))

# A tibble: 3 x 2
  date                text
  <dttm>              <chr>
1 2020-01-10 23:56:00 "@GeorgeWillard9 @washingtonpost He was definitely a fan of killing brown and ppl with drone strikes. Lots of M…"
2 2020-01-10 23:58:00 "@OneEyeBlackJack @washingtonpost Yet another RW lie @ddale8 You mean Rudy Giuliani, Trump’s appointed cybersecurit~
3 2020-01-10 23:59:00 "Subscribe to @washingtonpost The Intersect by @abbyohlheiser for your fish content primer, then AMA because fis… M~
</code>```

OwnerDisplayName: sotnik

Title: Merge tweets by minutes

Body:
You can use the function floor_date from the lubridate package for this. Just specify the minutes. Example below uses 1 minute, but change the 1 into 5 and you round down to the nearest 5 minutes.

library(dplyr)
library(lubridate)

df1 %>%
  mutate(date = floor_date(date, unit = "1 minutes")) %>%
  group_by(date) %>%
  summarise(text = paste(text, collapse = " "))

# A tibble: 3 x 2
  date                text
  <dttm>              <chr>
1 2020-01-10 23:56:00 "@GeorgeWillard9 @washingtonpost He was definitely a fan of killing brown and ppl with drone strikes. Lots of M…"
2 2020-01-10 23:58:00 "@OneEyeBlackJack @washingtonpost Yet another RW lie @ddale8 You mean Rudy Giuliani, Trump’s appointed cybersecurit~
3 2020-01-10 23:59:00 "Subscribe to @washingtonpost The Intersect by @abbyohlheiser for your fish content primer, then AMA because fis… M~


问:
Visual Studio extension: how to get value of $ macro?
I'm writing an extension for Visual Studio 2019 and I need to resolve the values of solution/project macros, e.g. $(ProjectDir) and $(SolutionDir). Is there any way to do this from an extension?

答:
I need to resolve the values of solution/project macros, e.g.
  $(ProjectDir) and $(SolutionDir). Is there any way to do this from an
  extension?

As far as I know, ProjectDir and SolutionDir are just MSBuild properties and if you want to use $() to get the values of ProjectDir and SolutionDir, they can ony be recognized by MSBuild tool rather than vsix api. Using $ to get properties values can only be used in MSBuild.

To get the values of $(ProjectDir) and $(SolutionDir) directly, l suggest you can just use EnvDTE interface to get the values and it can also be used in VS2019.

Solution

1) try to reference EnvDTE.dll which exists in C:\Program Files (x86)\Microsoft Visual Studio\2019\xxxx(Community/Professional/Enterprise)\Common7\IDE\PublicAssemblies.

2) using namespace using EnvDTE;

3) add these code in the project which will obtain the values directly.

```<code> DTE dTE = Package.GetGlobalService(typeof(DTE)) as DTE;
 string solutiondir = dTE.Solution.FileName;  // the value of $(SolutionDir)
 Project project = dTE.Solution.Projects.Item(1);
 string projectdir = project.FileName; // the value of $(projectdir)
</code>```

The result is equal to the values of $(ProjectDir) and $(SolutionDir) in msbuild.

Body:
I need to resolve the values of solution/project macros, e.g.
  $(ProjectDir) and $(SolutionDir). Is there any way to do this from an
  extension?

As far as I know, ProjectDir and SolutionDir are just MSBuild properties and if you want to use $() to get the values of ProjectDir and SolutionDir, they can ony be recognized by MSBuild tool rather than vsix api. Using $ to get properties values can only be used in MSBuild.

To get the values of $(ProjectDir) and $(SolutionDir) directly, l suggest you can just use EnvDTE interface to get the values and it can also be used in VS2019.

Solution

1) try to reference EnvDTE.dll which exists in C:\Program Files (x86)\Microsoft Visual Studio\2019\xxxx(Community/Professional/Enterprise)\Common7\IDE\PublicAssemblies.

2) using namespace using EnvDTE;

3) add these code in the project which will obtain the values directly.

 DTE dTE = Package.GetGlobalService(typeof(DTE)) as DTE;
 string solutiondir = dTE.Solution.FileName;  // the value of $(SolutionDir)
 Project project = dTE.Solution.Projects.Item(1);
 string projectdir = project.FileName; // the value of $(projectdir)

The result is equal to the values of $(ProjectDir) and $(SolutionDir) in msbuild.


问:
jOOQ surrounds functions with quotes even if the setting is turned off
I've turned off adding quotes in the settings:

```<code>.withRenderQuotedNames(RenderQuotedNames.NEVER)
</code>```

But when I check the SQL log I still find double quotes in the output. jOOQ adds it to function calls:

```<code>select connect_by_isleaf LEAF, ms.MODULNAME, ms.MODULNAMESPRUNG,
       TOSCA.PA_BEZ."MODULTOSCA_MENUBEZ"(ms.MODULNAMESPRUNG,
       TOSCA.PA_BASIS."SPRACHE_USER"()) MENUBEZ, app.BEZKURZ
       from TOSCA.MODULSPRUNG ms
       join TOSCA.MODULTOSCA mt1 on (ms.MODULNAME = mt1.MODULNAME and mt1.MODULART = 'M')
       left outer join TOSCA.MODULTOSCA mt2 on mt2.MODULNAME = ms.MODULNAMESPRUNG
       left outer join TOSCA.APPLIKATION app on app.APPL = mt2.APPL
       start with ms.MODULNAME = 'X000'
       connect by (prior ms.MODULNAMESPRUNG = ms.MODULNAME and prior ms.FUNKTION = 'springen')
       order siblings by ms.SEQUENZ
</code>```

And procedure calls:

```<code>begin ? := TOSCA.PA_SPRACH."MSGALERT_TEXT" (P_MODULNAME => 'ALLE', P_LAUFNR => 0); end;
</code>```

Is this a bug? Or do I have to configure something else?

答:
A related bug has been reported recently. Perhaps a 3.12 regression: https://github.com/jOOQ/jOOQ/issues/9813. We're currently investigating this.

A workaround would be to implement an ExecuteListener and regex-replace all function identifiers \."(\w+)"\( by .$1(:

```<code>class WorkaroundFor9813 extends DefaultExecuteListener {
    static final Pattern P = Pattern.compile("\\.\"(\\w+)\"\\(");
    @Override
    public void renderEnd(ExecuteContext ctx) {
        ctx.sql(P.matcher(ctx.sql()).replaceAll(".$1("));
    }
}
</code>```

Of course, that's a workaround and it could match things by accident that it shouldn't...

Body:
I've turned off adding quotes in the settings:

.withRenderQuotedNames(RenderQuotedNames.NEVER)

But when I check the SQL log I still find double quotes in the output. jOOQ adds it to function calls:

select connect_by_isleaf LEAF, ms.MODULNAME, ms.MODULNAMESPRUNG,
       TOSCA.PA_BEZ."MODULTOSCA_MENUBEZ"(ms.MODULNAMESPRUNG,
       TOSCA.PA_BASIS."SPRACHE_USER"()) MENUBEZ, app.BEZKURZ
       from TOSCA.MODULSPRUNG ms
       join TOSCA.MODULTOSCA mt1 on (ms.MODULNAME = mt1.MODULNAME and mt1.MODULART = 'M')
       left outer join TOSCA.MODULTOSCA mt2 on mt2.MODULNAME = ms.MODULNAMESPRUNG
       left outer join TOSCA.APPLIKATION app on app.APPL = mt2.APPL
       start with ms.MODULNAME = 'X000'
       connect by (prior ms.MODULNAMESPRUNG = ms.MODULNAME and prior ms.FUNKTION = 'springen')
       order siblings by ms.SEQUENZ

And procedure calls:

begin ? := TOSCA.PA_SPRACH."MSGALERT_TEXT" (P_MODULNAME => 'ALLE', P_LAUFNR => 0); end;

Is this a bug? Or do I have to configure something else?

Body:
A related bug has been reported recently. Perhaps a 3.12 regression: https://github.com/jOOQ/jOOQ/issues/9813. We're currently investigating this.

A workaround would be to implement an ExecuteListener and regex-replace all function identifiers \."(\w+)"\( by .$1(:

class WorkaroundFor9813 extends DefaultExecuteListener {
    static final Pattern P = Pattern.compile("\\.\"(\\w+)\"\\(");
    @Override
    public void renderEnd(ExecuteContext ctx) {
        ctx.sql(P.matcher(ctx.sql()).replaceAll(".$1("));
    }
}

Of course, that's a workaround and it could match things by accident that it shouldn't...


问:
Calling Partial View JavaScript function
I have a partial view that contains a function named test().

The view is rendered correctly in the parent view.

I need to call test() from  a parent view JavaScript function.

When I try so, an error occurs: test() is not defined.

I am using ASP.net MVC 4.

答:
The issue you have is that the parent view does not know the function exists. And why would it?

Let's say you render the parent, it then looks at all the javascript functions it has access to but as the partial view with the function test() isn't created yet, it cannot find it, therefore you have that error.

A way to fix this issue would be to put the function test() in the parent.


问:
Help with this ragged array/substring program in C?
so, I have a ragged array (called names) of length 200. each pointer in the array points to a string that is no longer than 50 characters and has no white spaces. I also have a string given through user-input called inname, with length 50, inname will be one of the strings stored in names. I need to find a way to go through the strings in my ragged array and find the string with the largest substring overlap with inname, excluding inname itself as that will be in the file. If no string has an overlap then we print out "no recommendation".
I've been melting trying to puzzle this out for many hours now, helps? O:) SO basically, the program finds the name in the array with the largest substring overlap with inname.
will edit to provide additional info if you need it </p>

答:
You should probably start on the smaller problem of determining the size of the overlap between infunc and a single string.

Wikipedia goes over some algorithms for solving the longest common substring problem (including pseudocode!)


问:
Bound Method - Python
```<code>class Iloilo():
     def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

Iloilo = Iloilo()
Palawan = Palawan()

print(Iloilo.Population)
print(Palawan.Population)
</code>```

I am trying to print its value but I'm getting an error saying:
bound method

My question is, how can I compare both method results?

答:
You need to do:</p>

```<code>ilolio_instance = Iloilo()
palawan_instance = Palawan()
print(ilolio_instance.Population())
print(palawan_instance.Population())
</code>```

Title: Bound Method - Python

Body:
class Iloilo():
     def Population(self):
        population = 946146
        return population

class Palawan():
    def Population(self):
        population = 1104585
        return population

Iloilo = Iloilo()
Palawan = Palawan()

print(Iloilo.Population)
print(Palawan.Population)

I am trying to print its value but I'm getting an error saying:
bound method

My question is, how can I compare both method results?

Body:
You need to do:

ilolio_instance = Iloilo()
palawan_instance = Palawan()
print(ilolio_instance.Population())
print(palawan_instance.Population())


问:
Reduce video processing time using FFMpeg?
Users of my app upload videos to my server and I process them to create different qualities, thumbnails and gifs etc. Which are then useful for mobile and web apps. It takes almost 15-20 minutes for each video to be processed. I am using ffmpeg. How can I reduce my processing time ? </p>

答:
I can't comment so I ask here.

15-20 is to make thumbnail/gif from a video? If so, that's awfully a lot.

If you want HQ lossless then consider using x264 encoder with lossless_ultrafast preset to make videos.

```<code>ffmpeg -f x11grab -r 25 -s 1080x720 -i :0.0 -vcodec libx264 -vpre ultrafast yourfile.mkv
</code>```

If possible, use GPU to convert.

I might be wrong, but FFmpeg by default uses 1 thread. You could put multiple instances running to solve it.

Body:
I can't comment so I ask here.

15-20 is to make thumbnail/gif from a video? If so, that's awfully a lot.

If you want HQ lossless then consider using x264 encoder with lossless_ultrafast preset to make videos.

ffmpeg -f x11grab -r 25 -s 1080x720 -i :0.0 -vcodec libx264 -vpre ultrafast yourfile.mkv

If possible, use GPU to convert.

I might be wrong, but FFmpeg by default uses 1 thread. You could put multiple instances running to solve it.


问:
Multi-DC replication after connection loss
We have 2 DC, which are connected via an instable VPN, which loses connection once every 3 hours.

All data is written to DC A and replicated to DC B.
After one of this "connection loss" events there is data missing (window of the outage affected) on DC B.

My assumption was, that DC B will resume replication after connection has been reestablished and get all the missing data. Is that assumption wrong?

答:
Cassandra has following ways for replicating data:

hints - when hinted_handoff_enabled is set to true, the mutations are replayed when nodes are back online, but this happens only inside window defined by max_hint_window_in_ms (default is 3 hours), but this may also be affected by per table gc_grace_seconds setting (see this blog post for details).  But use of hints could be disabled on the per-DC basis (via hinted_handoff_disabled_datacenters). Also, hints aren't replayed momentarily, as they are throttled by hinted_handoff_throttle_in_kb & max_hints_delivery_threads parameters.

repairs - need to be executed explicitly, but could be more effective than hints, especially because you can run it on specific tables;

read repairs - for multi DC will work only if you're using something like QUORUM for reading the data...

If the hints are enabled, and you still miss the data - check that hints are already replayed, or they are still replaying - there are metrics that shows how many hints on disk, etc.

If the problem happens periodically, and you can detect it, then maybe explicit repairs will work faster - but in this case you'll need to disable cross-DC hints, so the nodes won't be receiving the data twice...


问:
Standard deviation MPG

I am getting an error column 'mpg' unknown? I am trying to calculate the stdev of the mpg, a computed column

```<code>SELECT Date, Vehicle, Quantity as [Ltrs],
    LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage,
    OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles],
    (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG],
    case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10
        then 1 else 0 end as [Anomaly],
    stdev(MPG)
FROM [Fleet].[DwhTriscanChargeouts]
where vehicle='DE63VAM'
order by 2, 1
</code>```

答: SELECT columns are computed in unknown order, so you can not use computed column in same SELECT statement. You can use CTE or subquery.</p>

Title: Standard deviation MPG

Body:
I am getting an error column 'mpg' unknown? I am trying to calculate the stdev of the mpg, a computed column

SELECT Date, Vehicle, Quantity as [Ltrs],
    LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) AS previousmileage,
    OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date) as [Miles],
    (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) as [MPG],
    case when (OdoReadingMiles-LAG(OdoReadingMiles, 1) OVER (PARTITION BY Vehicle ORDER BY Date)) / (Quantity/4.544) not between 2 and 10
        then 1 else 0 end as [Anomaly],
    stdev(MPG)
FROM [Fleet].[DwhTriscanChargeouts]
where vehicle='DE63VAM'
order by 2, 1


问:
How to setup SVG's viewbox, width and height which is scalable and responsive
I am new to SVG design.
Struggling to scale, zoom in/out with container and make it responsive to all the devices.

Is it even possible to design SVG in a way that fits in all the devices and handles browsing zoom in/out functionality?

I have tried to play with viewport and viewbox for each breakpoint.

e.g. for Desktop, I have SVG to fit in a container. should scale and zoom in and out with the container(svgClass).

```<code>.svgClass {
 background-image: url('assets/svg/desktop-svg.svg');
 width: "100%";
 height: 800px;
 position: absolute;
}

<div class="svgClass"></div>
</code>```

Sample SVG

---desktop-svg.svg---

```<code><svg width="1400" height="800" viewbox="0 0 1121 641">
-----
</svg>
</code>```

It fits well with 100% browser zoom, but if in case of zoom in and zoom out SVG gets displaced.

To handle zoom in, I have increased viewport height="1400" and width="800" compared to viewbox (0 0 1121 641). which worked fine but zoom out still fails.

Had tried out: Removed width and height from viewport, also tried with setting auto and 100% with width and height. No success.

How to design SVG which can scale with the container and stay responsive, second do we need to setup viewport and viewbox for each device?

答: Remove your "width" and "height" attributes, and just work with the viewBox numbers. Now your SVG will auto-fit inside whatever you're using as its container (a DIV?), otherwise your width and height are fighting with the DIV's width and height.</p>

Body:
I am new to SVG design.
Struggling to scale, zoom in/out with container and make it responsive to all the devices.

Is it even possible to design SVG in a way that fits in all the devices and handles browsing zoom in/out functionality?

I have tried to play with viewport and viewbox for each breakpoint.

e.g. for Desktop, I have SVG to fit in a container. should scale and zoom in and out with the container(svgClass).

.svgClass {
 background-image: url('assets/svg/desktop-svg.svg');
 width: "100%";
 height: 800px;
 position: absolute;
}

Sample SVG

---desktop-svg.svg---

<svg width="1400" height="800" viewbox="0 0 1121 641">
-----
</svg>

It fits well with 100% browser zoom, but if in case of zoom in and zoom out SVG gets displaced.

To handle zoom in, I have increased viewport height="1400" and width="800" compared to viewbox (0 0 1121 641). which worked fine but zoom out still fails.

Had tried out: Removed width and height from viewport, also tried with setting auto and 100% with width and height. No success.

How to design SVG which can scale with the container and stay responsive, second do we need to setup viewport and viewbox for each device?


问:
How does character array with single quote affects an character array without the quotes?
```<code>char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };
</code>```

what is the difference? It does not raise any errors. why?

答:
```<code>char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };
</code>```

what is the difference?

The difference is that 1 and '1' have different values. 1 has the value 1 and '1' has the value of the numeric character code for the character '1'. Assuming the character set is based on ASCII, the ASCII character '1' has the value 49, so 1 will have value 1 and '1' will have value 49.

It does not raise any errors. why?

Both 1 and '1' (ASCII 49) are in the range of values supported by char, so there is no reason to raise an error or a warning.

Body:
char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };

what is the difference? It does not raise any errors. why?

Body:
char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };

what is the difference?

The difference is that 1 and '1' have different values. 1 has the value 1 and '1' has the value of the numeric character code for the character '1'. Assuming the character set is based on ASCII, the ASCII character '1' has the value 49, so 1 will have value 1 and '1' will have value 49.

It does not raise any errors. why?

Both 1 and '1' (ASCII 49) are in the range of values supported by char, so there is no reason to raise an error or a warning.


问:
Saving presto query output to a file
I'm pretty new to PostgreSQL, but I have to query some results using psql in an interactive command line session. I am connecting through a cluster and I would like to extract the output of the query into a file for further analysis.

The command I use to connect is psql -h hostname.with.dbs -p 5432 -U my-username and inside I do the query. But it is not clear to me how to pipe that into a file in my user folder in the machine used to connect to Presto.

If I have to add more details, let me know, as I am not an expert and might forgot to add important information. Thank you all!

答: I found a solution to that. Basically appending \g file_name; at the end of the query. It saves the file in the directory where I launched the command to connect to the database. I didn't try to add full path to the file name, but I assume it would work as well.

Title: Saving presto query output to a file