问:
How to exclude a @Configuration class when using @WebMvcTest with spring-boot?
I am writing junits for a rest controller. I want only minimal context to be loaded which is related to the controller and I think that is how @WebMvcTest loads the context. But the junit is loading complete Spring context and it is failing as some of the beans can not be created.

I have searched and read through many questions on stackoverflow and none of the solutions worked to exclude specific configuration. How can I load a minimal context when writing junits for controllers? Or is there any way to exclude some configuration classes? I am using Spring-boot 2.2.2.RELEASE, Java 8 and Junit 4.

Junit (where I have tried to exclude loading of some beans and configurations but it doesn't work):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = OrderController.class, excludeFilters = {@Filter(classes = Configuration.class), @Filter(type = FilterType.REGEX, pattern = "com\\.foo\\..*")})
@TestPropertySource(properties = { "spring.cloud.config.server.bootstrap:false" })
public class OrderControllerTest {

    @MockBean
    private OrderService orderService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/internal/order/123"));
        // Further code to verify the response
    }

}
```

<p>Controller</p>

<pre class="lang-java prettyprint-override"><code>@Slf4j
@Validated
@RestController
@RequestMapping("/internal")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/order/{orderId}", produces = { MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<RegularContributionOrder> retrieveRegularContributionOrder(@NotNull @PathVariable("orderId") String orderId)
            throws OrderNotFoundException {

        RegularContributionOrder order = orderService.retrieve(orderId);

        return new ResponseEntity<RegularContributionOrder>(order, HttpStatus.OK);
    }
}
</code>```

Configuration class which I want to exclude from context loading

@Slf4j
@Configuration
@EnableAspectJAutoProxy
@ImportResource({ "classpath:spring/service-config-one.xml", "classpath:spring/service-config-two.xml" })
public class OrderServiceConfig {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:resourcebundles/error-messages.properties");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        return mapper;
    }
}
```

<p>Spring boot main class:</p>

<pre class="lang-java prettyprint-override"><code>@EnableJms
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "com.foo.services", "com.bar" })
@SpringBootApplication(exclude = { SomeConfiguration.class})
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(BootApplication .class);
    }

    public static void main(final String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SpringApplication.run(BootApplication.class, args);
    }
}
</code>```

答:
Your use of @ComponentScan has disabled the filters that are used by @WebMvcTest to limit the types of components that are found by scanning.

You should remove @ComponentScan from your main application class and use the basePackages attribute on @SpringBootApplication instead.

You should also move @EnableJms and @EnableAspectJAutoProxy to a separate @Configuration class so that they are not enabled when using @WebMvcTest. Alternatively, you may be able to remove them entirely as they are covered by Spring Boot’s auto-configuration.

Body:
I am writing junits for a rest controller. I want only minimal context to be loaded which is related to the controller and I think that is how @WebMvcTest loads the context. But the junit is loading complete Spring context and it is failing as some of the beans can not be created.

I have searched and read through many questions on stackoverflow and none of the solutions worked to exclude specific configuration. How can I load a minimal context when writing junits for controllers? Or is there any way to exclude some configuration classes? I am using Spring-boot 2.2.2.RELEASE, Java 8 and Junit 4.

Junit (where I have tried to exclude loading of some beans and configurations but it doesn't work):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = OrderController.class, excludeFilters = {@Filter(classes = Configuration.class), @Filter(type = FilterType.REGEX, pattern = "com\\.foo\\..*")})
@TestPropertySource(properties = { "spring.cloud.config.server.bootstrap:false" })
public class OrderControllerTest {

    @MockBean
    private OrderService orderService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/internal/order/123"));
        // Further code to verify the response
    }

}

Controller

@Slf4j
@Validated
@RestController
@RequestMapping("/internal")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/order/{orderId}", produces = { MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<RegularContributionOrder> retrieveRegularContributionOrder(@NotNull @PathVariable("orderId") String orderId)
            throws OrderNotFoundException {

        RegularContributionOrder order = orderService.retrieve(orderId);

        return new ResponseEntity<RegularContributionOrder>(order, HttpStatus.OK);
    }
}

Configuration class which I want to exclude from context loading

@Slf4j
@Configuration
@EnableAspectJAutoProxy
@ImportResource({ "classpath:spring/service-config-one.xml", "classpath:spring/service-config-two.xml" })
public class OrderServiceConfig {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:resourcebundles/error-messages.properties");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        return mapper;
    }
}

Spring boot main class:

@EnableJms
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "com.foo.services", "com.bar" })
@SpringBootApplication(exclude = { SomeConfiguration.class})
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(BootApplication .class);
    }

    public static void main(final String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SpringApplication.run(BootApplication.class, args);
    }
}


来源: stackexchange

问:
How to pop-up message on the exact card where it's clicked?
I'm trying to show some elements in a list of cards and when I click on a card, I need to show a pop-up message on that exact card. Right now it's showing up the top card. But I need to it to show up on the card I click.

Here's my html code for showing card elements and pop-up:

```<code>
<a class="external" ng-repeat="card in cardData" ng-click="popUpFunction()">
  <div class="card">
      <img class="card-image" src="{{card.thumbNail_image}}" alt="">
      <div class="popup">
          <span class="popuptext" id="myPopup">A Simple Popup!</span>
      </div>
      <div class="card-infos">
          <h2 class="card-title">{{card.contentDescription}}</h2>
      </div>
   </div>
</a>

</code>```

Here's the css code:

```<code>.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  height:0px;
  width:0px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* The actual popup */
.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;

  margin-left: 80px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {opacity: 0;}
  to {opacity: 1;}
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity:1 ;}
}
</code>```

And here's the js code:

```<code>$scope.popUpFunction = function () {
   var popup = document.getElementById("myPopup");
   popup.classList.toggle("show");
}
</code>```

答:
To solve the issue, I passed the index of the card as a parameter and checked it in ng-if

```<code><a class="external" ng-repeat="card in cardData" ng-click="popUpFunction()">
  <div class="card">
      <img class="card-image" src="{{card.thumbNail_image}}" alt="">
      <div class="popup">
          <span class="popuptext" id="myPopup" ng-if="popUpIndex==$index">A Simple Popup!</span>
      </div>
      <div class="card-infos">
          <h2 class="card-title">{{card.contentDescription}}</h2>
      </div>
   </div>
</a>
</code>```

And here's the change in script file:

```<code>
$scope.popUpIndex = 0;
$scope.modalFunction = function (ind) {
    console.log(ind);
    $scope.popUpIndex = ind;
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to show some elements in a list of cards and when I click on a card, I need to show a pop-up message on that exact card. Right now it's showing up the top card. But I need to it to show up on the card I click.

Here's my html code for showing card elements and pop-up:

          A Simple Popup!

{{card.contentDescription}}

Here's the css code:

.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  height:0px;
  width:0px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* The actual popup */
.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;

  margin-left: 80px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {opacity: 0;}
  to {opacity: 1;}
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity:1 ;}
}

And here's the js code:

$scope.popUpFunction = function () {
   var popup = document.getElementById("myPopup");
   popup.classList.toggle("show");
}

Body:
To solve the issue, I passed the index of the card as a parameter and checked it in ng-if

<a class="external" ng-repeat="card in cardData" ng-click="popUpFunction()">
  <div class="card">
      <img class="card-image" src="{{card.thumbNail_image}}" alt="">
      <div class="popup">
          <span class="popuptext" id="myPopup" ng-if="popUpIndex==$index">A Simple Popup!</span>
      </div>
      <div class="card-infos">
          <h2 class="card-title">{{card.contentDescription}}</h2>
      </div>
   </div>
</a>

And here's the change in script file:

$scope.popUpIndex = 0;
$scope.modalFunction = function (ind) {
    console.log(ind);
    $scope.popUpIndex = ind;
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}


问:
Elegant PL/SQL to compare two numbers with different amount of decimal places
I need a function to compare two numbers so that 10.12432 = 10.124 and 10.12432 != 10.123. That is the more accurate number needs to be rounded according to the decimal places of the less accurate one.

The following function seems to do what I need (Edited as per Noel's comment):

```<code>function eq(number_1 in number, number_2 in number) return boolean is
    string_1 varchar2(100);
    string_2 varchar2(100);

    num_1    number;
    num_2    number;

    len      number;
begin
    string_1 := to_char(number_1, 'FM99999999999999999999999999999.99999999999999999999999999999');
    string_2 := to_char(number_2, 'FM99999999999999999999999999999.99999999999999999999999999999');

    string_1 := regexp_replace(string_1, '.*(\..*)', '\1');
    string_2 := regexp_replace(string_2, '.*(\..*)', '\1');

    len   := least(length(string_1), length(string_2)) - 1;

    num_1 := round(number_1, len);
    num_2 := round(number_2, len);

    return num_1 = num_2;

end eq;
</code>```

But, imho, is not the most satisfying approach. Is there a better solution, notably one without resorting to strings?

答:
I realize this is an old (very old) post, but I've seen lately several questions concerning floating point values. So when I ran across this I dredge up an old routine I had for making floating point comparisons. Hopefully this will be useful to future searchers. BTW It does NOT require conversion to strings as it compares relative values.

```<code>create or replace function compare_float(
                            float_value_1  double precision
                          , float_value_2  double precision
                          , delta_value    double precision default 1.0e-6
                          )
 return integer
 is
 /*
    Name:          Compare_Float
    Author:        Belayer
    Date Written:  22-Jan-2009

    Floating point number are ALWAYS estimates as there is no way to precisely a
    decimal base 10 number in binary. Therefore comparing 2 floating points of
    for equality is a risky proposition at best.

    While the above is true, we can at least inquire as to the difference being
    enough as to not matter and then consider the values as equal even though
    in the computed since they may not be.

    This routine implements the 'close enough' comparison to give the relative
    magnitude relationship between 2 floating point variables.

    Parameters:
      Float_Value_1. The first of 2 floating point values to be compared.
      Float_Value_2. The second of he 2 floating point values to be compared.
      Delta_Value.   The amount of the 2 values can differ and still be considered
                     to be equal.  Default value 10^-6 (.000001) This value can be
                     overridden on each call to the procedure.
    Return Values:
      -1 Float_Value_1 is less than Float_Value_2.
       0 Float_Value_1 equals Float_Value_2 within specified Datla_Value.
       1 Float_Value_1 is greater than Float_Value_2.

*/
     delta_diff           double precision;
     compare_float_result integer;
begin
    delta_diff := float_value_1 - float_value_2;
    if abs(delta_diff) < delta_value
    then
        compare_float_result := 0;
    else
        compare_float_result := sign(delta_diff);
    end if;
    return compare_float_result;
end compare_float;
</code>```

The following tests the same values with different values specified for the delta_value, the allowed difference between the values to still be considered equal. Test run with values 1.0e-6(default),1.0e-3, and 1.0e-7.

```<code>-- test 1.3e-6 (default)
with vals (f,s,e) as
     ( select 10.12432,  10.124,      1  from dual union all
       select 10.124,    10.124001,  -1  from dual union all
       select 1.0000124,  1.0000120,  0  from dual union all
       select 1.000124,   1.000120,   1  from dual union all
       select 1.11000015, 1.12000015,-1  from dual union all
       select 0.0000010,  0.00000011, 0  from dual
     )
select compare_float(f,s) result, e expecting
  from vals;
-- test 1.3e-3 (default)
with vals (f,s,e) as
     ( select 10.12432,  10.124,      0  from dual union all
       select 10.124,    10.124001,   0  from dual union all
       select 1.0000124,  1.0000120,  0  from dual union all
       select 1.000124,   1.000120,   0  from dual union all
       select 1.11000015, 1.12000015,-1  from dual union all
       select 0.0000010,  0.00000011, 0  from dual
     )
select compare_float(f,s, 1.0e-3) result, e expecting
  from vals; '
-- test 1.3e-7
with vals (f,s,e) as
     ( select 10.12432,  10.124,      1  from dual union all
       select 10.124,    10.124001,  -1  from dual union all
       select 1.0000124,  1.0000120,  1  from dual union all
       select 1.000124,   1.000120,   1  from dual union all
       select 1.11000015, 1.12000015,-1  from dual union all
       select 0.0000010,  0.00000011,-1  from dual
     )
select compare_float(f,s, 1.0e-7) result, e expecting
  from vals;
</code>```

Well it's there is anyone wants it. Note: This routine was sourced from a much older Fortran.

ContentLicense: CC BY-SA 3.0

Body:
I need a function to compare two numbers so that 10.12432 = 10.124 and 10.12432 != 10.123. That is the more accurate number needs to be rounded according to the decimal places of the less accurate one.

The following function seems to do what I need (Edited as per Noel's comment):

function eq(number_1 in number, number_2 in number) return boolean is
    string_1 varchar2(100);
    string_2 varchar2(100);

    num_1    number;
    num_2    number;

    len      number;
begin
    string_1 := to_char(number_1, 'FM99999999999999999999999999999.99999999999999999999999999999');
    string_2 := to_char(number_2, 'FM99999999999999999999999999999.99999999999999999999999999999');

    string_1 := regexp_replace(string_1, '.*(\..*)', '\1');
    string_2 := regexp_replace(string_2, '.*(\..*)', '\1');

    len   := least(length(string_1), length(string_2)) - 1;

    num_1 := round(number_1, len);
    num_2 := round(number_2, len);

    return num_1 = num_2;

end eq;

But, imho, is not the most satisfying approach. Is there a better solution, notably one without resorting to strings?

Body:
I realize this is an old (very old) post, but I've seen lately several questions concerning floating point values. So when I ran across this I dredge up an old routine I had for making floating point comparisons. Hopefully this will be useful to future searchers. BTW It does NOT require conversion to strings as it compares relative values.

create or replace function compare_float(
                            float_value_1  double precision
                          , float_value_2  double precision
                          , delta_value    double precision default 1.0e-6
                          )
 return integer
 is
 /*
    Name:          Compare_Float
    Author:        Belayer
    Date Written:  22-Jan-2009

    Floating point number are ALWAYS estimates as there is no way to precisely a
    decimal base 10 number in binary. Therefore comparing 2 floating points of
    for equality is a risky proposition at best.

    While the above is true, we can at least inquire as to the difference being
    enough as to not matter and then consider the values as equal even though
    in the computed since they may not be.

    This routine implements the 'close enough' comparison to give the relative
    magnitude relationship between 2 floating point variables.

    Parameters:
      Float_Value_1. The first of 2 floating point values to be compared.
      Float_Value_2. The second of he 2 floating point values to be compared.
      Delta_Value.   The amount of the 2 values can differ and still be considered
                     to be equal.  Default value 10^-6 (.000001) This value can be
                     overridden on each call to the procedure.
    Return Values:
      -1 Float_Value_1 is less than Float_Value_2.
       0 Float_Value_1 equals Float_Value_2 within specified Datla_Value.
       1 Float_Value_1 is greater than Float_Value_2.

*/
     delta_diff           double precision;
     compare_float_result integer;
begin
    delta_diff := float_value_1 - float_value_2;
    if abs(delta_diff) < delta_value
    then
        compare_float_result := 0;
    else
        compare_float_result := sign(delta_diff);
    end if;
    return compare_float_result;
end compare_float;

The following tests the same values with different values specified for the delta_value, the allowed difference between the values to still be considered equal. Test run with values 1.0e-6(default),1.0e-3, and 1.0e-7.

-- test 1.3e-6 (default)
with vals (f,s,e) as
     ( select 10.12432,  10.124,      1  from dual union all
       select 10.124,    10.124001,  -1  from dual union all
       select 1.0000124,  1.0000120,  0  from dual union all
       select 1.000124,   1.000120,   1  from dual union all
       select 1.11000015, 1.12000015,-1  from dual union all
       select 0.0000010,  0.00000011, 0  from dual
     )
select compare_float(f,s) result, e expecting
  from vals;
-- test 1.3e-3 (default)
with vals (f,s,e) as
     ( select 10.12432,  10.124,      0  from dual union all
       select 10.124,    10.124001,   0  from dual union all
       select 1.0000124,  1.0000120,  0  from dual union all
       select 1.000124,   1.000120,   0  from dual union all
       select 1.11000015, 1.12000015,-1  from dual union all
       select 0.0000010,  0.00000011, 0  from dual
     )
select compare_float(f,s, 1.0e-3) result, e expecting
  from vals; '
-- test 1.3e-7
with vals (f,s,e) as
     ( select 10.12432,  10.124,      1  from dual union all
       select 10.124,    10.124001,  -1  from dual union all
       select 1.0000124,  1.0000120,  1  from dual union all
       select 1.000124,   1.000120,   1  from dual union all
       select 1.11000015, 1.12000015,-1  from dual union all
       select 0.0000010,  0.00000011,-1  from dual
     )
select compare_float(f,s, 1.0e-7) result, e expecting
  from vals;

Well it's there is anyone wants it. Note: This routine was sourced from a much older Fortran.


问:
Replacing whole XML tree in Python
How to replace a whole XML tree?
Let's say I have a file that looks like:

```<code><root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem3>
       <sub1>'something else here'</sub1>
       <sub2>'blablabla'</sub2>
    </elem3>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>
</code>```

And I also have another xml file that would be an alternative for elem3 that looks like:

```<code>    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
</code>```

What I need is to replace elem3 with NewElem, that results in:

```<code><root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>
</code>```

I am using xml.etree.ElementTree and tried to append it but I end up getting the NewElem in the end, after </folder>. I could not remove the elem3 of the updated xml file.

I tried to append it using this:

```<code>import xml.etree.ElementTree as ET

tree = ET.parse('base.xml')
baseroot = tree.getroot()
tree2 = ET.parse('new.xml')
newroot = tree2.getroot()

old_element = baseroot.findall('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)
</code>```

With that the NewElem gets appended after folder, and I need in the same place where elem3 was, or at least inside <folder>
Also, when removing I get an error:
TypeError: remove() argument must be xml.etree.ElementTree.Element, not list
If I change to

```<code>old_element = baseroot.find('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)
</code>```

I get very similar error: ValueError: list.remove(x): x not in list

答:
The below is using the lxml package, a superior XML package to ElementTree.
You can find the index of the node you'd like to replace using the parent element's index(element) method.

Once you got that, you can use insert(index, element) from the parent and insert the new node in the position of the old.

The next thing is delete the old node via the remove(element) method

Example 'p' is the parent element, a is the child node of p to be replaced and b is the new child node:

```<code>p.insert(p.index(a), b) # insert b before a
p.remove(a)
</code>```

With ElementTree, you'll need to find the index of the old element first:

```<code>p = et.Element('parent') # parent node
a = et.Element('child1') # this is the child node to be replaced
b = et.Element('child2') # this is the new child node
p.append(a)
index = list(p).index(a)
p[index] = b
</code>```

Title: Replacing whole XML tree in Python

Body:
How to replace a whole XML tree?
Let's say I have a file that looks like:

<root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem3>
       <sub1>'something else here'</sub1>
       <sub2>'blablabla'</sub2>
    </elem3>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>

And I also have another xml file that would be an alternative for elem3 that looks like:

    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>

What I need is to replace elem3 with NewElem, that results in:

<root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>

I am using xml.etree.ElementTree and tried to append it but I end up getting the NewElem in the end, after </folder>. I could not remove the elem3 of the updated xml file.

I tried to append it using this:

import xml.etree.ElementTree as ET

tree = ET.parse('base.xml')
baseroot = tree.getroot()
tree2 = ET.parse('new.xml')
newroot = tree2.getroot()

old_element = baseroot.findall('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)

With that the NewElem gets appended after folder, and I need in the same place where elem3 was, or at least inside <folder>
Also, when removing I get an error:
TypeError: remove() argument must be xml.etree.ElementTree.Element, not list
If I change to

old_element = baseroot.find('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)

I get very similar error: ValueError: list.remove(x): x not in list

Body:
The below is using the lxml package, a superior XML package to ElementTree.
You can find the index of the node you'd like to replace using the parent element's index(element) method.

Once you got that, you can use insert(index, element) from the parent and insert the new node in the position of the old.

The next thing is delete the old node via the remove(element) method

Example 'p' is the parent element, a is the child node of p to be replaced and b is the new child node:

p.insert(p.index(a), b) # insert b before a
p.remove(a)

With ElementTree, you'll need to find the index of the old element first:

p = et.Element('parent') # parent node
a = et.Element('child1') # this is the child node to be replaced
b = et.Element('child2') # this is the new child node
p.append(a)
index = list(p).index(a)
p[index] = b


问:
jQuery does not find IMG component by its ID
I have a webpage which contains such code:

```<code><img class="img-qrcode" id="img_123.000.00.01"
     src="http://localhost:7777/data/code_img\123.000.00.01.png"
     alt="./data/code_img\123.000.00.01.png" style="display:none">
</code>```

I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:

```<code>$("#img_123.000.00.01")
</code>```

The added screenshot shows that it returns an empty array.

Why does it not find the element with ID ?

答:
The a . character has special meaning in a selector (it starts a class selector) so you need to escape it.  (Remember to escape the slash character in a string literal).

Generally it is easier to just avoid using . chapters in an id.

Body:
I have a webpage which contains such code:

I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:

$("#img_123.000.00.01")

The added screenshot shows that it returns an empty array.

Why does it not find the element with ID ?


问:
Firebase Querying many child based on one attribute value from one of them
My Firebase storge

from the image above, I want to get all the milk powder based on the barcode of one of them

```<code>var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)
</code>```

where 'read' is the barcode number I only get one item,
I want instead to get all the item type and wight based on barcode number
like:
 SELECT itemWieght, itemName, itemPrice FROM barcode WHERE itemBarcode.itemType = itemType or something like this

EDIT :

here is my part of the code if that's helps

```<code>var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)

                //Adapter
                query.addValueEventListener(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {

                    }

                    override fun onDataChange(p0: DataSnapshot) {
                        myBarcodeArray?.clear()
                        for (r in p0.children) {
                            var infoHolder = r.getValue(BarcodeInfo::class.java)

                            myBarcodeArray!!.add(infoHolder!!)
                        }
                        val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                        view.listOfBarcodeResult.adapter = infoAdapter
                    }
                })
</code>```

EDIT 2:
I tried also to use 2 queries, but it shows empty results

```<code>myDataRef?.child("Barcode")?.orderByChild("itemBarcode")?.equalTo(read)?.addListenerForSingleValueEvent(object : ValueEventListener{
                    override fun onCancelled(p0: DatabaseError) {

                    }
                    override fun onDataChange(p0: DataSnapshot) {
                        var result = p0.getValue(BarcodeInfo::class.java)
                        myDataRef?.child("Barcode")?.orderByChild(result?.itemWeight.toString())?.equalTo(read)?.addValueEventListener(object : ValueEventListener{
                            override fun onCancelled(p0: DatabaseError) {
                            }
                            override fun onDataChange(p0: DataSnapshot) {
                                for (r in p0.children){
                                    var holder = r.getValue(BarcodeInfo::class.java)
                                    myBarcodeArray!!.add(holder!!)
                                }
                                val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                                view.listOfBarcodeResult.adapter = infoAdapter
                            }
                        })
                    }
                })
</code>```

答:
If you want get all value inside an item (data snapshot) that mean you should catch a whole of that item so add your query to ListenerForSingleValueEvent

Reference : Query firebase data in Android

Body:
My Firebase storge

from the image above, I want to get all the milk powder based on the barcode of one of them

var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)

where 'read' is the barcode number I only get one item,
I want instead to get all the item type and wight based on barcode number
like:
 SELECT itemWieght, itemName, itemPrice FROM barcode WHERE itemBarcode.itemType = itemType or something like this

EDIT :

here is my part of the code if that's helps

var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)

                //Adapter
                query.addValueEventListener(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {

                    }

                    override fun onDataChange(p0: DataSnapshot) {
                        myBarcodeArray?.clear()
                        for (r in p0.children) {
                            var infoHolder = r.getValue(BarcodeInfo::class.java)

                            myBarcodeArray!!.add(infoHolder!!)
                        }
                        val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                        view.listOfBarcodeResult.adapter = infoAdapter
                    }
                })

EDIT 2:
I tried also to use 2 queries, but it shows empty results

myDataRef?.child("Barcode")?.orderByChild("itemBarcode")?.equalTo(read)?.addListenerForSingleValueEvent(object : ValueEventListener{
                    override fun onCancelled(p0: DatabaseError) {

                    }
                    override fun onDataChange(p0: DataSnapshot) {
                        var result = p0.getValue(BarcodeInfo::class.java)
                        myDataRef?.child("Barcode")?.orderByChild(result?.itemWeight.toString())?.equalTo(read)?.addValueEventListener(object : ValueEventListener{
                            override fun onCancelled(p0: DatabaseError) {
                            }
                            override fun onDataChange(p0: DataSnapshot) {
                                for (r in p0.children){
                                    var holder = r.getValue(BarcodeInfo::class.java)
                                    myBarcodeArray!!.add(holder!!)
                                }
                                val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                                view.listOfBarcodeResult.adapter = infoAdapter
                            }
                        })
                    }
                })


问:
Firefox doesn't show http answer status code and duplicates all AJAX requests
Can someone help with FF? It doesn't show AJAX requests' status codes (in F12 dev tools window). Also it duplicates all AJAX calls to server (save something in database and it will be saved twice), but shows that made only one request. The reason is HTTPS connection. All is good by HTTP, but with SSL by HTTPS problem appears again.
Server is IIS under Win Server 2019.
Also problem can be in null status code. Pages are returned without status code by https. By http it is ok, status 200 is returned and no problem with AJAX duplicate</p>

答: So at last I found the answer. In IIS in your page settings you should go to SSL options and there will be radio-butoon what to do with client certificate. Choose "Ignore" ("Accept" was by default) and Firefox starts working. Pages' status codes comes back, no AJAX duplicates.</p>


问:
I have problem with hebrew in Mysql. I use with visualstudio10, connector and linq. what can i do?
the query works well only in english.
*the tables and all DB is utf-8(utf-8_general_ci)
I see hebrew in the db(phpmyadmin or mysql Workbench)
the problem is to read VALUES from the db.

*I use linqtosql to do the query and the model is EntityFramework.

this is a sample:

```<code>        using (dbEntities model = new dbEntities())
        {

            List<string> lstNoth = new List<string>();
            var query = from t in model.producttype
                        where t.ProductTypeName.Contains(text)
                        select new
                        {
                           t.ProductTypeName
                        };

            foreach (var item in query) //value in hebrew didn't get inside.
            {
                lstNoth.Add(item.ProductTypeName);
            }
        }
</code>```

答:
I found the solution. I add the sentence- charset=utf8 to the connectionString in WebConfig.

```<code>database=XXXX;charset=utf8
</code>```

The problem solved. Thanks anyway for your help.

Body:
the query works well only in english.
*the tables and all DB is utf-8(utf-8_general_ci)
I see hebrew in the db(phpmyadmin or mysql Workbench)
the problem is to read VALUES from the db.

*I use linqtosql to do the query and the model is EntityFramework.

this is a sample:

        using (dbEntities model = new dbEntities())
        {

            List<string> lstNoth = new List<string>();
            var query = from t in model.producttype
                        where t.ProductTypeName.Contains(text)
                        select new
                        {
                           t.ProductTypeName
                        };

            foreach (var item in query) //value in hebrew didn't get inside.
            {
                lstNoth.Add(item.ProductTypeName);
            }
        }

Body:
I found the solution. I add the sentence- charset=utf8 to the connectionString in WebConfig.

database=XXXX;charset=utf8

The problem solved. Thanks anyway for your help.


问:
Wrap fetch function for token when using reactn
I am using reactn to store the access and refresh tokens from logging in.  Normally, to do an API call, I would do something like the following...

```<code>fetch('/api/options/1/', {
    method: 'PUT',
    credentials: 'same-origin',
    body: JSON.stringify(state),
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${auth.access.token}`,
    },
})
</code>```

But since the access token expires quickly, this can easily fail.  What I wanted to do is wrap the fetch function in a function like 'callAPI(url, options)' that would do the following:

Check if access token is expired (global.auth.access.exp variable).  If expired, first call /api/auth/token/refresh passing the refresh token to get a new access token

Send fetch with the Authorization header added automatically

Return response promise

What would be the best way to go about this when the auth information is stored in the reactn global state, so that in any component I could just import a function callAPI and do the API call?

答:
Considering you are using async/await syntax you can do it using below:

```<code>const fetchWrapper = async (URI, options) => {
    const auth = await fetch('/api/auth/token/refresh');
    const newOptions = {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${auth.access.token}`,
        },
    }
    const res = await fetch(URI, newOptions);
    return res;
}
</code>```

if you are not using async/await you can use below:

```<code>const fetchWrapper = (URI, options) => {
    const promise = new Promise((resolve, reject) => {
        fetch('/api/auth/token/refresh').then((auth) => {
            const newOptions = {
                ...options,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${auth.access.token}`,
                },
            }
            fetch(URI, newOptions).then(res => {
                resolve(res);
            }).catch((err) => {
                reject(err);
            });
        }).catch((err) => {
            reject(err);
        });
    })

    return promise;
}
</code>```

Body:
I am using reactn to store the access and refresh tokens from logging in.  Normally, to do an API call, I would do something like the following...

fetch('/api/options/1/', {
    method: 'PUT',
    credentials: 'same-origin',
    body: JSON.stringify(state),
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${auth.access.token}`,
    },
})

But since the access token expires quickly, this can easily fail.  What I wanted to do is wrap the fetch function in a function like 'callAPI(url, options)' that would do the following:

Check if access token is expired (global.auth.access.exp variable).  If expired, first call /api/auth/token/refresh passing the refresh token to get a new access token

Send fetch with the Authorization header added automatically

Return response promise

What would be the best way to go about this when the auth information is stored in the reactn global state, so that in any component I could just import a function callAPI and do the API call?

Body:
Considering you are using async/await syntax you can do it using below:

const fetchWrapper = async (URI, options) => {
    const auth = await fetch('/api/auth/token/refresh');
    const newOptions = {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${auth.access.token}`,
        },
    }
    const res = await fetch(URI, newOptions);
    return res;
}

if you are not using async/await you can use below:

const fetchWrapper = (URI, options) => {
    const promise = new Promise((resolve, reject) => {
        fetch('/api/auth/token/refresh').then((auth) => {
            const newOptions = {
                ...options,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${auth.access.token}`,
                },
            }
            fetch(URI, newOptions).then(res => {
                resolve(res);
            }).catch((err) => {
                reject(err);
            });
        }).catch((err) => {
            reject(err);
        });
    })

    return promise;
}


问:
ASP.NET Core 3.1 Host Sub application within main application
Let's say the main web app is: https:\mywebapp.com

Let's say I have separate Web API  project and it has multiple services  (api\service1, api\service2, )

For this I created 2 projects

ASP.NET Core MVC Project for Main App - https:\mywebapp.com

ASP.NET Core Web API project (Service 1, Service 2)

How should I set up my project and publish profile in Azure so that I have the following

Main App (https:\mywebapp.com) - This is good I have publish profile and this gets published correctly in Azure

Service 1 URL (https:\mywebapp.com\api\service1)

Service 2 URL (https:\mywebapp.com\api\service2)

How do I achieve pt 2 and pt3 and have my web API project as a sub-app in my main web application? and share the same URL\api ?

答:
You could create virtual directory on same azure web app.

When you first create Core MVC Project in azure webapp, go to Configuration > Path mappings and config the Virtual directory site/api.

When we publish the Core api to the Azure, we need to include the virtual directory path in the Site Name and Destination URL sections on the Connection tab.

Because Core 3.1 web api consists of one or more controller classes that derive from ControllerBase. The web API project template provides a starter controller:

```<code>[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
</code>```

So, we can visit it just with controllerName. And as it is sub directory, so the Url path is api\controllerName. Here is output:

Body:
You could create virtual directory on same azure web app.

When you first create Core MVC Project in azure webapp, go to Configuration > Path mappings and config the Virtual directory site/api.

When we publish the Core api to the Azure, we need to include the virtual directory path in the Site Name and Destination URL sections on the Connection tab.

Because Core 3.1 web api consists of one or more controller classes that derive from ControllerBase. The web API project template provides a starter controller:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase

So, we can visit it just with controllerName. And as it is sub directory, so the Url path is api\controllerName. Here is output:


问:
Best way to include other CSS/JS libraries in a Github repo?
I'm wanting to include FontAwesome, Bulma, jquery, and jquery-ui in one of my Github repos for the frontend portion. Currently what I'm doing is using the JS file or CSS files from these projects in my own JS/CSS folders, but I feel like there is a neater way to do this. I've tried git submodules for it and they work fine, although I'm unsure if that is the best way to go about doing it.</p>

答: The best way is to use some dependency management system like npm or yarn</p>


问:
How to open react select menu pragmatically
I want to open react select menu on click of a button.

here is the link of code sand box

https://codesandbox.io/s/material-demo-kssrb

I know a react select property 'menuIsOpen', Drawback of this prop is menu is always open and default close behaviour is lost because of this.

Any help appreciated.

答:
You can just make the value of "menuIsOpen" false once the user selects anything from the select box

See this. I have made the necessary changes

https://codesandbox.io/s/material-demo-guo4i


问:
Can cppcheck do a dry run to list all files without actually checking them?
I am running cppcheck on a big project and I'm trying to exclude a couple of files and folders that are 3rd party and/or generated. Is it possible to let cppcheck do a dry run and let it show the files it would normally try to check?</p>

答:
No, such a functionality is not (yet) implemented.

The best solution that comes to my mind is to use options like this:

```<code>cppcheck --check-config ./ 2> /dev/null
</code>```

Explanation:

The --check-config option lets Cppcheck only check if includes are
missing. No further analysis is done, no bugs are reported.

Replace ./ with the path to the source files that you want to have the output for.

2> /dev/null suppresses Cppcheck messages for missing includes and other errors

Running this on the Cppcheck sources I get an output like this:

```<code>$ ./cppcheck --check-config ./ 2> /dev/null
Checking addons/test/cert-test.c ...
1/291 files checked 0% done
Checking addons/test/cert-test.cpp ...
2/291 files checked 0% done
Checking addons/test/misc-test.cpp ...
3/291 files checked 0% done
Checking addons/test/misra/misra-suppressions1-test.c ...
4/291 files checked 0% done
Checking addons/test/misra/misra-suppressions2-test.c ...
5/291 files checked 0% done
Checking addons/test/misra/misra-test.c ...
6/291 files checked 0% done
Checking addons/test/misra/misra-test.cpp ...
7/291 files checked 0% done
Checking addons/test/naming_test.c ...
8/291 files checked 0% done
Checking addons/test/naming_test.cpp ...
9/291 files checked 0% done
Checking addons/test/namingng_test.c ...
10/291 files checked 0% done
Checking addons/test/path1/misra-suppressions1-test.c ...
11/291 files checked 0% done
Checking addons/test/path1/misra-suppressions2-test.c ...
...
</code>```

Body:
No, such a functionality is not (yet) implemented.

The best solution that comes to my mind is to use options like this:

cppcheck --check-config ./ 2> /dev/null

Explanation:

The --check-config option lets Cppcheck only check if includes are
missing. No further analysis is done, no bugs are reported.

Replace ./ with the path to the source files that you want to have the output for.

2> /dev/null suppresses Cppcheck messages for missing includes and other errors

Running this on the Cppcheck sources I get an output like this:

$ ./cppcheck --check-config ./ 2> /dev/null
Checking addons/test/cert-test.c ...
1/291 files checked 0% done
Checking addons/test/cert-test.cpp ...
2/291 files checked 0% done
Checking addons/test/misc-test.cpp ...
3/291 files checked 0% done
Checking addons/test/misra/misra-suppressions1-test.c ...
4/291 files checked 0% done
Checking addons/test/misra/misra-suppressions2-test.c ...
5/291 files checked 0% done
Checking addons/test/misra/misra-test.c ...
6/291 files checked 0% done
Checking addons/test/misra/misra-test.cpp ...
7/291 files checked 0% done
Checking addons/test/naming_test.c ...
8/291 files checked 0% done
Checking addons/test/naming_test.cpp ...
9/291 files checked 0% done
Checking addons/test/namingng_test.c ...
10/291 files checked 0% done
Checking addons/test/path1/misra-suppressions1-test.c ...
11/291 files checked 0% done
Checking addons/test/path1/misra-suppressions2-test.c ...
...


问:
The 2nd command is not executed before terminating the previous one
I'm very new to bash. I'm running a bash script. It is supposed to start Neo4j and then execute a series of queries located in a file called "cypher.ex1". Here is the code:

```<code>#!/bin/bash
./bin/neo4j console
./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1
</code>```

In order to use Cypher-shell, we should start the Neo4j service first. So, this line:

```<code>./bin/neo4j console
</code>```

starts the Neo4j, so that cypher-shell can be used using the following line:

```<code>./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1
</code>```

The problem is that since ./bin/neo4j console starts the Neo4j service, the next command (./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1) is not executed unless I press the "Ctrl + C". If I press "Ctrl + C", the Neo4j service will be stopped and the following command will not be executed too (I get "connection refused" error). What should I do in order to start the Neo4j service and then run the cypher shell in this bash script?

I tried the solutions given in Run a command in background and another command in frontground in the same line. None of them worked for me. For example, When I execute the code with "(command1 &); command2" (As it was suggested in the proposed topic), my script is executed 2 times automatically. The first time command2 is executed and since the command1 is not executed I get "connection refused" error; The second time command1 is executed and command2 is not executed.

答:
As it it mentioned in first answer in the Q/A you should exec the commands on this way:

```<code>#!/bin/bash
./bin/neo4j console &
./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1
</code>```

This will run ./bin/neo4j console in background. So you need to take care about this process and stop it in case of need:

```<code>PID=$(jobs -l |awk '{print $2}')
kill $PID
</code>```

Body:
I'm very new to bash. I'm running a bash script. It is supposed to start Neo4j and then execute a series of queries located in a file called "cypher.ex1". Here is the code:

#!/bin/bash
./bin/neo4j console
./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1

In order to use Cypher-shell, we should start the Neo4j service first. So, this line:

./bin/neo4j console

starts the Neo4j, so that cypher-shell can be used using the following line:

./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1

The problem is that since ./bin/neo4j console starts the Neo4j service, the next command (./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1) is not executed unless I press the "Ctrl + C". If I press "Ctrl + C", the Neo4j service will be stopped and the following command will not be executed too (I get "connection refused" error). What should I do in order to start the Neo4j service and then run the cypher shell in this bash script?

I tried the solutions given in Run a command in background and another command in frontground in the same line. None of them worked for me. For example, When I execute the code with "(command1 &); command2" (As it was suggested in the proposed topic), my script is executed 2 times automatically. The first time command2 is executed and since the command1 is not executed I get "connection refused" error; The second time command1 is executed and command2 is not executed.

Body:
As it it mentioned in first answer in the Q/A you should exec the commands on this way:

#!/bin/bash
./bin/neo4j console &
./bin/cypher-shell -u neo4j -p 123456 --file cypher.ex1

This will run ./bin/neo4j console in background. So you need to take care about this process and stop it in case of need:

PID=$(jobs -l |awk '{print $2}')
kill $PID


问:
while loop with store value for next while loop in java
I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:

anyone could help, thx!

here is my code

```<code>Scanner sc = new Scanner(System.in);

  int i = 0;
  String classname = " ";
  String rating = " ";
  int plus = 0;

  while(i < 3){
    System.out.print("What class are you rating? ");
    classname = sc.nextLine();

    System.out.print("How many plus signs does " + classname +" get? ");
    rating = sc.nextLine();
    plus = Integer.parseInt(rating);

    i++;
  }
    System.out.print(classname + ": ");

    while (plus > 0){
      System.out.print("+");
      plus --;
    }
    System.out.println();
</code>```

答:
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,

```<code>public class Course {
    private String name;
    private int rating;

    public Course(String name, int rating) {
        this.name = name;
        this.rating = rating;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rating; i++) {
            sb.append("+");
        }
        return String.format("%s: %s", name, sb);
    }
}
</code>```

Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,

```<code>Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
    System.out.print("What class are you rating? ");
    String className = sc.nextLine();
    System.out.printf("How many plus signs does %s get? ", className);
    int classRating = Integer.parseInt(sc.nextLine());
    courses[i] = new Course(className, classRating);
    i++;
}
i = 0;
while (i < courses.length) {
    System.out.println(courses[i]);
    i++;
}
</code>```

Body:
I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:

anyone could help, thx!

here is my code

Scanner sc = new Scanner(System.in);

  int i = 0;
  String classname = " ";
  String rating = " ";
  int plus = 0;

  while(i < 3){
    System.out.print("What class are you rating? ");
    classname = sc.nextLine();

    System.out.print("How many plus signs does " + classname +" get? ");
    rating = sc.nextLine();
    plus = Integer.parseInt(rating);

    i++;
  }
    System.out.print(classname + ": ");

    while (plus > 0){
      System.out.print("+");
      plus --;
    }
    System.out.println();

Body:
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,

public class Course {
    private String name;
    private int rating;

    public Course(String name, int rating) {
        this.name = name;
        this.rating = rating;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rating; i++) {
            sb.append("+");
        }
        return String.format("%s: %s", name, sb);
    }
}

Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,

Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
    System.out.print("What class are you rating? ");
    String className = sc.nextLine();
    System.out.printf("How many plus signs does %s get? ", className);
    int classRating = Integer.parseInt(sc.nextLine());
    courses[i] = new Course(className, classRating);
    i++;
}
i = 0;
while (i < courses.length) {
    System.out.println(courses[i]);
    i++;
}


答:
Find with ^

let img = $("img[id^='img_123']");
console.log(img.attr('src'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123"
     src="http://localhost:7777/data/code_img\123.000.00.01.png"
     alt="./data/code_img\123.000.00.01.png" style="display:none"></code>```

Title: jQuery does not find IMG component by its ID

Body:
Find with ^

let img = $("img[id^='img_123']");
console.log(img.attr('src'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123"
     src="http://localhost:7777/data/code_img\123.000.00.01.png"
     alt="./data/code_img\123.000.00.01.png" style="display:none">


问:
C# -> Android (Xamarin) -> start task every 5 minutes in Background
i want to run a task every 5 minutes. i've tried to solve it with an IntentService and AlarmManager, my code:

```<code>protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);

    var tkrServiceIntent = new Intent(this, typeof(GpsDataHandler));
    var tkrServicePendingIntent = PendingIntent.GetService(this, 0, tkrServiceIntent, 0);

    long interval = 5000;
    var firstStart = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000;

    var am = (AlarmManager)GetSystemService(Context.AlarmService);

    am.SetInexactRepeating(AlarmType.RtcWakeup, firstStart, interval, tkrServicePendingIntent);

    Toast.MakeText(this, "Service started", ToastLength.Long).Show();
}
</code>```

i receive the toast, that the service is started, but if i look in running services, there is no service for my application. Can you tell me where the problem ist?

答:
you can create your own timer using xamarin forms device class

sample timer class:

```<code>public class Timer    {
        public Timer(int interval)
        {
            _interval = TimeSpan.FromMilliseconds(interval);
        }

        private bool _isRunning;
        private readonly TimeSpan _interval;

        private Action Tick;

        public void Start(Action tick)
        {
            _isRunning = true;
            Tick = tick;
            Xamarin.Forms.Device.StartTimer(_interval,() =>
            {
                Tick?.Invoke();
                return _isRunning;
            });
        }

        public void Stop()
        {
            _isRunning = false;
            Tick = null;
        }
    }
</code>```

Body:
i want to run a task every 5 minutes. i've tried to solve it with an IntentService and AlarmManager, my code:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);

    var tkrServiceIntent = new Intent(this, typeof(GpsDataHandler));
    var tkrServicePendingIntent = PendingIntent.GetService(this, 0, tkrServiceIntent, 0);

    long interval = 5000;
    var firstStart = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000;

    var am = (AlarmManager)GetSystemService(Context.AlarmService);

    am.SetInexactRepeating(AlarmType.RtcWakeup, firstStart, interval, tkrServicePendingIntent);

    Toast.MakeText(this, "Service started", ToastLength.Long).Show();
}

i receive the toast, that the service is started, but if i look in running services, there is no service for my application. Can you tell me where the problem ist?

Body:
you can create your own timer using xamarin forms device class

sample timer class:

public class Timer    {
        public Timer(int interval)
        {
            _interval = TimeSpan.FromMilliseconds(interval);
        }

        private bool _isRunning;
        private readonly TimeSpan _interval;

        private Action Tick;

        public void Start(Action tick)
        {
            _isRunning = true;
            Tick = tick;
            Xamarin.Forms.Device.StartTimer(_interval,() =>
            {
                Tick?.Invoke();
                return _isRunning;
            });
        }

        public void Stop()
        {
            _isRunning = false;
            Tick = null;
        }
    }


问:
Composer update memory limit
I need to run composer update at my hosting so I log in with ssh and try to run the following command inside /www folder where I have Laravel and composer installation:

```<code>composer update
</code>```

I get this error:

I'm in contact with my hosting provider, they told me to run the command:

```<code>php -d memory_limit=512M composer update
</code>```

I ran this command but I got: "Could not open file: composer"

What to do? What is the solution here?

答:
This error can occur especially when you are updating large libraries or libraries with a lot of dependencies. Composer can be quite memory hungry.

Be sure that your composer itself is updated to the latest version:

```<code>php composer.phar --self-update
</code>```

You can increase the memory limit for composer temporarily by adding the composer memory limit environment variable:

```<code>COMPOSER_MEMORY_LIMIT=128MB php composer.phar update
</code>```

Use the format “128M” for megabyte or “2G” for gigabyte. You can use the value “-1” to ignore the memory limit completely.

Another way would be to increase the PHP memory limit:

```<code>php -d memory_limit=512M composer.phar update ...
</code>```

Title: Composer update memory limit

Body:
I need to run composer update at my hosting so I log in with ssh and try to run the following command inside /www folder where I have Laravel and composer installation:

composer update

I get this error:

I'm in contact with my hosting provider, they told me to run the command:

php -d memory_limit=512M composer update

I ran this command but I got: "Could not open file: composer"

What to do? What is the solution here?

Body:
This error can occur especially when you are updating large libraries or libraries with a lot of dependencies. Composer can be quite memory hungry.

Be sure that your composer itself is updated to the latest version:

php composer.phar --self-update

You can increase the memory limit for composer temporarily by adding the composer memory limit environment variable:

COMPOSER_MEMORY_LIMIT=128MB php composer.phar update

Use the format “128M” for megabyte or “2G” for gigabyte. You can use the value “-1” to ignore the memory limit completely.

Another way would be to increase the PHP memory limit:

php -d memory_limit=512M composer.phar update ...


问:
PHP - Group Array by its Sub Array Value (Indexed Array)
I need to group array by its sub array value.

just came through this link.

Group array by subarray values

But here sub array value having keys. In my case we don't have key. Only indexed keys. Below is my array

```<code>Array
(
    [0] => Array
        (
            [0] => 14. Remarketing Bengaluru
            [1] => RM Web
            [2] => Ludhiana
            **[3] => Display Only**
            [4] => INR
            [5] => 6
        )

    [1] => Array
        (
            [0] => 12. Other Search ROTN
            [1] => 01. Eye glass Shapes
            [2] => Tiruchirappalli
            **[3] => Search Only**
            [4] => INR
            [5] => 144
        )

    [2] => Array
        (
            [0] => 10. Brand ROTN
            [1] => 03. Brand + Keywords
            [2] => Erode
            **[3] => Search Only**
            [4] => INR
            [5] => 24
        )

    [3] => Array
        (
            [0] => 11. Competitors ROTN
            [1] => 02. Titan Eye Plus
            [2] => Thoothukudi
            **[3] => Search Only**
            [4] => INR
            [5] => 1
        )

    [4] => Array
        (
            [0] => 14. Remarketing Bengaluru
            [1] => RM Web
            [2] => Chandigarh
            **[3] => Display Only**
            [4] => INR
            [5] => 6
        )
)
</code>```

Expected:

Needs to group above array with starred value. Eg. Need to group array with array indexed key 3.

Grouped array should be like Display Only, Search Only

答:
This is the solution from Group array by subarray values. I just replaced 'id' with 3.

```<code>$old_arr = array(
  array( "14. Remarketing", "RM", "Lu", "Display Only", "INR", "6" ),
  array( "12. Other", "Shapes", "Ti", "Search Only", "INR", "144" ),
  array( "10. Brand", "Brand", "E", "Search Only", "INR", "24" ),
  array( "11. Competitors", "Titan", "Th", "Search Only", "INR", "1"),
);

foreach ($old_arr as $key => $item) {
   $arr[$item[3]][$key] = $item;
}

echo '```';
var_export($arr);
```

<p>Result:</p>

```array (
  'Display Only' =>
  array (
    0 =>
    array (
      0 => '14. Remarketing',
      1 => 'RM',
      2 => 'Lu',
      3 => 'Display Only',
      4 => 'INR',
      5 => '6',
    ),
  ),
  'Search Only' =>
  array (
    1 =>
    array (
      0 => '12. Other',
      1 => 'Shapes',
      2 => 'Ti',
      3 => 'Search Only',
      4 => 'INR',
      5 => '144',
    ),
    2 =>
    array (
      0 => '10. Brand',
      1 => 'Brand',
      2 => 'E',
      3 => 'Search Only',
      4 => 'INR',
      5 => '24',
    ),
    3 =>
    array (
      0 => '11. Competitors',
      1 => 'Titan',
      2 => 'Th',
      3 => 'Search Only',
      4 => 'INR',
      5 => '1',
    ),
  ),
)
```

Body:
I need to group array by its sub array value.

just came through this link.

Group array by subarray values

But here sub array value having keys. In my case we don't have key. Only indexed keys. Below is my array

Array
(
    [0] => Array
        (
            [0] => 14. Remarketing Bengaluru
            [1] => RM Web
            [2] => Ludhiana
            **[3] => Display Only**
            [4] => INR
            [5] => 6
        )

    [1] => Array
        (
            [0] => 12. Other Search ROTN
            [1] => 01. Eye glass Shapes
            [2] => Tiruchirappalli
            **[3] => Search Only**
            [4] => INR
            [5] => 144
        )

    [2] => Array
        (
            [0] => 10. Brand ROTN
            [1] => 03. Brand + Keywords
            [2] => Erode
            **[3] => Search Only**
            [4] => INR
            [5] => 24
        )

    [3] => Array
        (
            [0] => 11. Competitors ROTN
            [1] => 02. Titan Eye Plus
            [2] => Thoothukudi
            **[3] => Search Only**
            [4] => INR
            [5] => 1
        )

    [4] => Array
        (
            [0] => 14. Remarketing Bengaluru
            [1] => RM Web
            [2] => Chandigarh
            **[3] => Display Only**
            [4] => INR
            [5] => 6
        )
)

Expected:

Needs to group above array with starred value. Eg. Need to group array with array indexed key 3.

Grouped array should be like Display Only, Search Only

Body:
This is the solution from Group array by subarray values. I just replaced 'id' with 3.

$old_arr = array(
  array( "14. Remarketing", "RM", "Lu", "Display Only", "INR", "6" ),
  array( "12. Other", "Shapes", "Ti", "Search Only", "INR", "144" ),
  array( "10. Brand", "Brand", "E", "Search Only", "INR", "24" ),
  array( "11. Competitors", "Titan", "Th", "Search Only", "INR", "1"),
);

foreach ($old_arr as $key => $item) {
   $arr[$item[3]][$key] = $item;
}

echo '<pre>';
var_export($arr);

Result:

array (
  'Display Only' =>
  array (
    0 =>
    array (
      0 => '14. Remarketing',
      1 => 'RM',
      2 => 'Lu',
      3 => 'Display Only',
      4 => 'INR',
      5 => '6',
    ),
  ),
  'Search Only' =>
  array (
    1 =>
    array (
      0 => '12. Other',
      1 => 'Shapes',
      2 => 'Ti',
      3 => 'Search Only',
      4 => 'INR',
      5 => '144',
    ),
    2 =>
    array (
      0 => '10. Brand',
      1 => 'Brand',
      2 => 'E',
      3 => 'Search Only',
      4 => 'INR',
      5 => '24',
    ),
    3 =>
    array (
      0 => '11. Competitors',
      1 => 'Titan',
      2 => 'Th',
      3 => 'Search Only',
      4 => 'INR',
      5 => '1',
    ),
  ),
)


问:
How do I check whether an array contains a string in TypeScript?
Currently I am using Angular 2.0. I have an array as follows:

```<code>var channelArray: Array<string> = ['one', 'two', 'three'];
</code>```

How can I check in TypeScript whether the channelArray contains a string 'three'?

答:
You can use filter too

```<code>this.products = array_products.filter((x) => x.Name.includes("ABC"))
</code>```

Body:
Currently I am using Angular 2.0. I have an array as follows:

var channelArray: Array<string> = ['one', 'two', 'three'];

How can I check in TypeScript whether the channelArray contains a string 'three'?

Body:
You can use filter too

this.products = array_products.filter((x) => x.Name.includes("ABC"))


问:
x86 Assembly: Loops!
Okay, long story short, I'm learning assembly, and I'm trying to make a loop print out the ascii characters "0" - "9".
So, I did all of the basics I've been seeing in examples, like saving register states with pushad and popad, allocating stack space, and making sure I leave things the way they started.
So I managed this small example:

```<code>;
; Hello_World.asm
; (NASM Syntax, Windows)

    extern _printf

    section .text

_main:
  pushad                ; save register states

  push  ebp             ; save old stack
  mov       ebp, esp    ; prepare new stack
  sub       esp, 1*4    ; allocate 4 bytes

  mov       byte [esp + 0], 48  ; add ascii '0' to stack
  mov       byte [esp + 1], 0   ; add ascii NULL terminator to stack

  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret               ; leave this function
</code>```

This works, it prints out '0', but that's a little on the safe side. I tried adding a loop into it, but things just fall apart there. I read that the 'loop' opcode is supposed to decrement the ECX register, and go back to the label parameter should ECX > 0, however, I don't think I've quite got it yet.

So I add a few lines, and come up with this:

```<code>;
; Hello_World.asm
;

    extern _printf
    global _main

    section .text

_main:
  pushad                ; save register states

  push  ebp         ; save old stack
  mov   ebp, esp    ; prepare new stack
  sub   esp, 1*4    ; allocate 4 bytes

  mov   byte [esp + 0], 48  ; add ascii '0' to stack
  mov   byte [esp + 1], 0   ; add ascii NULL terminator to stack

  mov   ecx, 9      ; set loop counter to 9

aLoop:
  inc   byte [esp + 0]  ; increment ascii character
  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence
  loop  aLoop           ; loop back to aLoop if ecx > 0

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret                   ; leave this function
</code>```

Well, now things go crazy. I run it in command prompt and I hear this beeping through my headphones, and it's cycling through every ascii character, printing them all out. So after about 5 seconds of flying characters, I assume something overflows, and it just crashes.

I'm pretty new to assembly (today's my first day of real coding), and I don't see what's going wrong. Could someone please explain how I could better implement a loop ?

Thanks ahead!
-Jason

答: Does the "_printf" subroutine preserve the contents of ECX? If not, that could be your problem. Try saving it across the call.</p>

Title: x86 Assembly: Loops!

Body:
Okay, long story short, I'm learning assembly, and I'm trying to make a loop print out the ascii characters "0" - "9".
So, I did all of the basics I've been seeing in examples, like saving register states with pushad and popad, allocating stack space, and making sure I leave things the way they started.
So I managed this small example:

;
; Hello_World.asm
; (NASM Syntax, Windows)

    extern _printf

    section .text

_main:
  pushad                ; save register states

  push  ebp             ; save old stack
  mov       ebp, esp    ; prepare new stack
  sub       esp, 1*4    ; allocate 4 bytes

  mov       byte [esp + 0], 48  ; add ascii '0' to stack
  mov       byte [esp + 1], 0   ; add ascii NULL terminator to stack

  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret               ; leave this function

This works, it prints out '0', but that's a little on the safe side. I tried adding a loop into it, but things just fall apart there. I read that the 'loop' opcode is supposed to decrement the ECX register, and go back to the label parameter should ECX > 0, however, I don't think I've quite got it yet.

So I add a few lines, and come up with this:

;
; Hello_World.asm
;

    extern _printf
    global _main

    section .text

_main:
  pushad                ; save register states

  push  ebp         ; save old stack
  mov   ebp, esp    ; prepare new stack
  sub   esp, 1*4    ; allocate 4 bytes

  mov   byte [esp + 0], 48  ; add ascii '0' to stack
  mov   byte [esp + 1], 0   ; add ascii NULL terminator to stack

  mov   ecx, 9      ; set loop counter to 9

aLoop:
  inc   byte [esp + 0]  ; increment ascii character
  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence
  loop  aLoop           ; loop back to aLoop if ecx > 0

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret                   ; leave this function

Well, now things go crazy. I run it in command prompt and I hear this beeping through my headphones, and it's cycling through every ascii character, printing them all out. So after about 5 seconds of flying characters, I assume something overflows, and it just crashes.

I'm pretty new to assembly (today's my first day of real coding), and I don't see what's going wrong. Could someone please explain how I could better implement a loop ?

Thanks ahead!
-Jason


问:
Understanding of Azure Functions Premium Plan Billing
I've been reading various documentation around this and was not able to clearly confirm my understanding, we are evaluating Azure Functions Premium Plan and want to have a clearer understanding on the costs.

My understanding is as follows:

In a Premium Plan, we can configure the minimum instances, and the burst size.  This is min and max size of a reserved pool of Premium Plan instances (say it's SKU EP2).  Let's say I set minimum instances to 3, burst size to 10.

The configured minimum (in this case 3) means there are 3 EP2's running at all times that I'm paying for even if they are not doing anything.

On my Function App, I specify that I want 2 pre-warmed function instances.  I'm also paying for these to be pre-warmed and waiting for requests.

Requests start coming in, and now I'm also paying for the execution time (by cores and memory used) in the pre-warmed instances.

Is my understanding above correct?  Would the total costs associated here be the following:

(3 EP2 fixed cost + up to 10 EP2 max burst) +
(2 pre-warmed instances + additional Consumption instances) +
(request executions)

How are we charged for the pre-warmed instances?

答:
You need to pay for the Minimum Instances, whether they run or not: https://learn.microsoft.com/en-us/azure/azure-functions/functions-premium-plan#plan-and-sku-settings
, The pre-warmed instances is in the range of the Minimum Instances. After exceeding the Minimum Instances, the Premium plan will be expanded and charged like a consumption plan, and the instance buffer will no longer be retained.

Taking your example as an example, the cost of the Minimum Instances 3 must be paid (please consider this as a fixed cost), and the excess is charged according to the consumption plan. A tool to calculate costs: https://azure.microsoft.com/en-us/pricing/calculator/?service=functions#functionse9e50b69-a40b-49cf-acac-83786868417a

The above is the fee for the Minimum Instances of the premium plan and the fee beyond the Minimum Instances. In addition, for the Function, you have other charges that you need to pay attention to, otherwise it may bring unexpectedly large cost consumption.

The first is a deposit account. Each feature application requires you to have an associated universal Azure storage account, which is billed separately. This account is used internally by the Functions runtime. Function needs to be bound to a deposit account when it is created. Its use is divided into two parts. One part is to pass your function to the file share during deployment, this part is often negligible; the other part is the cost of using storage resources during your function operation.

The second is Application Insights. Function relies on Application Insights to provide a high-performance monitoring experience for your functional applications. He is not required. Related fees: https://azure.microsoft.com/en-us/pricing/details/monitor/

The third is the data transmission between different areas. You can avoid this by creating Azure services in the same region. If you accidentally formed a data transfer situation from one area to another, then there will be network bandwidth charges: https://azure.microsoft.com/en-us/pricing/details/bandwidth/

The final cost should be: the Minimum Instances 3 that must be spent + the consumption plan cost beyond the Minimum Instances + the cost of the storage account + the Azure Monitor cost + the network bandwidth cost (if the same region, this consumption is 0)


问:
PowerShell Jobs complete but do not create output
I'm trying to get Jobs to work and hitting an issue with them again.
EDIT: Realised that I need to change each of the variables inside the Job ScriptBlocks to include "using", so $using:temp_cpu, $using:temp_cpu_cores, $using:temp_cpu_logical

Even with the using fix, the output below still randomly results in empty output, even though I am waiting for the output files to a) exist, and b) be non-zero size, but about 1 in 3 runs of the below results in empty output.

```<code>function test {
    $temp_cpu = "$($env:TEMP)\ps_temp_cpu.txt"
    $temp_cpu_cores = "$($env:TEMP)\ps_temp_cpu_cores.txt"
    $temp_cpu_logical = "$($env:TEMP)\ps_temp_cpu_logical.txt"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
    $job_cpu         = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).Name > $using:temp_cpu }
    $job_cpu_cores   = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).NumberOfCores > $using:temp_cpu_cores }
    $job_cpu_logical = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).NumberOfLogicalProcessors > $using:temp_cpu_logical }
    Wait-Job $job_cpu, $job_cpu_cores, $job_cpu_logical
    while (!(Test-Path $temp_cpu)) { while ((Get-Item $temp_cpu -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    while (!(Test-Path $temp_cpu_cores)) { while ((Get-Item $temp_cpu_cores -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    while (!(Test-Path $temp_cpu_logical)) { while ((Get-Item $temp_cpu_logical -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }

    "CPU:               $(cat $temp_cpu)"
    "CPU Cores:         $(cat $temp_cpu_cores)"
    "CPU Logical:       $(cat $temp_cpu_logical)"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
}
</code>```

答:
try this:</p>

```<code>$job_cpu = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).Name }
Wait-Job $job_cpu
Receive-Job -Job $job_cpu -OutVariable job_cpu_output
$job_cpu_output > $temp_cpu
</code>```

Body:
I'm trying to get Jobs to work and hitting an issue with them again.
EDIT: Realised that I need to change each of the variables inside the Job ScriptBlocks to include "using", so $using:temp_cpu, $using:temp_cpu_cores, $using:temp_cpu_logical

Even with the using fix, the output below still randomly results in empty output, even though I am waiting for the output files to a) exist, and b) be non-zero size, but about 1 in 3 runs of the below results in empty output.

function test {
    $temp_cpu = "$($env:TEMP)\ps_temp_cpu.txt"
    $temp_cpu_cores = "$($env:TEMP)\ps_temp_cpu_cores.txt"
    $temp_cpu_logical = "$($env:TEMP)\ps_temp_cpu_logical.txt"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
    $job_cpu         = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).Name > $using:temp_cpu }
    $job_cpu_cores   = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).NumberOfCores > $using:temp_cpu_cores }
    $job_cpu_logical = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).NumberOfLogicalProcessors > $using:temp_cpu_logical }
    Wait-Job $job_cpu, $job_cpu_cores, $job_cpu_logical
    while (!(Test-Path $temp_cpu)) { while ((Get-Item $temp_cpu -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    while (!(Test-Path $temp_cpu_cores)) { while ((Get-Item $temp_cpu_cores -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    while (!(Test-Path $temp_cpu_logical)) { while ((Get-Item $temp_cpu_logical -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }

    "CPU:               $(cat $temp_cpu)"
    "CPU Cores:         $(cat $temp_cpu_cores)"
    "CPU Logical:       $(cat $temp_cpu_logical)"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
}

Body:
try this:

$job_cpu = Start-Job -ScriptBlock { (Get-WmiObject -Class Win32_Processor).Name }
Wait-Job $job_cpu
Receive-Job -Job $job_cpu -OutVariable job_cpu_output
$job_cpu_output > $temp_cpu


问:
Embedded iframe in pdf to generate report
I am making a fitness portal on which I am showing multiple health dashboards which are embedded using iframes from external service that I am using , I want to generate a pdf report by inserting all the iframes in the pdf file and download it. </p>

答: PDF files are not HTML files. They have no concept of iframes. But you can use a Flash component and embed it in the PDF.</p>


问:
How to ellipsize a TextView in between an ImageView and a TextView?
Here is my layout:

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="65dp"
    android:layout_marginStart="20dp"
    android:gravity="center_vertical|start"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="18.9dp"
        android:lineSpacingExtra="64sp"
        android:textColor="#484848"
        android:textSize="16sp"
        tools:text="அனைத்து  அனைத்துஅனைத்து" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:lineSpacingExtra="64sp"
        android:text="0"
        android:textAlignment="center"
        android:textColor="@color/red_500"
        android:textSize="14sp" />
</LinearLayout>
</code>```

All other languages are working fine, except tamil language is very big.

I need an icon at beginning and sometimes it show number of notifications at end. So I need to set ellipsize to text on middle.

How to achieve this?

答:
you can use android:ellipsize atrribute to do that.

like this :

```<code><TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="18.9dp"
                        android:lineSpacingExtra="64sp"
                        android:textColor="#484848"
                        android:textSize="16sp"
                        android:ellipsize="end"
                        android:maxLines="1"
                        tools:text="அனைத்து  அனைத்துஅனைத்து" />
</code>```

note: don't forget to use android:maxLines attribute to set the line number of your text.

Body:
Here is my layout:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="65dp"
    android:layout_marginStart="20dp"
    android:gravity="center_vertical|start"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="18.9dp"
        android:lineSpacingExtra="64sp"
        android:textColor="#484848"
        android:textSize="16sp"
        tools:text="அனைத்து  அனைத்துஅனைத்து" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:lineSpacingExtra="64sp"
        android:text="0"
        android:textAlignment="center"
        android:textColor="@color/red_500"
        android:textSize="14sp" />
</LinearLayout>

All other languages are working fine, except tamil language is very big.

I need an icon at beginning and sometimes it show number of notifications at end. So I need to set ellipsize to text on middle.

How to achieve this?

Body:
you can use android:ellipsize atrribute to do that.

like this :

<TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="18.9dp"
                        android:lineSpacingExtra="64sp"
                        android:textColor="#484848"
                        android:textSize="16sp"
                        android:ellipsize="end"
                        android:maxLines="1"
                        tools:text="அனைத்து  அனைத்துஅனைத்து" />

note: don't forget to use android:maxLines attribute to set the line number of your text.


问:
Jersey Resource class interaction?
So, I'm coming up to speed on Jersey and have a "best practice" question. How strict should keep the resources self contained in one file. Should one resource class reference another class if needed?

An example:

I have a Person resource and an Appointment Resource. (ie: /Person/1 & /appointment/12345). I can also do something like /Person/1/Appointments to list all the appointments for person 1.

So, my question is should I implement a method getPersonAppointments() in the Person Resource class, or just someone get a reference to the Appointment resource class and call that method, keeping all the methods which return "Appointments" together.

I don't know that there is a right or a wrong way.

答:
Your REST API should simplify access to resources. One of the principles of REST is the idea of "Hypermedia as the Engine of Application State," which prefers to direct clients to related resources by their URIs so that the client doesn't need to know about how to construct URIs to certain resources a priori.

More information on that here: http://en.wikipedia.org/wiki/HATEOAS

The request to /person/1 should return information about that person, including a collection of appointment URIs. The client can then request any of those URIs to get information about each of those appointments. Implementing /person/1/appointments is redundant.

ContentLicense: CC BY-SA 2.5

Title: Jersey Resource class interaction?


问:
How to manage time in seconds in text format?
I’m reporting on one of the older telecom applications which exports the data in a text format.

I can convert the text to time.

Issue: The issue surfaces when I get a time in this format

-   :00,

-   :22,

The data is changing from :22 to 00:22:00 which changes 22 seconds to 22 minutes.

```<code>Sub FixTime()
    For Each cell In Range("A1:A10")
        cell.Value = "00" & cell.Value
    Next
End Sub
</code>```

This does not happen if I have 00:22:00 (minutes) and 01:22:00 (Hour).

答:
I highly recommend to use the TimeSerial function to produce a real time format and not a string again. The disadvantage of using the Format function is that is produces a string again. Note that this string might look like a time but it is not. For Excel it is just a string while if you use TimeSerial() you will get a real time that Excel recognizes as time and can calculate with.

Rule No. 1 when you are working with dates and times is:

Never let Excel convert date or times on it's own. Never let Excel guess which format this string is. Never let Excel decide anything! • Instead always be specific and parse the string yourself. You are the only one who can tell for 100 % sure which format should be the correct one. Excel will definitely fail soon or later.

```<code>Option Explicit

Public Sub ConvertStringIntoTimes()
    Dim Cell As Range
    For Each Cell In Range("A1:A10").Cells
        Dim RawData() As String 'split cell text by `:`
        RawData = Split(Cell.Text, ":")

        'validate if one is empty string or non-numeric
        Dim i As Long
        For i = 0 To UBound(RawData)
            If RawData(i) = vbNullString Then
                RawData(i) = 0 'epmty string is considered to be zero
            ElseIf Not IsNumeric(RawData(i)) Then
                GoTo NextCell  'non-numeric cannot be handled continue with next cell
            End If
        Next i

        Dim OutputTime As Date
        Select Case UBound(RawData)
            Case 2: '01:22:33 or :22:33
                OutputTime = TimeSerial(RawData(0), RawData(1), RawData(2))

            Case 1: '22:33 or :33
                OutputTime = TimeSerial(0, RawData(0), RawData(1))

            Case 0: '33
                OutputTime = TimeSerial(0, 0, RawData(0))

            Case Else: 'anything else that connot be converted
                GoTo NextCell
        End Select

        'set numberformat and write value as real time
        Cell.NumberFormat = "[$-F400]h:mm:ss AM/PM" 'choose your desired time format
        Cell.Value = OutputTime

NextCell:
    Next Cell
End Sub
</code>```

Image 1: Left is the input data, right column is the output that the procedure will give.

Body:
I’m reporting on one of the older telecom applications which exports the data in a text format.

I can convert the text to time.

Issue: The issue surfaces when I get a time in this format

-   :00,

-   :22,

The data is changing from :22 to 00:22:00 which changes 22 seconds to 22 minutes.

Sub FixTime()
    For Each cell In Range("A1:A10")
        cell.Value = "00" & cell.Value
    Next
End Sub

This does not happen if I have 00:22:00 (minutes) and 01:22:00 (Hour).

Body:
I highly recommend to use the TimeSerial function to produce a real time format and not a string again. The disadvantage of using the Format function is that is produces a string again. Note that this string might look like a time but it is not. For Excel it is just a string while if you use TimeSerial() you will get a real time that Excel recognizes as time and can calculate with.

Rule No. 1 when you are working with dates and times is:

Never let Excel convert date or times on it's own. Never let Excel guess which format this string is. Never let Excel decide anything! • Instead always be specific and parse the string yourself. You are the only one who can tell for 100 % sure which format should be the correct one. Excel will definitely fail soon or later.

Option Explicit

Public Sub ConvertStringIntoTimes()
    Dim Cell As Range
    For Each Cell In Range("A1:A10").Cells
        Dim RawData() As String 'split cell text by `:`
        RawData = Split(Cell.Text, ":")

        'validate if one is empty string or non-numeric
        Dim i As Long
        For i = 0 To UBound(RawData)
            If RawData(i) = vbNullString Then
                RawData(i) = 0 'epmty string is considered to be zero
            ElseIf Not IsNumeric(RawData(i)) Then
                GoTo NextCell  'non-numeric cannot be handled continue with next cell
            End If
        Next i

        Dim OutputTime As Date
        Select Case UBound(RawData)
            Case 2: '01:22:33 or :22:33
                OutputTime = TimeSerial(RawData(0), RawData(1), RawData(2))

            Case 1: '22:33 or :33
                OutputTime = TimeSerial(0, RawData(0), RawData(1))

            Case 0: '33
                OutputTime = TimeSerial(0, 0, RawData(0))

            Case Else: 'anything else that connot be converted
                GoTo NextCell
        End Select

        'set numberformat and write value as real time
        Cell.NumberFormat = "[$-F400]h:mm:ss AM/PM" 'choose your desired time format
        Cell.Value = OutputTime

NextCell:
    Next Cell
End Sub

Image 1: Left is the input data, right column is the output that the procedure will give.


问:
Clarification on "this" pointer with multiple inheritance in C++
I am a bit confused as to how the "this" pointer works with base and derived classes. Consider this code:

```<code>class A {
    //some code
};

class B:  public A {
    //some code
};
</code>```

Is it correct to assume that the "this" pointer invoked from class B will be pointing to the same address as a "this" pointer invoked from some code in the base class A?

What about multiple inheritance?

```<code>class A {
    //some code
};

class B {
    //some code
};

class C:  public A, public B {
    //some code
};
</code>```

Is it correct to assume that the "this" pointer invoked from class C will be pointing to the same address as a "this" pointer invoked from some code in the base classes A or B?

答:
Is it correct to assume that the "this" pointer invoked from class B will be pointing to the same address as a "this" pointer invoked from some code in the base class A?

No, you cannot assume this. However, although not required, many implementations will use the same address (tested with clang 11 and gcc 10).

With multiple inheritance, in your example, clang 11 and gcc 10 use the same address for an instance of class C and it's base A. The base B will have another address.

Another example is multiple inheritance with a common base instance:

```<code>struct A {};
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {};
</code>```

Instantiating D, we get with gcc 10 and clang 11:

```<code>D: 0x7ffc164eefd0
B: 0x7ffc164eefd0 and A: 0x7ffc164eefd0 // address of A and B = address of D
C: 0x7ffc164eefd8 and A: 0x7ffc164eefd0 // different address for C
</code>```

There are no rules specifying the relations between addresses of instances of a derived and a base class. This is implementation dependent.

Body:
I am a bit confused as to how the "this" pointer works with base and derived classes. Consider this code:

class A {
    //some code
};

class B:  public A {
    //some code
};

Is it correct to assume that the "this" pointer invoked from class B will be pointing to the same address as a "this" pointer invoked from some code in the base class A?

What about multiple inheritance?

class A {
    //some code
};

class B {
    //some code
};

class C:  public A, public B {
    //some code
};

Is it correct to assume that the "this" pointer invoked from class C will be pointing to the same address as a "this" pointer invoked from some code in the base classes A or B?

Body:
Is it correct to assume that the "this" pointer invoked from class B will be pointing to the same address as a "this" pointer invoked from some code in the base class A?

No, you cannot assume this. However, although not required, many implementations will use the same address (tested with clang 11 and gcc 10).

With multiple inheritance, in your example, clang 11 and gcc 10 use the same address for an instance of class C and it's base A. The base B will have another address.

Another example is multiple inheritance with a common base instance:

struct A {};
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {};

Instantiating D, we get with gcc 10 and clang 11:

D: 0x7ffc164eefd0
B: 0x7ffc164eefd0 and A: 0x7ffc164eefd0 // address of A and B = address of D
C: 0x7ffc164eefd8 and A: 0x7ffc164eefd0 // different address for C

There are no rules specifying the relations between addresses of instances of a derived and a base class. This is implementation dependent.


问:
How can i get type of python object when it is enclosed in a string?
I have a python object a="123.50" which is string type(a)=string
I want something that tells me  variable a is float object.

I have tried ast.literal_eval(value) , but since it accepts every other things.

Is there anything similar to it (ast.literal_eval) ?

答:
In python, its usual to just try it

```<code>>>> def floater(val):
...     try:
...             float(val)
...             return True
...     except ValueError:
...             return False
...
>>> floater("123.45")
True
>>> floater("sinker")
False
</code>```

Or you could just have python take a crack at it and report what it finds

```<code>>>> def what_is_it(val):
...     try:
...             return type(ast.literal_eval(val)).__name__
...     except:
...             return None
...
>>>
>>> what_is_it("113.44")
'float'
>>> what_is_it("1")
'int'
</code>```

Body:
In python, its usual to just try it

>>> def floater(val):
...     try:
...             float(val)
...             return True
...     except ValueError:
...             return False
...
>>> floater("123.45")
True
>>> floater("sinker")
False

Or you could just have python take a crack at it and report what it finds

>>> def what_is_it(val):
...     try:
...             return type(ast.literal_eval(val)).__name__
...     except:
...             return None
...
>>>
>>> what_is_it("113.44")
'float'
>>> what_is_it("1")
'int'