问:
Multiple combinations logic should use switch or IF
I am trying to write a logic when a particular string are present in switch.

Ex: String

* * * * * My string will alway be in this format space between each string but the string length varies. but 5 spaces and 5 string

Other examples:
0 * * * *
* 0 * * *
* * 12/3 * *
* * 0 0 *
0 0 * * *
* * * 0 0
* * * AA 12

What I am trying here is to write switch cases when the string present other then * i will run case.

```<code>switch(true):
case '0 * * * * ':
echo 'First string has value';
case '`* * 0 0 * `':
echo '3rd & 4th string has value';
case 'A B C AA 12 ':
echo 'All string has value';
</code>```

ect...

I have many combinations but i am not sure switch is the correct way to achive it.

OR LOGIC 2:

Should I explode the string with spaces then use if condition to check 5 string?

答:
Some thing like this

```<code>   $total = 0;
   if( preg_match('/([^*\s]+)/', $str, $match ) ){
       $total = count( $matches[1]);
   }
    echo $total;
</code>```

If you need to know where they match then use this instead

```<code>   $str = '* 0 * * *';
   if( preg_match_all('/([^*\s]+)|\s/', $str, $match ) ){
       print_r( $match )
   }
</code>```

Result

```<code>array (
  0 =>
  array (
    0 => ' ',
    1 => '0',
    2 => ' ',
    3 => ' ',
    4 => ' ',
  ),
  1 =>
  array (
    0 => '',
    1 => '0',
    2 => '',
    3 => '',
    4 => '',
  ),
)
</code>```

See this way ( 0 based index ) you know what ones matched.  Matches are in array index 1, so $match[1][n],

then you can just loop over that, like this

```<code>  $results = [];
   foreach( $match[1] as $m ){
      if( strlen($m) > 0 ){
          $results[] = "Match at pos $m";
      }
   }
</code>```

Etc...

The advantage is that they possible combinations of  * and other stuff is huge, this Normalizes that, so you only have to worry about non * things.  Imagine putting a case of if for every possible combination, not gonna happen.

Body:
I am trying to write a logic when a particular string are present in switch.

Ex: String

* * * * * My string will alway be in this format space between each string but the string length varies. but 5 spaces and 5 string

Other examples:
0 * * * *
* 0 * * *
* * 12/3 * *
* * 0 0 *
0 0 * * *
* * * 0 0
* * * AA 12

What I am trying here is to write switch cases when the string present other then * i will run case.

switch(true):
case '0 * * * * ':
echo 'First string has value';
case '`* * 0 0 * `':
echo '3rd & 4th string has value';
case 'A B C AA 12 ':
echo 'All string has value';

ect...

I have many combinations but i am not sure switch is the correct way to achive it.

OR LOGIC 2:

Should I explode the string with spaces then use if condition to check 5 string?

Body:
Some thing like this

   $total = 0;
   if( preg_match('/([^*\s]+)/', $str, $match ) ){
       $total = count( $matches[1]);
   }
    echo $total;

If you need to know where they match then use this instead

   $str = '* 0 * * *';
   if( preg_match_all('/([^*\s]+)|\s/', $str, $match ) ){
       print_r( $match )
   }

Result

array (
  0 =>
  array (
    0 => ' ',
    1 => '0',
    2 => ' ',
    3 => ' ',
    4 => ' ',
  ),
  1 =>
  array (
    0 => '',
    1 => '0',
    2 => '',
    3 => '',
    4 => '',
  ),
)

See this way ( 0 based index ) you know what ones matched.  Matches are in array index 1, so $match[1][n],

then you can just loop over that, like this

  $results = [];
   foreach( $match[1] as $m ){
      if( strlen($m) > 0 ){
          $results[] = "Match at pos $m";
      }
   }

Etc...

The advantage is that they possible combinations of  * and other stuff is huge, this Normalizes that, so you only have to worry about non * things.  Imagine putting a case of if for every possible combination, not gonna happen.


来源: stackexchange

问:
java.exe code error in xamarin android
I am using xamarin android for my application. When i add the following code to my axml file it shows the error like "java.exe exited with code 2"

```<code><LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical"
          android:background="@drawable/bordertop"
          android:layout_marginTop="0dp"
          android:id="@+id/linearLayout1"
          android:layout_marginBottom="71dp"
          android:layout_gravity="bottom">
        <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal"
          android:weightSum="5">
          <ImageView
              android:src="@drawable/sportscar"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView1"
              android:layout_gravity="fill_horizontal"
              android:layout_weight="0.5" />
          <ImageView
              android:src="@drawable/seatbelt"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView4"
              android:layout_weight="1" />
          <ImageView
              android:src="@drawable/money"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView5"
              android:layout_weight="1"
              android:layout_gravity="fill_horizontal" />
          <ImageView
              android:src="@drawable/customer"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView3"
              android:layout_weight="1" />
          <ImageView
              android:src="@drawable/groupbutton"
              android:layout_width="wrap_content"
              android:layout_height="match_parent"
              android:id="@+id/imageView2"
              android:layout_weight="1.5" />
        </LinearLayout>
        <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:weightSum="5">
          <TextView
             android:text="Four"
             android:textAppearance="?android:attr/textAppearanceSmall"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:id="@+id/txtdtl1"
             android:textColor="#13317E"
             android:layout_weight="1.2"
             android:layout_gravity="center_horizontal" />
          <TextView
              android:text="4"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl2"
              android:textColor="#13317E"
              android:layout_weight="0.5" />
          <TextView
              android:text="PayTm"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl3"
              android:textColor="#13317E"
              android:layout_weight="1.3" />
          <TextView
              android:text="3.5"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl4"
              android:textColor="#13317E"
              android:layout_weight="1" />
          <TextView
              android:text="CUG,FB,GP-VP"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl5"
              android:textColor="#13317E"
              android:drawableTop="@color/BLUE"
              android:layout_weight="1" />
        </LinearLayout>
     </LinearLayout>
</code>```

Can anyone please help me to resolve this issue.

Thanks in advance

答: Finally I got the solution after a longtime. I have updated my xamarin in visual studio to 4.6.0.279 and it works fine now.</p>

ContentLicense: CC BY-SA 3.0

Title: java.exe code error in xamarin android

Body:
I am using xamarin android for my application. When i add the following code to my axml file it shows the error like "java.exe exited with code 2"

<LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical"
          android:background="@drawable/bordertop"
          android:layout_marginTop="0dp"
          android:id="@+id/linearLayout1"
          android:layout_marginBottom="71dp"
          android:layout_gravity="bottom">
        <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal"
          android:weightSum="5">
          <ImageView
              android:src="@drawable/sportscar"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView1"
              android:layout_gravity="fill_horizontal"
              android:layout_weight="0.5" />
          <ImageView
              android:src="@drawable/seatbelt"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView4"
              android:layout_weight="1" />
          <ImageView
              android:src="@drawable/money"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView5"
              android:layout_weight="1"
              android:layout_gravity="fill_horizontal" />
          <ImageView
              android:src="@drawable/customer"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/imageView3"
              android:layout_weight="1" />
          <ImageView
              android:src="@drawable/groupbutton"
              android:layout_width="wrap_content"
              android:layout_height="match_parent"
              android:id="@+id/imageView2"
              android:layout_weight="1.5" />
        </LinearLayout>
        <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:weightSum="5">
          <TextView
             android:text="Four"
             android:textAppearance="?android:attr/textAppearanceSmall"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:id="@+id/txtdtl1"
             android:textColor="#13317E"
             android:layout_weight="1.2"
             android:layout_gravity="center_horizontal" />
          <TextView
              android:text="4"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl2"
              android:textColor="#13317E"
              android:layout_weight="0.5" />
          <TextView
              android:text="PayTm"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl3"
              android:textColor="#13317E"
              android:layout_weight="1.3" />
          <TextView
              android:text="3.5"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl4"
              android:textColor="#13317E"
              android:layout_weight="1" />
          <TextView
              android:text="CUG,FB,GP-VP"
              android:textAppearance="?android:attr/textAppearanceSmall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/txtdtl5"
              android:textColor="#13317E"
              android:drawableTop="@color/BLUE"
              android:layout_weight="1" />
        </LinearLayout>
     </LinearLayout>

Can anyone please help me to resolve this issue.

Thanks in advance


问:
How to generate a random string in rails
In my form i want to generate random strings for the following fields

```<code>  f.input :lti_api_key, label: "LTI API KEY"
    f.input :lti_api_secret, label: "LTI API SECRET"
</code>```

how can i do that?
Please help me...

答:
Hello you can do that:</p>

```<code>require 'securerandom'
SecureRandom.hex(64)
</code>```

Body:
In my form i want to generate random strings for the following fields

  f.input :lti_api_key, label: "LTI API KEY"
    f.input :lti_api_secret, label: "LTI API SECRET"

how can i do that?
Please help me...

Body:
Hello you can do that:

require 'securerandom'
SecureRandom.hex(64)


问:
Error message ORA-19279: XPTY0004 received when trying to create view of XML file in PL/SQL
I am trying to create a view of some XML files in Oracle PL/SQL. The problem with the data content of the XML files is that a single path often has more than one data entry, as shown below:

```<code><priip>
  <data>
    <properties>
      <priipMonitoringInterval>daily</priipMonitoringInterval>
      <priipMonitoringStartDate>2017-06-30T13:51:03.168000</priipMonitoringStartDate>
      <permittedKIDDownloadJurisdictions>
        <item>DE</item>
        <item>AT</item>
      </permittedKIDDownloadJurisdictions>
    </properties>
  </data>
</priip>
</code>```

I am hence getting an error message which reads:

ORA-19279: XPTY0004 - XQuery dynamic type mismatch: expected singleton sequence - got multi-item sequence

Here, clearly, the problem lies with the path:

```<code>priip/data/properties/permittedKIDDownloadJurisdictions/item
</code>```

where we have two permissible jurisdictions, DE and AT. I cannot change the raw XML file, and I require all data within the files to be entered into the PL/SQL view. I have attached a sample of my code below, showing what I have already tried to do.

```<code>create or replace view PRIIPS_XML_VIEW as
  select *
    from PRIIPS_XML t,
      XMLTable(
        '$p/priip/data'
        passing t.SYS_NC_ROWINFO$ as "p"

        columns
          priip_monitoring_interval varchar2(20) path 'properties/priipMonitoringInterval',
          priip_monitoring_start_date varchar2(26) path 'properties/priipMonitoringStartDate',
          kid_download_jurisdiction varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item'
          );
</code>```

Any help would be greatly appreciated!

答:
Change to this.  It is fragile and will not work for > 2 item elements, which in that case you will want to use xquery to do some more sophisticated stuff:</p>

```<code>create or replace view PRIIPS_XML_VIEW as
  select *
    from PRIIPS_XML t,
      XMLTable(
        '$p/priip/data'
        passing t.SYS_NC_ROWINFO$ as "p"

        columns
          priip_monitoring_interval varchar2(20) path 'properties/priipMonitoringInterval',
          priip_monitoring_start_date varchar2(26) path 'properties/priipMonitoringStartDate',
          kid_download_jurisdiction varchar2(10) path
 kid_download_jurisdiction1 varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item[1]',
          kid_download_jurisdiction2 varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item[2]'
);
</code>```

Body:
I am trying to create a view of some XML files in Oracle PL/SQL. The problem with the data content of the XML files is that a single path often has more than one data entry, as shown below:

<priip>
  <data>
    <properties>
      <priipMonitoringInterval>daily</priipMonitoringInterval>
      <priipMonitoringStartDate>2017-06-30T13:51:03.168000</priipMonitoringStartDate>
      <permittedKIDDownloadJurisdictions>
        <item>DE</item>
        <item>AT</item>
      </permittedKIDDownloadJurisdictions>
    </properties>
  </data>
</priip>

I am hence getting an error message which reads:

ORA-19279: XPTY0004 - XQuery dynamic type mismatch: expected singleton sequence - got multi-item sequence

Here, clearly, the problem lies with the path:

priip/data/properties/permittedKIDDownloadJurisdictions/item

where we have two permissible jurisdictions, DE and AT. I cannot change the raw XML file, and I require all data within the files to be entered into the PL/SQL view. I have attached a sample of my code below, showing what I have already tried to do.

create or replace view PRIIPS_XML_VIEW as
  select *
    from PRIIPS_XML t,
      XMLTable(
        '$p/priip/data'
        passing t.SYS_NC_ROWINFO$ as "p"

        columns
          priip_monitoring_interval varchar2(20) path 'properties/priipMonitoringInterval',
          priip_monitoring_start_date varchar2(26) path 'properties/priipMonitoringStartDate',
          kid_download_jurisdiction varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item'
          );

Any help would be greatly appreciated!

Body:
Change to this.  It is fragile and will not work for > 2 item elements, which in that case you will want to use xquery to do some more sophisticated stuff:

create or replace view PRIIPS_XML_VIEW as
  select *
    from PRIIPS_XML t,
      XMLTable(
        '$p/priip/data'
        passing t.SYS_NC_ROWINFO$ as "p"

        columns
          priip_monitoring_interval varchar2(20) path 'properties/priipMonitoringInterval',
          priip_monitoring_start_date varchar2(26) path 'properties/priipMonitoringStartDate',
          kid_download_jurisdiction varchar2(10) path
 kid_download_jurisdiction1 varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item[1]',
          kid_download_jurisdiction2 varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item[2]'
);


问:
Add XML child after empty child
I want to create an XML document from the object page, that contains some information about a print page. I am using this code:

```<code>$xml = new \SimpleXMLElement('<page/>');
$xml->addChild( "pageid", $page->id );
$xml->addChild( "keyword", $page->page_name );

$elements = $xml->addChild( "elements" );

foreach ( $page->elements as $page_element ) {
    $element = $elements->addChild( "element" );
    $element->addChild( "type", $page_element["type"] );
    $element->addChild( "id", $page_element["id"] );
    $element->addChild( "parentContainerID", $page_element["parent_container_id"] );
    $element->addChild( "parentContainerType", $page_element["parent_container_type"] );
    $element->addChild( "Width", $page_element["width"] ?? 0 );
    $element->addChild( "Height", $page_element["height"] ?? 0 );
    $user_def_fields = $element->addChild( "UserDefFields" );

    if ( isset( $page_element["custom_fields"] ) ) {
            foreach ( $page["custom_fields"] as $custom_field_name => $custom_field_value ) {
                $user_def_field = $user_def_fields->addChild( "field" );
                $user_def_field->addChild( "label", $custom_field_name );
                $user_def_field->addChild( "value", $custom_field_value );
            }
        }
    }

    $states = $element->addChild( "ArticleStates" );

    foreach( $page_element["article_states"] as $state ) {
        $states->addChild( "articlestate", $state );
    }
}
</code>```

This works - but when article_states is empty, I get this:

```<code><element>
  <type>group</type>
  <id>1234</id>
  <parentcontainerid>2345</parentcontainerid>
  <parentcontainertype>article</parentcontainertype>
  <width>0</width>
  <height>0</height>
  <userdeffields>
    <articlestates></articlestates>
  </userdeffields>
</element>
</code>```

The articlesstates tag is inside the userdeffields. That's wrong, it should be like this:

```<code><element>
  <type>group</type>
  <id>1234</id>
  <parentcontainerid>2345</parentcontainerid>
  <parentcontainertype>article</parentcontainertype>
  <width>0</width>
  <height>0</height>
  <userdeffields></userdeffields>
  <articlestates></articlestates>
</element>
</code>```

H

答:
Quite simple... but strange indeed.
Just add a space like this:

```<code>$user_def_fields = $element->addChild( "UserDefFields", " " );
</code>```

I just have to remember to use the trim function when parsing the XML... JSON ftw :-)

Title: Add XML child after empty child

Body:
I want to create an XML document from the object page, that contains some information about a print page. I am using this code:

$xml = new \SimpleXMLElement('<page/>');
$xml->addChild( "pageid", $page->id );
$xml->addChild( "keyword", $page->page_name );

$elements = $xml->addChild( "elements" );

foreach ( $page->elements as $page_element ) {
    $element = $elements->addChild( "element" );
    $element->addChild( "type", $page_element["type"] );
    $element->addChild( "id", $page_element["id"] );
    $element->addChild( "parentContainerID", $page_element["parent_container_id"] );
    $element->addChild( "parentContainerType", $page_element["parent_container_type"] );
    $element->addChild( "Width", $page_element["width"] ?? 0 );
    $element->addChild( "Height", $page_element["height"] ?? 0 );
    $user_def_fields = $element->addChild( "UserDefFields" );

    if ( isset( $page_element["custom_fields"] ) ) {
            foreach ( $page["custom_fields"] as $custom_field_name => $custom_field_value ) {
                $user_def_field = $user_def_fields->addChild( "field" );
                $user_def_field->addChild( "label", $custom_field_name );
                $user_def_field->addChild( "value", $custom_field_value );
            }
        }
    }

    $states = $element->addChild( "ArticleStates" );

    foreach( $page_element["article_states"] as $state ) {
        $states->addChild( "articlestate", $state );
    }
}

This works - but when article_states is empty, I get this:

<element>
  <type>group</type>
  <id>1234</id>
  <parentcontainerid>2345</parentcontainerid>
  <parentcontainertype>article</parentcontainertype>
  <width>0</width>
  <height>0</height>
  <userdeffields>
    <articlestates></articlestates>
  </userdeffields>
</element>

The articlesstates tag is inside the userdeffields. That's wrong, it should be like this:

<element>
  <type>group</type>
  <id>1234</id>
  <parentcontainerid>2345</parentcontainerid>
  <parentcontainertype>article</parentcontainertype>
  <width>0</width>
  <height>0</height>
  <userdeffields></userdeffields>
  <articlestates></articlestates>
</element>

H

Body:
Quite simple... but strange indeed.
Just add a space like this:

$user_def_fields = $element->addChild( "UserDefFields", " " );

I just have to remember to use the trim function when parsing the XML... JSON ftw :-)


问:
Simplifiying JQuery
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <span id="first">Blah blah blah, please <span id="span1">click here</span>.</span>
    <span id="second" style="display:none;">Cancel</span>
    <div id="third" style="display:none;">Test</div></code>```

This code is taken from accepted answer from original post.

答:
For the duration, you can either type a number (which represents milliseconds) like this:

```<code>.fadeIn(400);
</code>```

which performs the action throughout the course of 400ms.
An alternative, is to use a string such as "fast" or "slow", like this:

```<code>.fadeIn("slow");
</code>```

or

```<code>.fadeIn("fast");
</code>```

Also, to shorten it (If I have correctly understood your question) you can use this example:

$("#first > span").click(function() {
  $(this).parent().nextAll("div").fadeIn();
  $(this).parent().hide();
});
$("#second").on('click', function() {
  $(this).prev().fadeIn();
  $(this).prev().nextAll().hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container #second, #first > span {
  color: blue;
  cursor: pointer;
}
.hidden {
  display: none;
}</code>```

    Blah blah blah, please
    click here.

Cancel

Test

Test

Test

Test

Test

Test

Test

```

Title: Simplifiying JQuery

Body:
I'm running a blog on wordpress. I wish to make #first to disappear when #span1 is clicked but reappear when #second clicked. And #second, #third appear when #span1 clicked but disappear when #second clicked. It works but my questions is it possible to simplify this JQuery to make more simpler and neat. Because probably in future I will have to add more DIVs similar to #third. Other question is how do I control duration of fadeIn and fadeOut?

HTML

    $("#span1").on('click', function() {
       $("#second, #third").fadeIn();
       $("#first").hide();
    });

    $("#second").on('click', function() {
       $("#first").fadeIn();
       $("#second, #third").hide();

    });

    Blah blah blah, please click here.
    Cancel

Test

This code is taken from accepted answer from original post.

Body:
For the duration, you can either type a number (which represents milliseconds) like this:

.fadeIn(400);

which performs the action throughout the course of 400ms.
An alternative, is to use a string such as "fast" or "slow", like this:

.fadeIn("slow");

or

.fadeIn("fast");

Also, to shorten it (If I have correctly understood your question) you can use this example:

$("#first > span").click(function() {
  $(this).parent().nextAll("div").fadeIn();
  $(this).parent().hide();
});
$("#second").on('click', function() {
  $(this).prev().fadeIn();
  $(this).prev().nextAll().hide();
});

.container #second, #first > span {
  color: blue;
  cursor: pointer;
}
.hidden {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="container">
  <span id="first">
    Blah blah blah, please
    <span>click here.</span>
  </span>
  <div class="hidden" id="second">Cancel</div>
  <div class="hidden" id="third">Test</div>
  <div class="hidden" id="fourth">Test</div>
  <div class="hidden" id="fith">Test</div>
  <div class="hidden" id="sixth">Test</div>
  <div class="hidden" id="seventh">Test</div>
  <div class="hidden" id="eighth">Test</div>
  <div class="hidden" id="ninth">Test</div>
</div>


问:
How to set the formatting on the axes in Google Charts to a certain pattern?
I want to change the formatting of the values on the axis to look like so:

```<code>1
100
1 000
10 000
100 000
1 000 000
</code>```

Meaning, I'd like to change the default grouping symbol to a space (' '). So far I tried with different approaches but none of them worked. Even the documentation couldn't help me much. Anyone?

Important:

I want to change the formatting on the values on the axis, not the inner values.

I don't want to change the language of the google chart.

答:
use option --> ticks -- to provide custom labels for either axis

hAxis or vAxis

using object notation, provide both a value v: and a formatted value f:

```<code>    hAxis: {
      ticks: [
        {v: 0, f: '1'},
        {v: 1, f: '100'},
        {v: 2, f: '1 000'},
        {v: 3, f: '10 000'},
        {v: 4, f: '100 000'},
        {v: 5, f: '1 000 000'}
      ]
    },
</code>```

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [4, 4],
    [5, 5],
    [6, 6]
  ]);
  var options = {
    hAxis: {
      ticks: [
        {v: 0, f: '1'},
        {v: 1, f: '100'},
        {v: 2, f: '1 000'},
        {v: 3, f: '10 000'},
        {v: 4, f: '100 000'},
        {v: 5, f: '1 000 000'}
      ]
    },
    vAxis: {
      ticks: [
        {v: 0, f: '1'},
        {v: 1, f: '100'},
        {v: 2, f: '1 000'},
        {v: 3, f: '10 000'},
        {v: 4, f: '100 000'},
        {v: 5, f: '1 000 000'}
      ]
    }
  };
  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div></code>```

EDIT

you can use a number formatter to create the number pattern

```<code>var formatLabel = new google.visualization.NumberFormat({
  groupingSymbol: ' ',
  fractionDigits: 0
});
</code>```

format the data table to see the format on the tooltips

```<code>// format tooltips
formatLabel.format(data, 1);
</code>```

still need to create custom labels to see on the axis

```<code>// create axis labels
var axisTicks = [];
var axisRange = data.getColumnRange(1);
for (var i = axisRange.min; i <= axisRange.max; i=i+1000) {
  axisTicks.push({
    v: i,
    f: formatLabel.formatValue(i)
  });
}
</code>```

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    [0, 1000],
    [1, 2000],
    [2, 3000],
    [3, 6000],
    [4, 10000]
  ]);

  var formatLabel = new google.visualization.NumberFormat({
    groupingSymbol: ' ',
    fractionDigits: 0
  });

  // format tooltips
  formatLabel.format(data, 1);

  // create axis labels
  var axisTicks = [];
  var axisRange = data.getColumnRange(1);
  for (var i = axisRange.min; i <= axisRange.max; i=i+1000) {
    axisTicks.push({
      v: i,
      f: formatLabel.formatValue(i)
    });
  }

  var options = {
    height: 400,
    pointSize: 4,
    vAxis: {
      ticks: axisTicks
    }
  };
  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div></code>```

Body:
I want to change the formatting of the values on the axis to look like so:

1
100
1 000
10 000
100 000
1 000 000

Meaning, I'd like to change the default grouping symbol to a space (' '). So far I tried with different approaches but none of them worked. Even the documentation couldn't help me much. Anyone?

Important:

I want to change the formatting on the values on the axis, not the inner values.

I don't want to change the language of the google chart.

Body:
use option --> ticks -- to provide custom labels for either axis

hAxis or vAxis

using object notation, provide both a value v: and a formatted value f:

    hAxis: {
      ticks: [
        {v: 0, f: '1'},
        {v: 1, f: '100'},
        {v: 2, f: '1 000'},
        {v: 3, f: '10 000'},
        {v: 4, f: '100 000'},
        {v: 5, f: '1 000 000'}
      ]
    },

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [4, 4],
    [5, 5],
    [6, 6]
  ]);
  var options = {
    hAxis: {
      ticks: [
        {v: 0, f: '1'},
        {v: 1, f: '100'},
        {v: 2, f: '1 000'},
        {v: 3, f: '10 000'},
        {v: 4, f: '100 000'},
        {v: 5, f: '1 000 000'}
      ]
    },
    vAxis: {
      ticks: [
        {v: 0, f: '1'},
        {v: 1, f: '100'},
        {v: 2, f: '1 000'},
        {v: 3, f: '10 000'},
        {v: 4, f: '100 000'},
        {v: 5, f: '1 000 000'}
      ]
    }
  };
  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

EDIT

you can use a number formatter to create the number pattern

var formatLabel = new google.visualization.NumberFormat({
  groupingSymbol: ' ',
  fractionDigits: 0
});

format the data table to see the format on the tooltips

// format tooltips
formatLabel.format(data, 1);

still need to create custom labels to see on the axis

// create axis labels
var axisTicks = [];
var axisRange = data.getColumnRange(1);
for (var i = axisRange.min; i <= axisRange.max; i=i+1000) {
  axisTicks.push({
    v: i,
    f: formatLabel.formatValue(i)
  });
}

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    [0, 1000],
    [1, 2000],
    [2, 3000],
    [3, 6000],
    [4, 10000]
  ]);

  var formatLabel = new google.visualization.NumberFormat({
    groupingSymbol: ' ',
    fractionDigits: 0
  });

  // format tooltips
  formatLabel.format(data, 1);

  // create axis labels
  var axisTicks = [];
  var axisRange = data.getColumnRange(1);
  for (var i = axisRange.min; i <= axisRange.max; i=i+1000) {
    axisTicks.push({
      v: i,
      f: formatLabel.formatValue(i)
    });
  }

  var options = {
    height: 400,
    pointSize: 4,
    vAxis: {
      ticks: axisTicks
    }
  };
  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>


问:
How can I achieve the DICOM Alignment
The question is quite simple, we have many DICOM serial images, for same patient for sure.
I need figure out the image of the same location in the body in different serials and compare them.
Let's assume the image parameters like pixel spacing, slice thickness, etc. are the same. But the patient may moved after each scan.

How can I achieve the image alignment?

Actually I got a parameter "slice location", I heard its a DICOM3 attribute, let's say we always have this one. Is the image with same slice location means the same position on the body?
I heard the coordinate system is based on patient's body, how can we define the origin point on patient's body? I believe the origin point should on the scan machine, which called world coordinate, isn't it?

答:
Alignment between series is more than just image position.

See http://dicom.nema.org/medical/dicom/current/output/html/part03.html#sect_C.7.6.2 for the relevant part of the DICOM image standard.

See http://www.dclunie.com/medical-image-faq/html/part2.html for information about drawing appropriate scout lines in images, which may help to clarify the information.

If the patient physically moved within the scanner between series (or they are different studies), then you have to use some image registration algorithms using the mutual information in the images.

There is a lot of information on the web and stackoverflow relating to this.

Title: How can I achieve the DICOM Alignment


问:
ngrok + Local IIS: how to expose a website
I'm working on an ASP.NET MVC project in which I use Paypal thus I want to debug a webhook implementation.

I'm running my project with the local IIS and I followed this tutorial to try to expose it to the web but it's not working. I tried everything in it.

I run on Windows 10 and  IIS 10.0.14. My local IIS website runs on door 80 and 443 (SSL enabled). I had XAMPP running in the same door then I changed it to run on 81 and 442.

Can you help me? Is there anything I'm missing?
Thanks for any help

答:
read following article. I have used it successfully on my side.
https://vipul1989.wordpress.com/2017/06/09/using-ngrok-to-expose-your-localhost-to-web/</p>


问:
Referencing already opened word document in VBA
I am using Excel VBA to open a word Template and it populates the template with information from an excel spreadsheet. From there, I have a button on the spreadsheet that I want to then populate another line in the word document whenever it is clicked. The problem I am encountering is that when I run the button macro it just opens up another word document and pastes the button information instead of doing it on the already opened document. I will attach my code below and I believe it is an easy fix I just can't seem to find a way around it.</p>

```<code>Sub RepairCal()

Dim objWord As Object
Dim objDoc As Object

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Open("C:\Users\z003narc\Documents\Gage Lab Form Template.docm")

objWord.Activate

With Selection

   objWord.ActiveDocument.Selection.MoveDown count:=6
   objWord.ActiveDocument.Selection.MoveRight count:=5
   objWord.ActiveDocument.Selection.TypeText Text:="Repair and Calibration"

End With

End Sub
</code>```

答:
Are you saying you already have the document open when you run this every time?  The way you wrote the code, it will do this:

1) Open new blank Microsoft Word process

2) In the new process, opens the workbook you have chosen

3) Makes the new process the active window

4) does stuff

If you want it to attach to the file you already have open, you would need to do GetObject instead of CreateObject. So change:

```<code>Set objWord = CreateObject("Word.Application")
</code>```

To

```<code>Set objWord = GetObject(, "Word.Application")
</code>```

This will attach to the currently open process, then open the workbook in that process. However, it will still open up a fresh copy of that document each time, because that's what you're telling it to do.

Body:
I am using Excel VBA to open a word Template and it populates the template with information from an excel spreadsheet. From there, I have a button on the spreadsheet that I want to then populate another line in the word document whenever it is clicked. The problem I am encountering is that when I run the button macro it just opens up another word document and pastes the button information instead of doing it on the already opened document. I will attach my code below and I believe it is an easy fix I just can't seem to find a way around it.

Sub RepairCal()

Dim objWord As Object
Dim objDoc As Object

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Open("C:\Users\z003narc\Documents\Gage Lab Form Template.docm")

objWord.Activate

With Selection

   objWord.ActiveDocument.Selection.MoveDown count:=6
   objWord.ActiveDocument.Selection.MoveRight count:=5
   objWord.ActiveDocument.Selection.TypeText Text:="Repair and Calibration"

End With

End Sub

Body:
Are you saying you already have the document open when you run this every time?  The way you wrote the code, it will do this:

1) Open new blank Microsoft Word process

2) In the new process, opens the workbook you have chosen

3) Makes the new process the active window

4) does stuff

If you want it to attach to the file you already have open, you would need to do GetObject instead of CreateObject. So change:

Set objWord = CreateObject("Word.Application")

To

Set objWord = GetObject(, "Word.Application")

This will attach to the currently open process, then open the workbook in that process. However, it will still open up a fresh copy of that document each time, because that's what you're telling it to do.


问:
Validity of GUI design patterns under linux
I am investigating a switch from windows to linux and i struggle to find samples of design patterns applied in this world.

The application is a classic client server with detailed forms for each business entity.

It will be taking user input, do some validation checks, a few calculations, and save them to database.

It will also have lists summarizing entities, and searches among these entities.

A click to one item of these lists will open the detailled forms.

If i use python or ruby, what should i use for GUI ?

And what pattern : is MVC, MVVM or MVP any good ?

Or is there anything better ?

Note : I have never done web developpement, and i would like to avoid to have to learn both linux and web developpement at the same time.

答:
You might want to look at Mono. It's basically cross-platform .NET. You could write your app once and run it on Windows or Linux (and easily port it to Android or iOS). You can also look into Moonlight, the open source version of Silverlight if you want to focus on an MVVM pattern. Leveraging .NET will make it a lot easier to move to a web application framework. As a benefit you can do your development on either Windows, Linux, or Mac.

If you need database access, and are going to go with .NET, I'd recommend dblinq and a MySql backend.

ContentLicense: CC BY-SA 2.5


问:
how to get selected value from ajax combobox using javascript in asp.net c#
I want to get the selected value from ajax combobox selected item using javascript in asp.net c#

here is my code

```<code><asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssClass="ComboboxWidth" DropDownStyle="DropDownList" Height="15px" MaxLength="50">
</asp:ComboBox>

function blurFunction()
{
     var ddlReport = document.getElementById("<%=dropdown_dest.ClientID%>").value;
     alert(ddlReport);
}
</code>```

in alert it is showing undefined.

Please help me to solve me this error

Thank You.

答:
I have not tested. </p>

```<code><asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction(this)" AutoCompleteMode="SuggestAppend" CssClass="ComboboxWidth" DropDownStyle="DropDownList" Height="15px" MaxLength="50">
</asp:ComboBox>

<script>

function blurFunction(e) {
var val = e.options[e.selectedIndex].value;
console.log(val);
}
</script>
</code>```

<p>using "this" will skip jquery loop and js script can be put in separate file. </p>

Body:
I want to get the selected value from ajax combobox selected item using javascript in asp.net c#

here is my code

<asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssClass="ComboboxWidth" DropDownStyle="DropDownList" Height="15px" MaxLength="50">
</asp:ComboBox>

function blurFunction()
{
     var ddlReport = document.getElementById("<%=dropdown_dest.ClientID%>").value;
     alert(ddlReport);
}

in alert it is showing undefined.

Please help me to solve me this error

Thank You.

Body:
I have not tested.

<asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction(this)" AutoCompleteMode="SuggestAppend" CssClass="ComboboxWidth" DropDownStyle="DropDownList" Height="15px" MaxLength="50">
</asp:ComboBox>

<script>

function blurFunction(e) {
var val = e.options[e.selectedIndex].value;
console.log(val);
}
</script>

using "this" will skip jquery loop and js script can be put in separate file.


问:
Outlook 365 Rest API - The audience claim value is invalid
I am working on a current project where we already using Identity Server to auth. Here we use the Access token to access the microsoft Graph API to get Meetings, profile pictures and other stuff.

Now we want to make an integration to the new Outlook 365 API to read and in the future write tasks.

I am trying to get Outlook tasks from the Outlook restapi using already existing accesstoken:

```<code>{
  "aud": "https://graph.microsoft.com",
  "iss": "https://sts.windows.net/17e18230-55e1-4f60-8262-5c67e2b2ab11/",
  "iat": 1145153145,
  "nbf": 1491225024,
  "exp": 1491258924,
  "acr": "1",
  "aio": "QSQA8/8DAFFFInSl+iIfvSXhA95NqTYRmKugpaLdvffNkba0L8N5x0U=",
  "amr": [
    "pwd"
  ],
  "app_displayname": "AwesomeApp.Dev",
  "appid": "0c2fgc75-f2ee-fas5-ae9f-fasd2s5d523fs",
  "appidacr": "1",
  "family_name": "Jesper Krægpøth Ryder",
  "given_name": "Joshua",
  "ipaddr": "208.67.222.222",
  "name": "Joshua Jesper Krægpøth Ryder",
  "oid": "a4586g1-d0215-3226-ar05-125463gasrqw5",
  "platf": "3",
  "puid": "654wf84yu3s1g6",
  "scp": "Calendars.Read Calendars.Read.Shared Calendars.ReadWrite Directory.Read.All Files.ReadWrite Group.Read.All Mail.ReadWrite Mail.Send Tasks.Read User.Read User.ReadBasic.All User.ReadWrite",
  "sub": "0s_x0JhaNb1QLpIM2Hldx7pSVkrpTgXKe4QPXXiRguQ",
  "tid": "15e18430-54e9-4f60-8821-5c85e2b2ab77",
  "unique_name": "jor@awesome.com",
  "upn": "jor@awesome.com",
  "uti": "65a2gasdrfasda_fasfa54153",
  "ver": "1.0"
}
</code>```

https://outlook.office.com/api/v2.0/me/tasks

Error message:

```<code>Content-Length →0
Date →Tue, 04 Jul 2017 08:35:21 GMT
Server →Microsoft-IIS/10.0
WWW-Authenticate →Bearer client_id="00000002-0000-0ff1-ce00-000000000000",
trusted_issuers="00000001-0000-0000-c000-000000000000@*",
token_types="app_asserted_user_v1 service_asserted_app_v1",
authorization_uri="https://login.windows.net/common/oauth2/authorize",
error="invalid_token",Basic Realm="",Basic Realm="",Basic Realm=""
X-BEServer →HE1PR0901MB1194
X-BackEndHttpStatus →401, 401
X-CalculatedBETarget →HE1PR0901MB1194.eurprd09.prod.outlook.com
X-CalculatedFETarget →HE1P190CU001.internal.outlook.com
X-DiagInfo →HE1PR0901MB1194
X-FEProxyInfo →HE1P190CA0005.EURP190.PROD.OUTLOOK.COM
X-FEServer →HE1P190CA0005, HE1PR0201CA0031
X-MSEdge-Ref →Ref A: C32D029EF8F84E68BF6327901BBED14F Ref B: HEL01EDGE0307
Ref C: Tue Jul 4 01:35:21 2017 PST
X-Powered-By →ASP.NET
request-id →2266567a-dd67-48f0-b3b4-72cfb5ee6b42
x-ms-diagnostics →2000003;reason="The audience claim value is invalid
'https://graph.microsoft.com'.";error_category="invalid_resource"
</code>```

On the identity server we are using the middle ware to handle our scopes like so:

```<code>        app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
        {
            AuthenticationScheme = "Microsoft",
            DisplayName = "Microsoft",
            SignInScheme = cookieScheme,
            ClientId = Configuration.GetValue<string>("ExternalKeys:SecretMicrosoftClientId"),
            ClientSecret = Configuration.GetValue<string>("ExternalKeys:SecretMicrosoftClientSecret"),
            CallbackPath = new PathString("/signin-microsoft"),
            Scope =
            {
                "offline_access",
                "Calendars.Read",
                "Calendars.Read.Shared",
                "https://outlook.office.com/tasks.read"
            },

            SaveTokens = true,

        });
</code>```

When we try to login, we get prompted with the additional Tasks access requirement. So we should have access to the tasks API.

Anyone else tried to use both Microsoft graph API and new Outlook 365 Rest API?

答:
New answer:

Api has now been released and can be found here
https://msdn.microsoft.com/en-us/office/office365/api/task-rest-operations

Working scopes for our project:

```<code>Scope =
{
    "offline_access",
    "Calendars.Read",
    "Calendars.Read.Shared",
    "Tasks.Readwrite"
},
</code>```

Old answer:

You cannot use a token issued for Graph ("aud": "https://graph.microsoft.com") against the Outlook endpoint. You need a token with "aud": "https://outlook.office.com". To get that you would need to do another auth request to Azure with all of your scopes fully-qualified with the Outlook domain:

```<code>Scope =
{
    "offline_access",
    "https://outlook.office.com/Calendars.Read",
    "https://outlook.office.com/Calendars.Read.Shared",
    "https://outlook.office.com/tasks.read"
},
</code>```

However, since you're already using Graph, you could just access tasks via the Graph too :). Graph recently added task support to their beta endpoint: https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/outlooktask.

Body:
I am working on a current project where we already using Identity Server to auth. Here we use the Access token to access the microsoft Graph API to get Meetings, profile pictures and other stuff.

Now we want to make an integration to the new Outlook 365 API to read and in the future write tasks.

I am trying to get Outlook tasks from the Outlook restapi using already existing accesstoken:

{
  "aud": "https://graph.microsoft.com",
  "iss": "https://sts.windows.net/17e18230-55e1-4f60-8262-5c67e2b2ab11/",
  "iat": 1145153145,
  "nbf": 1491225024,
  "exp": 1491258924,
  "acr": "1",
  "aio": "QSQA8/8DAFFFInSl+iIfvSXhA95NqTYRmKugpaLdvffNkba0L8N5x0U=",
  "amr": [
    "pwd"
  ],
  "app_displayname": "AwesomeApp.Dev",
  "appid": "0c2fgc75-f2ee-fas5-ae9f-fasd2s5d523fs",
  "appidacr": "1",
  "family_name": "Jesper Krægpøth Ryder",
  "given_name": "Joshua",
  "ipaddr": "208.67.222.222",
  "name": "Joshua Jesper Krægpøth Ryder",
  "oid": "a4586g1-d0215-3226-ar05-125463gasrqw5",
  "platf": "3",
  "puid": "654wf84yu3s1g6",
  "scp": "Calendars.Read Calendars.Read.Shared Calendars.ReadWrite Directory.Read.All Files.ReadWrite Group.Read.All Mail.ReadWrite Mail.Send Tasks.Read User.Read User.ReadBasic.All User.ReadWrite",
  "sub": "0s_x0JhaNb1QLpIM2Hldx7pSVkrpTgXKe4QPXXiRguQ",
  "tid": "15e18430-54e9-4f60-8821-5c85e2b2ab77",
  "unique_name": "jor@awesome.com",
  "upn": "jor@awesome.com",
  "uti": "65a2gasdrfasda_fasfa54153",
  "ver": "1.0"
}

https://outlook.office.com/api/v2.0/me/tasks

Error message:

Content-Length →0
Date →Tue, 04 Jul 2017 08:35:21 GMT
Server →Microsoft-IIS/10.0
WWW-Authenticate →Bearer client_id="00000002-0000-0ff1-ce00-000000000000",
trusted_issuers="00000001-0000-0000-c000-000000000000@*",
token_types="app_asserted_user_v1 service_asserted_app_v1",
authorization_uri="https://login.windows.net/common/oauth2/authorize",
error="invalid_token",Basic Realm="",Basic Realm="",Basic Realm=""
X-BEServer →HE1PR0901MB1194
X-BackEndHttpStatus →401, 401
X-CalculatedBETarget →HE1PR0901MB1194.eurprd09.prod.outlook.com
X-CalculatedFETarget →HE1P190CU001.internal.outlook.com
X-DiagInfo →HE1PR0901MB1194
X-FEProxyInfo →HE1P190CA0005.EURP190.PROD.OUTLOOK.COM
X-FEServer →HE1P190CA0005, HE1PR0201CA0031
X-MSEdge-Ref →Ref A: C32D029EF8F84E68BF6327901BBED14F Ref B: HEL01EDGE0307
Ref C: Tue Jul 4 01:35:21 2017 PST
X-Powered-By →ASP.NET
request-id →2266567a-dd67-48f0-b3b4-72cfb5ee6b42
x-ms-diagnostics →2000003;reason="The audience claim value is invalid
'https://graph.microsoft.com'.";error_category="invalid_resource"

On the identity server we are using the middle ware to handle our scopes like so:

        app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
        {
            AuthenticationScheme = "Microsoft",
            DisplayName = "Microsoft",
            SignInScheme = cookieScheme,
            ClientId = Configuration.GetValue<string>("ExternalKeys:SecretMicrosoftClientId"),
            ClientSecret = Configuration.GetValue<string>("ExternalKeys:SecretMicrosoftClientSecret"),
            CallbackPath = new PathString("/signin-microsoft"),
            Scope =
            {
                "offline_access",
                "Calendars.Read",
                "Calendars.Read.Shared",
                "https://outlook.office.com/tasks.read"
            },

            SaveTokens = true,

        });

When we try to login, we get prompted with the additional Tasks access requirement. So we should have access to the tasks API.

Anyone else tried to use both Microsoft graph API and new Outlook 365 Rest API?

Body:
New answer:

Api has now been released and can be found here
https://msdn.microsoft.com/en-us/office/office365/api/task-rest-operations

Working scopes for our project:

Scope =
{
    "offline_access",
    "Calendars.Read",
    "Calendars.Read.Shared",
    "Tasks.Readwrite"
},

Old answer:

You cannot use a token issued for Graph ("aud": "https://graph.microsoft.com") against the Outlook endpoint. You need a token with "aud": "https://outlook.office.com". To get that you would need to do another auth request to Azure with all of your scopes fully-qualified with the Outlook domain:

Scope =
{
    "offline_access",
    "https://outlook.office.com/Calendars.Read",
    "https://outlook.office.com/Calendars.Read.Shared",
    "https://outlook.office.com/tasks.read"
},

However, since you're already using Graph, you could just access tasks via the Graph too :). Graph recently added task support to their beta endpoint: https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/outlooktask.


问:
Backbone pagination scroll issue in Chrome after getNextPage
New to backbone and backbone.pageableCollection in 'infinite' mode and everything is working fine except when I call to get the next page. After calling to load the next page, instead of maintaining the scroll position and loading the next records underneath "as it's supposed to", Chrome and safari scrolls all of the way to the top of the page, making it very annoying for the users to have to scroll all of the way down again. Here it's the code I use to get the next page

this.collection.getNextPage({remove: false, silent: true});

Everything works great in Firefox and Opera, they both maintain the scroll position and load the next records, but Chrome and safari are not working and are the most used browsers for our web app.

I have tried everything from

var pos = window.pageYOffset;
this.collection.getNextPage({remove: false, silent: true});
 window.scrollTo(0, pos);

To set a time out and nothing works, it always scrolls up to the top of the page

setTimeout(function() {window.scrollTo(0, pos);}, 1);

At this point, I am stuck with a solution in order for Chrome and Safari to keep the scroll position.

Any help will be greatly appreciated it.

答:
Finally found a solution that works in all browsers maintaining the scroll position. If anyone knows why it'll be great to have an explanation, Thanks!</p>

```<code>var pos = window.pageYOffset;

this.collection.getNextPage({remove: false, silent: true});

$("html,body").animate({ scrollTop: pos }, "slow");
</code>```

Body:
Finally found a solution that works in all browsers maintaining the scroll position. If anyone knows why it'll be great to have an explanation, Thanks!

var pos = window.pageYOffset;

this.collection.getNextPage({remove: false, silent: true});

$("html,body").animate({ scrollTop: pos }, "slow");


问:
Ruby Api How to change time format to (HH:mm) using Active:model:Serializer?
my db table column name is hora (translation:hour): type time. (Postgres).
Iḿ using Ruby 5.1 to develop my API i have installed gem active model serializer. my problem is that it shows me the field in this format: "hora":"2000-01-01T11:40:00Z", but i need only the hour with its minutes just like this: 11:40.
this is my actual output json
{"fecha":"2016-08-02","hora":"2000-01-01T11:40:00Z","importe":"86.0","medico":....}.

i need this:
{"fecha":"2016-08-02","hora":"11:40","importe":"86.0","medico":...}

```<code>my table
|hora                  |
|time withotu time zone|
| 09:30:00             |
| 11:40:00             |
| 10:10:00             |

mycontroller#show
 # GET /atencions/1
  def show
    render json: @atencion
  end

my model
class Atencion < ApplicationRecord
    self.table_name = "atencion"
    belongs_to :medico
    belongs_to :paciente_planobrasocial
end

my model serializer
class AtencionSerializer < ActiveModel::Serializer
  belongs_to :medico
  belongs_to :paciente_planobrasocial
  attributes :fecha, :hora, :importe

end
</code>```

is possible? how and where i can change the format of the time...
thanks in advance...

答:
If I recall correctly, it works like this:

```<code>class AtencionSerializer < ActiveModel::Serializer
  belongs_to :medico
  belongs_to :paciente_planobrasocial
  attributes :fecha, :importe
  attribute :hora { object.hora.strftime "%H:%M" }
end
</code>```

see https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#overriding-attribute-methods

Body:
my db table column name is hora (translation:hour): type time. (Postgres).
Iḿ using Ruby 5.1 to develop my API i have installed gem active model serializer. my problem is that it shows me the field in this format: "hora":"2000-01-01T11:40:00Z", but i need only the hour with its minutes just like this: 11:40.
this is my actual output json
{"fecha":"2016-08-02","hora":"2000-01-01T11:40:00Z","importe":"86.0","medico":....}.

i need this:
{"fecha":"2016-08-02","hora":"11:40","importe":"86.0","medico":...}

my table
|hora                  |
|time withotu time zone|
| 09:30:00             |
| 11:40:00             |
| 10:10:00             |

mycontroller#show
 # GET /atencions/1
  def show
    render json: @atencion
  end

my model
class Atencion < ApplicationRecord
    self.table_name = "atencion"
    belongs_to :medico
    belongs_to :paciente_planobrasocial
end

my model serializer
class AtencionSerializer < ActiveModel::Serializer
  belongs_to :medico
  belongs_to :paciente_planobrasocial
  attributes :fecha, :hora, :importe

end

is possible? how and where i can change the format of the time...
thanks in advance...

Body:
If I recall correctly, it works like this:

class AtencionSerializer < ActiveModel::Serializer
  belongs_to :medico
  belongs_to :paciente_planobrasocial
  attributes :fecha, :importe
  attribute :hora { object.hora.strftime "%H:%M" }
end

see https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#overriding-attribute-methods


问:
Different Prometheus scrape URL for every target
Every instance of my application has a different URL.
How can I configure prometheus.yml so that it takes path of a target along with the host name?</p>

```<code>scrape_configs:
- job_name:       'example-random'

# Override the global default and scrape targets from this job every 5 seconds.
scrape_interval: 5s

static_configs:
  - targets: ['localhost:8090','localhost:8080']
    labels:
      group: 'dummy'
</code>```

答:
I believe you need to do some relabelling of the __metrics_path__ label set to include the varying paths of your applications.

The Prometheus configuration docs will prove useful to you here and this article should help you understand relabelling a little better.

ContentLicense: CC BY-SA 4.0

Body:
Every instance of my application has a different URL.
How can I configure prometheus.yml so that it takes path of a target along with the host name?

scrape_configs:
- job_name:       'example-random'

# Override the global default and scrape targets from this job every 5 seconds.
scrape_interval: 5s

static_configs:
  - targets: ['localhost:8090','localhost:8080']
    labels:
      group: 'dummy'


问:
displaying the next hidden div with same class name
i created an array of similar elements in mvc razor which are hidden

```<code>  <button type="button" class="btn btn-primary addit" id="add"><i class="fa
  fa-plus"></i> Add Branch</button>
 <div id="parnt">
    @for (int w = 0; w < 10; ++w)
       {
         ViewBag.Branch = "branchform" + w;

         <div class="col-md-6 formBranch" id="@ViewBag.Branch" hidden="hidden" >
            <div class="jarviswidget Widget_margin col-md-10" data-widget-
    editbutton="false" data-widget-colorbutton="false" data-widget-
 deletebutton="true" data-widget-fullscreenbutton="false">

                <header>
                    <div class="jarviswidget-ctrls" role="menu" id="deleteButton" onclick="Remove('@ViewBag.Branch')"><a href="javascript:void(0);" class="button-icon jarviswidget-delete-btn" rel="tooltip" title=""><i class="fa fa-times"></i></a></div>

                    @*<span class="widget-icon"> <i class="fa fa-arrows-v"></i> </span>*@
                    <h2 class="font-md">Branch <span id="branchTitle">@w</span></h2>
                </header>

                <!-- widget div-->
                <div>

                    <!-- widget edit box -->
                    <div class="jarviswidget-editbox">
                        <!-- This area used as dropdown edit box -->

                    </div>
                    <!-- end widget edit box -->
                    <!-- widget content -->
                    <div class="widget-body form-horizontal" style="min-height:30px;">

                        <div class="form-group">
                            @Html.Label("Branch Type", new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <select class="form-control" name="BranchId[]" id="BranchId1"><option>Head Office</option></select>
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.Label("Branch Name", htmlAttributes: new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="Branch[]" id="Branch1" />
                            </div>

                        </div>

                        <div class="form-group">
                            @Html.Label("Address", htmlAttributes: new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="Address[]" id="Address1" />
                            </div>

                        </div>

                        <div class="form-group">
                            @Html.Label("Address 2", htmlAttributes: new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="Address2[]" id="Address21" />
                            </div>

                        </div>

                        <div class="form-group">
                            @Html.Label("City", new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <input type="text" class="form-control" name="City[]" id="City1" />
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.Label("State", new { @class = "col-md-2 control-label" })
                            <div class="col-md-9">
                                <select class="form-control" name="State[]" id="State1"><option>Lagos</option></select>
                            </div>
                        </div>

                    </div>

                </div>
            </div>
        </div>

    }
</div>
</code>```

how do i show the next hidden div in the array of div. i.e if first div is shown display the next available hidden div on button click using jquery.

i tried...

```<code>    jQuery(document).on("click", ".addit", function (e) {
        e.preventDefault();

        $("#parnt").next('.formBranch').show();

    })
</code>```

答:
Try This jQuery code</p>

```<code>jQuery(document).ready(function () {
            jQuery(document).on("click", ".addit", function (e) {
                jQuery(".formBranch:visible:last").next(".formBranch").show();
            });
        });
</code>```

Body:
i created an array of similar elements in mvc razor which are hidden

  <button type="button" class="btn btn-primary addit" id="add"> Add Branch</button>

    @for (int w = 0; w < 10; ++w)
       {
         ViewBag.Branch = "branchform" + w;

                    @*  *@

Branch @w

                            @Html.Label("Branch Type", new { @class = "col-md-2 control-label" })

                                <select class="form-control" name="BranchId[]" id="BranchId1"><option>Head Office</option></select>

                            @Html.Label("Branch Name", htmlAttributes: new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="Branch[]" id="Branch1" />

                            @Html.Label("Address", htmlAttributes: new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="Address[]" id="Address1" />

                            @Html.Label("Address 2", htmlAttributes: new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="Address2[]" id="Address21" />

                            @Html.Label("City", new { @class = "col-md-2 control-label" })

                                <input type="text" class="form-control" name="City[]" id="City1" />

                            @Html.Label("State", new { @class = "col-md-2 control-label" })

                                <select class="form-control" name="State[]" id="State1"><option>Lagos</option></select>

    }

how do i show the next hidden div in the array of div. i.e if first div is shown display the next available hidden div on button click using jquery.

i tried...

    jQuery(document).on("click", ".addit", function (e) {
        e.preventDefault();

        $("#parnt").next('.formBranch').show();

    })

Body:
Try This jQuery code

jQuery(document).ready(function () {
            jQuery(document).on("click", ".addit", function (e) {
                jQuery(".formBranch:visible:last").next(".formBranch").show();
            });
        });


问:
How can I access mobx store in another mobx store?
Assume following structure

```<code>stores/
  RouterStore.js
  UserStore.js
  index.js
</code>```

each of ...Store.js files is a mobx store class containing @observable and @action. index.js just exports all stores, so

```<code>import router from "./RouterStore";
import user from "./UserStore";

export default {
  user,
  router
};
</code>```

What is correct way to access one store inside another? i.e. inside my UserStore, I need to dispatch action from RouterStore when users authentication changes.

I tired import store from "./index" inside UserStore and then using store.router.transitionTo("/dashboard") (transitionTo) is an action within RouterStore class.

But this doesn't seem to work correctly.

答:
Your propose solution doesn't work because you are interested in the instance of the store which contains the observed values instead of the Store class which has no state.

Given that you don't have any loop between store dependencies, you could pass one store as a constructor argument to another store.

Something like:

```<code>routerStore = new RouterStore();
userStore = new UserStore(routerStore);

stores = {user: userStore, router: routerStore};
</code>```

Here you pass the routerStore instance to the userStore, which means that it'll be available. For example:

```<code>class UserStore {
    routerStore;
    constructor(router) {
        this.routerStore = router
    };

    handleLoggedIn = () => {
         this.routerStore.transitionTo("/dashboard")
         // Here the router has an observable/actions/... set up when it's initialized. So we just call the action and it all works.
    }
}
</code>```

Another way could be to pass the other store (say routerStore) as an argument when calling a function that is in userStore.

Body:
Assume following structure

stores/
  RouterStore.js
  UserStore.js
  index.js

each of ...Store.js files is a mobx store class containing @observable and @action. index.js just exports all stores, so

import router from "./RouterStore";
import user from "./UserStore";

export default {
  user,
  router
};

What is correct way to access one store inside another? i.e. inside my UserStore, I need to dispatch action from RouterStore when users authentication changes.

I tired import store from "./index" inside UserStore and then using store.router.transitionTo("/dashboard") (transitionTo) is an action within RouterStore class.

But this doesn't seem to work correctly.

Body:
Your propose solution doesn't work because you are interested in the instance of the store which contains the observed values instead of the Store class which has no state.

Given that you don't have any loop between store dependencies, you could pass one store as a constructor argument to another store.

Something like:

routerStore = new RouterStore();
userStore = new UserStore(routerStore);

stores = {user: userStore, router: routerStore};

Here you pass the routerStore instance to the userStore, which means that it'll be available. For example:

class UserStore {
    routerStore;
    constructor(router) {
        this.routerStore = router
    };

    handleLoggedIn = () => {
         this.routerStore.transitionTo("/dashboard")
         // Here the router has an observable/actions/... set up when it's initialized. So we just call the action and it all works.
    }
}

Another way could be to pass the other store (say routerStore) as an argument when calling a function that is in userStore.


问:
NullPointerException when using multiple stepdefinitions in Cucumber-jvm
I am currently building a framework to test a Rest-API endpoint. As I am planning to write a lot of test cases, I decided to organize the project to allow me to reuse common Step Definition methods.

The structure is as follows;

```<code>FunctionalTest
    com.example.steps
        -- AbstractEndpointSteps.java
        -- SimpleSearchSteps.java
    com.example.stepdefinitions
        -- CommonStepDefinition.java
        -- SimpleSearchStepDefinition.java`
</code>```

However when I try to call SimpleSearchSteps.java methods I get a NullPointerException

CommonStepDefinition Code

```<code>package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;

import com.example.functionaltest.steps.AbstractEndpointSteps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CommonStepDefinition {

    @Steps
    private AbstractEndpointSteps endpointSteps;

    @Given("^a base uri \"([^\"]*)\" and base path \"([^\"]*)\"$")
    public void aBaseUriAndBasePath(String baseURI, String basePath) {
        endpointSteps.givenBasepath(baseURI, basePath);
    }

    @When("^country is \"([^\"]*)\"$")
    public void countryIs(String country)
    {
        endpointSteps.whenCountry(country);
    }

    @Then("^the status code is (\\d+)$")
    public void theStatusCodeIs(int statusCode) {
        endpointSteps.executeRequest();
        endpointSteps.thenTheStatusCodeIs200(statusCode);
    }

}
</code>```

SimpleSearchStepDefinition.java

```<code>package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;
import com.example.functionaltest.steps.EndpointSteps;
import cucumber.api.java.en.When;

public class SimpleSearchStepDefinition {

    @Steps
    private SimpleSearchSteps searchSteps;

    @When("^what is \"([^\"]*)\"$")
    public void whatIs(String what) {
        searchSteps.whenWhatIsGiven(what);
    }

}
</code>```

答:
Looks like you are missing holder class for Cucumber annotation, something like this you should have so that cucumber knows and identified that steps and features of yours:

```<code>@RunWith(Cucumber.class)
@CucumberOptions(
    glue = {"com.example.functionaltest.features.steps"},
    features = {"classpath:functionaltest/features"}
)
public class FunctionalTest {
}
</code>```

Note that, in your src/test/resources you should have functionaltest/features folder with your .feature files according to this sample, you can ofc, change it by your design

Body:
I am currently building a framework to test a Rest-API endpoint. As I am planning to write a lot of test cases, I decided to organize the project to allow me to reuse common Step Definition methods.

The structure is as follows;

FunctionalTest
    com.example.steps
        -- AbstractEndpointSteps.java
        -- SimpleSearchSteps.java
    com.example.stepdefinitions
        -- CommonStepDefinition.java
        -- SimpleSearchStepDefinition.java`

However when I try to call SimpleSearchSteps.java methods I get a NullPointerException

CommonStepDefinition Code

package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;

import com.example.functionaltest.steps.AbstractEndpointSteps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class CommonStepDefinition {

    @Steps
    private AbstractEndpointSteps endpointSteps;

    @Given("^a base uri \"([^\"]*)\" and base path \"([^\"]*)\"$")
    public void aBaseUriAndBasePath(String baseURI, String basePath) {
        endpointSteps.givenBasepath(baseURI, basePath);
    }

    @When("^country is \"([^\"]*)\"$")
    public void countryIs(String country)
    {
        endpointSteps.whenCountry(country);
    }

    @Then("^the status code is (\\d+)$")
    public void theStatusCodeIs(int statusCode) {
        endpointSteps.executeRequest();
        endpointSteps.thenTheStatusCodeIs200(statusCode);
    }

}

SimpleSearchStepDefinition.java

package com.example.functionaltest.features.stepdefinitions;

import net.thucydides.core.annotations.Steps;
import com.example.functionaltest.steps.EndpointSteps;
import cucumber.api.java.en.When;

public class SimpleSearchStepDefinition {

    @Steps
    private SimpleSearchSteps searchSteps;

    @When("^what is \"([^\"]*)\"$")
    public void whatIs(String what) {
        searchSteps.whenWhatIsGiven(what);
    }

}

Body:
Looks like you are missing holder class for Cucumber annotation, something like this you should have so that cucumber knows and identified that steps and features of yours:

@RunWith(Cucumber.class)
@CucumberOptions(
    glue = {"com.example.functionaltest.features.steps"},
    features = {"classpath:functionaltest/features"}
)
public class FunctionalTest {
}

Note that, in your src/test/resources you should have functionaltest/features folder with your .feature files according to this sample, you can ofc, change it by your design


问:
issue with legend boxes in ChartJS
we are using Chartjs for some graphs and having an issue with cliackable legend boxes, as they are being displayed in some cases and not displayed in other cases as in the below snapshots :

The case that we have observed for displaying these boxes is when the page auto refreshes while it is minimized.

Can anyone please let us know what is wrong here?

Thanks a lot in advance

答:
It could be due to the fact that your canvas isn't big enough to fit your legend at small enough sizes.

One solution would be to create a custom legend that is completely separate from the canvas. This can be done using the legendcallback function.
e.g

```<code>legendCallback: function (chartInstance) {
    //Generate legend here
}
</code>```

Also, make sure that you have

```<code>responsive: true
</code>```

set in your chart options.

Hope this helps!

Title: issue with legend boxes in ChartJS

Body:
It could be due to the fact that your canvas isn't big enough to fit your legend at small enough sizes.

One solution would be to create a custom legend that is completely separate from the canvas. This can be done using the legendcallback function.
e.g

legendCallback: function (chartInstance) {
    //Generate legend here
}

Also, make sure that you have

responsive: true

set in your chart options.

Hope this helps!


问:
How to update the Hibernate Entity Record when only few fields of entity obj are modified and remaining fields should not be null
is there any other different solution for this code.
for every pojo class we have to check that modified data coming from browser and we will store only modified data into the database.

see below billingTax  obj is coming from browser which is updated data
and billingtaxDbObject obj is retrieved from database and we will check with if condition whether updated data is changed or not

if pojo class has 20 fields, we have to write 20 if conditions
if pojo class has 5 fields, we have to write 5 if conditions

instead of writing if conditions for checking wheter data is modified or nor is there any other simplest way?

```<code>@Override

    public BillingTax update(BillingTax billingTax) throws DataInsufficientException, RecordNotFoundException {
        log.debug("BillingTaxServiceImpl.update()....................");
    try {

        if (billingTax == null)
            throw new DataInsufficientException("billingTax object is null");

        BillingTax billingtaxDbObject = get(billingTax.getId());

        if (billingtaxDbObject == null)
            throw new RecordNotFoundException("billingTax object is not found in database");

        if (billingTax.getTaxApplyType() != null
                && !billingTax.getTaxApplyType().equals(billingtaxDbObject.getTaxApplyType()))
            billingtaxDbObject.setTaxApplyType(billingTax.getTaxApplyType());

        if (billingTax.getCode() != null && !billingTax.getCode().trim().equalsIgnoreCase("null")
                && !billingTax.getCode().equalsIgnoreCase(billingtaxDbObject.getCode()))
            billingtaxDbObject.setCode(billingTax.getCode());

        if (billingTax.getName() != null && !billingTax.getName().trim().equalsIgnoreCase("null")
                && !billingTax.getName().equalsIgnoreCase(billingtaxDbObject.getName()))
            billingtaxDbObject.setName(billingTax.getName());

        if (billingTax.getDescription() != null && !billingTax.getDescription().trim().equalsIgnoreCase("null")
                && !billingTax.getDescription().equalsIgnoreCase(billingtaxDbObject.getDescription()))
            billingtaxDbObject.setDescription(billingTax.getDescription());

        if (billingTax.getServiceTypeForTax() != null
                && !billingTax.getServiceTypeForTax().equals(billingtaxDbObject.getServiceTypeForTax()))
            billingtaxDbObject.setServiceTypeForTax(billingTax.getServiceTypeForTax());

        if (billingTax.getTaxValue() != null && !billingTax.getTaxValue().equals("null")
                && !billingTax.getTaxValue().equals(billingtaxDbObject.getTaxValue()))
            billingtaxDbObject.setTaxValue(billingTax.getTaxValue());

        if (billingTax.getStatus() != null && !billingTax.getStatus().equals(billingtaxDbObject.getStatus()))
            billingtaxDbObject.setStatus(billingTax.getStatus());

        if (billingTax.getOrderNo() != null && !billingTax.getOrderNo().equals("null")
                && !billingTax.getOrderNo().equals(billingtaxDbObject.getOrderNo()))
            billingtaxDbObject.setOrderNo(billingTax.getOrderNo());

        if (billingTax.getId() != null && !billingTax.getId().trim().equalsIgnoreCase(billingtaxDbObject.getId())
                && !billingTax.getId().equalsIgnoreCase(billingtaxDbObject.getId()))
            billingtaxDbObject.setId(billingTax.getId());

        if (billingTax.getStartDate()!= null && !billingTax.getStartDate().equals(billingtaxDbObject.getStartDate()))
            billingtaxDbObject.setStartDate(billingTax.getStartDate());

        if (billingTax.getEndDate()!= null && !billingTax.getEndDate().equals(billingtaxDbObject.getEndDate()))
            billingtaxDbObject.setEndDate(billingTax.getEndDate());

        billingtaxDbObject.setUpdatedDate(new Date());
        return billingTaxDAO.update(billingtaxDbObject);

    } catch (Exception e) {
        log.error("BillingTaxServiceImpl.update()....................exception:" + e.getMessage());
        throw e;
    }
}
</code>```

答:
this is developed by getting all the fields/properties from the pojo class and checking with wheter null data or modified data.
below is the code:

copyProperties(billingTax, billingtaxDbObject);

public void copyProperties(BillingTax source, BillingTax dest) throws Exception{

```<code>    if (source == null)
        throw new DataInsufficientException("billingTax object is null");

    if (dest == null)
        throw new RecordNotFoundException("billingtaxDbObject object is not found in database");

    try{
        for (Field field : source.getClass().getDeclaredFields()) {

            field.setAccessible(true);
            Object sourceValue = field.get(source);
            Object destValue=field.get(dest);

            if(sourceValue!=null && sourceValue!="" && sourceValue!="null"){

                if(sourceValue instanceof String){
                    if(!sourceValue.toString().trim().equalsIgnoreCase("null")){
                        if(!sourceValue.toString().equalsIgnoreCase(destValue.toString())){
                            field.set(dest, sourceValue);
                            System.err.println(field.getName()+" is modified:"+field.get(dest));
                        }
                    }
                }
                else{
                    if(!sourceValue.equals("null") && !sourceValue.equals(destValue)){
                        field.set(dest, sourceValue);
                        System.err.println(field.getName()+" is modified:"+field.get(dest));
                    }
                }
            }
        }
        System.out.println();
    }catch (Exception e) {
         throw e;
    }
}
</code>```

Body:
is there any other different solution for this code.
for every pojo class we have to check that modified data coming from browser and we will store only modified data into the database.

see below billingTax  obj is coming from browser which is updated data
and billingtaxDbObject obj is retrieved from database and we will check with if condition whether updated data is changed or not

if pojo class has 20 fields, we have to write 20 if conditions
if pojo class has 5 fields, we have to write 5 if conditions

instead of writing if conditions for checking wheter data is modified or nor is there any other simplest way?

@Override

    public BillingTax update(BillingTax billingTax) throws DataInsufficientException, RecordNotFoundException {
        log.debug("BillingTaxServiceImpl.update()....................");
    try {

        if (billingTax == null)
            throw new DataInsufficientException("billingTax object is null");

        BillingTax billingtaxDbObject = get(billingTax.getId());

        if (billingtaxDbObject == null)
            throw new RecordNotFoundException("billingTax object is not found in database");

        if (billingTax.getTaxApplyType() != null
                && !billingTax.getTaxApplyType().equals(billingtaxDbObject.getTaxApplyType()))
            billingtaxDbObject.setTaxApplyType(billingTax.getTaxApplyType());

        if (billingTax.getCode() != null && !billingTax.getCode().trim().equalsIgnoreCase("null")
                && !billingTax.getCode().equalsIgnoreCase(billingtaxDbObject.getCode()))
            billingtaxDbObject.setCode(billingTax.getCode());

        if (billingTax.getName() != null && !billingTax.getName().trim().equalsIgnoreCase("null")
                && !billingTax.getName().equalsIgnoreCase(billingtaxDbObject.getName()))
            billingtaxDbObject.setName(billingTax.getName());

        if (billingTax.getDescription() != null && !billingTax.getDescription().trim().equalsIgnoreCase("null")
                && !billingTax.getDescription().equalsIgnoreCase(billingtaxDbObject.getDescription()))
            billingtaxDbObject.setDescription(billingTax.getDescription());

        if (billingTax.getServiceTypeForTax() != null
                && !billingTax.getServiceTypeForTax().equals(billingtaxDbObject.getServiceTypeForTax()))
            billingtaxDbObject.setServiceTypeForTax(billingTax.getServiceTypeForTax());

        if (billingTax.getTaxValue() != null && !billingTax.getTaxValue().equals("null")
                && !billingTax.getTaxValue().equals(billingtaxDbObject.getTaxValue()))
            billingtaxDbObject.setTaxValue(billingTax.getTaxValue());

        if (billingTax.getStatus() != null && !billingTax.getStatus().equals(billingtaxDbObject.getStatus()))
            billingtaxDbObject.setStatus(billingTax.getStatus());

        if (billingTax.getOrderNo() != null && !billingTax.getOrderNo().equals("null")
                && !billingTax.getOrderNo().equals(billingtaxDbObject.getOrderNo()))
            billingtaxDbObject.setOrderNo(billingTax.getOrderNo());

        if (billingTax.getId() != null && !billingTax.getId().trim().equalsIgnoreCase(billingtaxDbObject.getId())
                && !billingTax.getId().equalsIgnoreCase(billingtaxDbObject.getId()))
            billingtaxDbObject.setId(billingTax.getId());

        if (billingTax.getStartDate()!= null && !billingTax.getStartDate().equals(billingtaxDbObject.getStartDate()))
            billingtaxDbObject.setStartDate(billingTax.getStartDate());

        if (billingTax.getEndDate()!= null && !billingTax.getEndDate().equals(billingtaxDbObject.getEndDate()))
            billingtaxDbObject.setEndDate(billingTax.getEndDate());

        billingtaxDbObject.setUpdatedDate(new Date());
        return billingTaxDAO.update(billingtaxDbObject);

    } catch (Exception e) {
        log.error("BillingTaxServiceImpl.update()....................exception:" + e.getMessage());
        throw e;
    }
}

Body:
this is developed by getting all the fields/properties from the pojo class and checking with wheter null data or modified data.
below is the code:

copyProperties(billingTax, billingtaxDbObject);

public void copyProperties(BillingTax source, BillingTax dest) throws Exception{

    if (source == null)
        throw new DataInsufficientException("billingTax object is null");

    if (dest == null)
        throw new RecordNotFoundException("billingtaxDbObject object is not found in database");

    try{
        for (Field field : source.getClass().getDeclaredFields()) {

            field.setAccessible(true);
            Object sourceValue = field.get(source);
            Object destValue=field.get(dest);

            if(sourceValue!=null && sourceValue!="" && sourceValue!="null"){

                if(sourceValue instanceof String){
                    if(!sourceValue.toString().trim().equalsIgnoreCase("null")){
                        if(!sourceValue.toString().equalsIgnoreCase(destValue.toString())){
                            field.set(dest, sourceValue);
                            System.err.println(field.getName()+" is modified:"+field.get(dest));
                        }
                    }
                }
                else{
                    if(!sourceValue.equals("null") && !sourceValue.equals(destValue)){
                        field.set(dest, sourceValue);
                        System.err.println(field.getName()+" is modified:"+field.get(dest));
                    }
                }
            }
        }
        System.out.println();
    }catch (Exception e) {
         throw e;
    }
}


问:
Number comparision in java
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome. </p>

```<code>package com.practise.examples;

import java.util.Scanner;

public class Practise
{
    public static void main(String[] args) {

        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        int revNum=0;

        while(num!=0)
        {
            revNum=revNum *10;
            revNum= revNum+ num%10;
            num=num/10;
        }
        System.out.println("the reverse of the number is: " +revNum);

            if(revNum==num)
            {
                System.out.println("the number is a palindrome" );

            }
            else
            {
                System.out.println("the number entered is not a palindrome");

            }

        }
    }
</code>```

答:
you can cast your number to a string and check doe's its palindrome?</p>

```<code>import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        if (isPalindrome(num+"")){
            System.out.println("the number is a palindrome" );
        }else{
            System.out.println("the number entered is not a palindrome");
        }
    }
    public static boolean isPalindrome(String s) {
        int n = s.length();
        for (int i = 0; i < (n/2); ++i) {
            if (s.charAt(i) != s.charAt(n - i - 1)) {
                return false;
            }
        }

        return true;
    }
}
</code>```

Title: Number comparision in java

Body:
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome.

package com.practise.examples;

import java.util.Scanner;

public class Practise
{
    public static void main(String[] args) {

        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        int revNum=0;

        while(num!=0)
        {
            revNum=revNum *10;
            revNum= revNum+ num%10;
            num=num/10;
        }
        System.out.println("the reverse of the number is: " +revNum);

            if(revNum==num)
            {
                System.out.println("the number is a palindrome" );

            }
            else
            {
                System.out.println("the number entered is not a palindrome");

            }

        }
    }

Body:
you can cast your number to a string and check doe's its palindrome?

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        System.out.println("enter the number to reverse it:\n");
        int num=s.nextInt();
        if (isPalindrome(num+"")){
            System.out.println("the number is a palindrome" );
        }else{
            System.out.println("the number entered is not a palindrome");
        }
    }
    public static boolean isPalindrome(String s) {
        int n = s.length();
        for (int i = 0; i < (n/2); ++i) {
            if (s.charAt(i) != s.charAt(n - i - 1)) {
                return false;
            }
        }

        return true;
    }
}


问:
Application appears to have two session cookies
In my application I'm seeing it's setting two session cookies:

.AspNet.ApplicationCookie

ASP.NET_SessionId

I can understand the requirement for a session cookie but why have two?  What are the specific purposes of each?

I'm using asp.net identity in case that has something to do with it.

答:
.AspNet.ApplicationCookie basically is created when you use cookie authentication in your application. This cookie is created by the server on user request and is stored by the browser.

AspNet.ApplicationCookie gets sent with each subsequent request to inform the server the identity of the logged in user. It usually gets deleted when the user logs out(depends on expiry interval).

ASP.NET_SessionId cookie gets automatically created by Asp.net. There is no control over this cookie. It is created for the first time when the application is accessed by a user.

Even if the user has logged out, this cookie and its value are not deleted by the browser.
This is because when the session is abandoned, any new requests to the same application will use the same session ID but will have a new session state instance.


问:
String Pattern Question - Core Java (repeatSeparator)
Write a Java function such that Given two strings, word and a separator, return a big string made of count occurences of the word, separated by the separator string.

```<code>repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"
</code>```

My code is as below but is not working

```<code>public String repeatSeparator(String word, String sep, int count) {
    if(count == 1) {
        return word;
    }
    if(count > 1) {
        for (int i = 0; i < count-1; i++){
            word = word + sep + word;
        }
    }
   return word;
}
</code>```

Example Output ::

```<code>                                   Expected         Run                  Result
repeatSeparator("Word", "X", 3) → "WordXWordXWord" "WordXWordXWordXWord" X
</code>```

答:
```<code>public String repeatSeparator(String word, String sep, int count) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < count; i++) {
    sb.append(word);
    if (i < count - 1)
        sb.append(sep);
    }
    return sb.toString();
}
</code>```

In real life, would use Apache Common Lang StringUtils.repeat

Body:
Write a Java function such that Given two strings, word and a separator, return a big string made of count occurences of the word, separated by the separator string.

repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"

My code is as below but is not working

public String repeatSeparator(String word, String sep, int count) {
    if(count == 1) {
        return word;
    }
    if(count > 1) {
        for (int i = 0; i < count-1; i++){
            word = word + sep + word;
        }
    }
   return word;
}

Example Output ::

                                   Expected         Run                  Result
repeatSeparator("Word", "X", 3) → "WordXWordXWord" "WordXWordXWordXWord" X

Body:
public String repeatSeparator(String word, String sep, int count) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < count; i++) {
    sb.append(word);
    if (i < count - 1)
        sb.append(sep);
    }
    return sb.toString();
}

In real life, would use Apache Common Lang StringUtils.repeat


问:
how to read data of foreign key though eval using asp.net?
Just to have an idea of my database. I have two tables called brand and stringInstrumentItem. the table brand have columns called brandId,name and image. While the stringInstrumentItem have a column of itemId,brand,model and price.Normally i would be able to display data of column brand and model of table stringInstrumentItem through this code:

```<code><div id="label"><%# Eval("brand") %> <%# Eval("model") %></div>
</code>```

The output in my webpage would be: Ibanez AB30

But now that i'm trying to learn about relational database and foreign keys. I changed the column named brand of stringInstrumentItem to brandId. Now, the column brandId,which is the foreign key for table stringInstrumentItem references the primary key of table brand called brandId as well.

The problem is, I cannot do the same thing anymore. If i try to do this line of code:

```<code><div id="label"><%# Eval("brandId") %> <%# Eval("model") %></div>
</code>```

It will give me this output: 1 AB30

Instead of the actual string, it is giving me the id instead. My question is, how do i access the column called name of table brand through the relationship of brandId(foreign key) of table stringInstrumentItem to brandId(primary key) of table brand???

Take note, i haven't coded anything in my code-behind to make this work. it is all code inline. Kindly give advice and solution for this.

答:
Your select statement will need now to join the 2 tables as so:

```<code>SELECT  brandid ,
    brand ,
    model
FROM    brand
    JOIN stringInstrumentItem ON stringInstrumentItem.brandid = brand.brandid;
</code>```

Now you will get both, brandid and brand in the output and you can Eval as you need to; in this case, you will need to <%# Eval("brand") %> again but you will also get brandid if you need to perform some action based on the unique id of the brand.

Update

Change your SELECT statement to:

```<code>SELECT  *
FROM    stringInstrumentItem
        JOIN brand ON stringInstrumentItem.brandid = brand.brandid
WHERE   brandId IN ( SELECT brandId
                     FROM   brand
                     WHERE  name = @brand );
</code>```

Body:
Just to have an idea of my database. I have two tables called brand and stringInstrumentItem. the table brand have columns called brandId,name and image. While the stringInstrumentItem have a column of itemId,brand,model and price.Normally i would be able to display data of column brand and model of table stringInstrumentItem through this code:

<%# Eval("brand") %> <%# Eval("model") %>

The output in my webpage would be: Ibanez AB30

But now that i'm trying to learn about relational database and foreign keys. I changed the column named brand of stringInstrumentItem to brandId. Now, the column brandId,which is the foreign key for table stringInstrumentItem references the primary key of table brand called brandId as well.

The problem is, I cannot do the same thing anymore. If i try to do this line of code:

<%# Eval("brandId") %> <%# Eval("model") %>

It will give me this output: 1 AB30

Instead of the actual string, it is giving me the id instead. My question is, how do i access the column called name of table brand through the relationship of brandId(foreign key) of table stringInstrumentItem to brandId(primary key) of table brand???

Take note, i haven't coded anything in my code-behind to make this work. it is all code inline. Kindly give advice and solution for this.

Body:
Your select statement will need now to join the 2 tables as so:

SELECT  brandid ,
    brand ,
    model
FROM    brand
    JOIN stringInstrumentItem ON stringInstrumentItem.brandid = brand.brandid;

Now you will get both, brandid and brand in the output and you can Eval as you need to; in this case, you will need to <%# Eval("brand") %> again but you will also get brandid if you need to perform some action based on the unique id of the brand.

Update

Change your SELECT statement to:

SELECT  *
FROM    stringInstrumentItem
        JOIN brand ON stringInstrumentItem.brandid = brand.brandid
WHERE   brandId IN ( SELECT brandId
                     FROM   brand
                     WHERE  name = @brand );