问:
How to use select query inside the select column name by iterating column row values using oracle?
Query:

```<code>select column_one, column_two, column_three
from main_tbl_name
</code>```

Output:

```<code>column_one  column_two
--------------------------------------------------------------------------------
data1       SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE
data2       SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA
data3       DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS
</code>```

I have another query:

```<code>select column_one, column_two, column_three
from another_tbl_name
where column_four in (main_tbl_name.column_two)
</code>```

I need to split up the values of main_tbl_name.column_two into for example like ('SBANAR','SBARTO','SCBADP','SCCHBA','SCHPIT','SCTHAB','SDPCLV','SDPRPN','SDPSEC','SERIE')

In the above second query if some of the values exist, append each iterated value in main_tbl_name.column_three

So my final output should be

```<code>column_one  column_two                                                                  column_three
-------------------------------------------------------------------------------------------------------------------------
data1       SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE        SBANAR SBARTO SCCHBA SDPCLV SDPSEC
data2       SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA                            SRALEN SSCMAR SSDECA
data3       DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS                              DRAP14 E05A ESPHSA ESS
</code>```

答:
Here is an example with data similiar to yours:

```<code>with

-- sample data
  main_tbl_name ( column_one,  column_two) as (
    select 'data1', 'SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE'
      from dual union all
    select 'data2', 'SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA'
      from dual union all
    select 'data3', 'DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS' from dual ),
  another_tbl_name(column_four) as (
    select 'SDPSEC SBANAR SBARTO SCCHBA SDPCLV' from dual union all
    select 'DRAP14 E05A ESPHSA ESS' from dual),
  -- end of sample data

  t1 as (select column_one c1, column_two c2, '"'||replace(column_two, ' ', '", "')||'"' cx
           from main_tbl_name),
  t2 as (select '"'||replace(column_four, ' ', '", "')||'"' cx
           from another_tbl_name)
select c1, c2, listagg(b.cs, ' ') within group (order by b.cs) c3
  from (select c1, c2, trim(column_value) cs from t1, xmltable(cx)) a
  left join (select trim(column_value) cs from t2, xmltable(cx)) b on a.cs = b.cs
  group by c1, c2
</code>```

... which results:

```<code>C1    C2                                                                   C3
----- -------------------------------------------------------------------- -------------------------------
data1 SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE SBANAR SBARTO SCCHBA SDPCLV SDPSEC
data2 SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA
data3 DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS                       DRAP14 E05A ESPHSA ESS
</code>```

demo

This solution is based on xmltable, left join and listagg(). I assumed that single space is the separator. If another_table contains data not in the form of list then you can even simplify this query.

Basically you have to split list columns then make join. There are also other ways to do this like hierarchical queries, PLSQL functions, already posted on SO. Use whatever method which suits you.

Body:
Query:

select column_one, column_two, column_three
from main_tbl_name

Output:

column_one  column_two
--------------------------------------------------------------------------------
data1       SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE
data2       SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA
data3       DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS

I have another query:

select column_one, column_two, column_three
from another_tbl_name
where column_four in (main_tbl_name.column_two)

I need to split up the values of main_tbl_name.column_two into for example like ('SBANAR','SBARTO','SCBADP','SCCHBA','SCHPIT','SCTHAB','SDPCLV','SDPRPN','SDPSEC','SERIE')

In the above second query if some of the values exist, append each iterated value in main_tbl_name.column_three

So my final output should be

column_one  column_two                                                                  column_three
-------------------------------------------------------------------------------------------------------------------------
data1       SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE        SBANAR SBARTO SCCHBA SDPCLV SDPSEC
data2       SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA                            SRALEN SSCMAR SSDECA
data3       DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS                              DRAP14 E05A ESPHSA ESS

Body:
Here is an example with data similiar to yours:

with

-- sample data
  main_tbl_name ( column_one,  column_two) as (
    select 'data1', 'SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE'
      from dual union all
    select 'data2', 'SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA'
      from dual union all
    select 'data3', 'DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS' from dual ),
  another_tbl_name(column_four) as (
    select 'SDPSEC SBANAR SBARTO SCCHBA SDPCLV' from dual union all
    select 'DRAP14 E05A ESPHSA ESS' from dual),
  -- end of sample data

  t1 as (select column_one c1, column_two c2, '"'||replace(column_two, ' ', '", "')||'"' cx
           from main_tbl_name),
  t2 as (select '"'||replace(column_four, ' ', '", "')||'"' cx
           from another_tbl_name)
select c1, c2, listagg(b.cs, ' ') within group (order by b.cs) c3
  from (select c1, c2, trim(column_value) cs from t1, xmltable(cx)) a
  left join (select trim(column_value) cs from t2, xmltable(cx)) b on a.cs = b.cs
  group by c1, c2

... which results:

C1    C2                                                                   C3
----- -------------------------------------------------------------------- -------------------------------
data1 SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE SBANAR SBARTO SCCHBA SDPCLV SDPSEC
data2 SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA
data3 DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS                       DRAP14 E05A ESPHSA ESS

demo

This solution is based on xmltable, left join and listagg(). I assumed that single space is the separator. If another_table contains data not in the form of list then you can even simplify this query.

Basically you have to split list columns then make join. There are also other ways to do this like hierarchical queries, PLSQL functions, already posted on SO. Use whatever method which suits you.


来源: stackexchange

问:
Sequelize pagination
Using sequelize on my nodejs web app, I want to query posts using pagination (by date). Reading sequelize docs, they offer to use offset and limit.

Since I want to display the posts from new to old, I need to consider the date they were created. For example, if I limit the first query to 10 page, and before executing the second query a new post was created, the next query with offset of 10 will result a duplicate post from the last query.

How should I implement the pagination so it will support new entries?

答:
Try this instead:</p>
```<code>db.findAll({
   offset: page_no,// your page number
      limit:25,// your limit
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sequelize pagination

Body:
Try this instead:

db.findAll({
   offset: page_no,// your page number
      limit:25,// your limit

ContentLicense: CC BY-SA 4.0


问:
ValueError: key must be provided when HDF5 file contains multiple datasets while reading h5 file in pandas i am getting this error
While trying to read a h5 file I get the following error:
 ValueError: key must be provided when HDF5 file contains multiple datasets.

```<code>f=pd.read_hdf('file_path')

ValueError                             Traceback (most recent call last)

384             for group_to_check in groups[1:]:
385                 if not _is_metadata_of(group_to_check, candidate_only_group):

--> 386                     raise ValueError('key must be provided when HDF5 file '
    387                                      'contains multiple datasets.')
    388             key = candidate_only_group._v_pathname

ValueError: key must be provided when HDF5 file contains multiple datasets.
</code>```

Can anyone send me the complete code so that I can resolve this error and work in pandas?

答:
As @AT_asks mentioned in a comment, you have to provide the name of the group that you want to open in the H5 file. If you do not know what the name could be, you can have look at which groups the file contains:

```<code>with pd.HDFStore('file_path') as hdf:
    # This prints a list of all group names:
    print(hdf.keys())

</code>```

Pick one group name, and open it by using the key parameter of read_hdf:

```<code>f = pd.read_hdf('file_path', key='your_group')
</code>```

Body:
While trying to read a h5 file I get the following error:
 ValueError: key must be provided when HDF5 file contains multiple datasets.

f=pd.read_hdf('file_path')

ValueError                             Traceback (most recent call last)

384             for group_to_check in groups[1:]:
385                 if not _is_metadata_of(group_to_check, candidate_only_group):

--> 386                     raise ValueError('key must be provided when HDF5 file '
    387                                      'contains multiple datasets.')
    388             key = candidate_only_group._v_pathname

ValueError: key must be provided when HDF5 file contains multiple datasets.

Can anyone send me the complete code so that I can resolve this error and work in pandas?

Body:
As @AT_asks mentioned in a comment, you have to provide the name of the group that you want to open in the H5 file. If you do not know what the name could be, you can have look at which groups the file contains:

with pd.HDFStore('file_path') as hdf:
    # This prints a list of all group names:
    print(hdf.keys())

Pick one group name, and open it by using the key parameter of read_hdf:

f = pd.read_hdf('file_path', key='your_group')


问:
How to pass a foreign key id from query to the updating row element?
I'm using Slick 3.3.0 and I have a use-case for updating a password table but the look up element is something called a LoginInfo which then links to the target updateable PasswordInfo via its user_id this is a very simplified version of my use case:

```<code>def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
    // first look up a loginInfo by some id, then find the connected userId and use
    // it to update the PasswordInfo.
    val action = (for {
      loginInfo <- LoginInfo if loginInfo.id === id
      passwordInfo <- PasswordInfo if passwordInfo.userId === loginInfo.userId
    } yield passwordInfo).update(PasswordInfoRow(??? /* <<<< I need userId here */, hasher, password, salt))
    db.run(action)
}
</code>```

But after the query yields passwordInfo and I chain the update method I have no access to the userId key.

If were possible I'd need:

```<code>... yield passwordInfo).update(pi => PasswordInfoRow(pi.userId, ...
</code>```

How do do this in Slick?

答:
After some soul searching I solved it like this:</p>

```<code>def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
    // first look up a loginInfo by some id, then find the connected userId and use
    // it to update the PasswordInfo.
    val action = (for {
      userId <- LoginInfo.filter(_.id === id).result.head.map(_.userId)
    } yield userId).flatMap { userId =>
      val updated = PasswordInfoRow(userId, hasher, password, salt)
      PasswordInfo.update(updated).map(_ => updated.toExt)
    }.transactionally()
    db.run(action)
}
</code>```

Body:
I'm using Slick 3.3.0 and I have a use-case for updating a password table but the look up element is something called a LoginInfo which then links to the target updateable PasswordInfo via its user_id this is a very simplified version of my use case:

def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
    // first look up a loginInfo by some id, then find the connected userId and use
    // it to update the PasswordInfo.
    val action = (for {
      loginInfo <- LoginInfo if loginInfo.id === id
      passwordInfo <- PasswordInfo if passwordInfo.userId === loginInfo.userId
    } yield passwordInfo).update(PasswordInfoRow(??? /* <<<< I need userId here */, hasher, password, salt))
    db.run(action)
}

But after the query yields passwordInfo and I chain the update method I have no access to the userId key.

If were possible I'd need:

... yield passwordInfo).update(pi => PasswordInfoRow(pi.userId, ...

How do do this in Slick?

Body:
After some soul searching I solved it like this:

def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
    // first look up a loginInfo by some id, then find the connected userId and use
    // it to update the PasswordInfo.
    val action = (for {
      userId <- LoginInfo.filter(_.id === id).result.head.map(_.userId)
    } yield userId).flatMap { userId =>
      val updated = PasswordInfoRow(userId, hasher, password, salt)
      PasswordInfo.update(updated).map(_ => updated.toExt)
    }.transactionally()
    db.run(action)
}


问:
Error code 16 "CANCELLED" in react-native-google-sign-in
I am trying to implement google sign in on my app and every thing running well , it ask me to choose account on press of sign in button but it response it send me code 16 "CANCELLED" error.

I've installed library by npm install react-native-google-sign-in.
Then I linked it. I created a new project on firebase and download google-services.json from there and paste it in android/app. Also generated release SHA1 and add in firebase project.

```<code>componentDidMount() {
   GoogleSignin.configure({
     //It is mandatory to call this method before attempting to call signIn()
     scopes: ['https://www.googleapis.com/auth/drive.readonly'],
     // Repleace with your webClientId generated from Firebase console
     webClientId:
       'my client id',
   });
 }
</code>```

Google sign in button and action

```<code>
   <TouchableOpacity
     onPress={() => _signIn()}
     style={{height:50,width:50,borderRadius:50}}
   >
      <Image
       style={{height:50,width:50}}
        resizeMode='contain'
        source={ImagePath.GOOGLE_ICON}
     />
   </TouchableOpacity>

  _signIn = async () => {
    //Prompts a modal to let the user sign in into your application.
    try {
      await GoogleSignin.hasPlayServices({
        //Check if device has Google Play Services installed.
        //Always resolves to true on iOS.
        showPlayServicesUpdateDialog: true,
      });
      const userInfo = await GoogleSignin.signIn();
      alert(JSON.stringify(userInfo))
      console.log('User Info --> ', userInfo);
      this.setState({ userInfo: userInfo });
    } catch (error) {
      console.log('Message', error.message);
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        console.log('User Cancelled the Login Flow');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        console.log('Signing In');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        console.log('Play Services Not Available or Outdated');
      } else {
        alert(JSON.stringify(error))
        console.log('Some Other Error Happened',error);
      }
    }
  };
</code>```

These are my signing config

```<code>       release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
</code>```

I expect successful google sign in and user data in response. Any kind of help will be appreciated.Thank you

答: Please share your AndroidManifest.xml file.  Please check whether you have added any launch mode in manifest.  If so please remove. </p>

Body:
I am trying to implement google sign in on my app and every thing running well , it ask me to choose account on press of sign in button but it response it send me code 16 "CANCELLED" error.

I've installed library by npm install react-native-google-sign-in.
Then I linked it. I created a new project on firebase and download google-services.json from there and paste it in android/app. Also generated release SHA1 and add in firebase project.

componentDidMount() {
   GoogleSignin.configure({
     //It is mandatory to call this method before attempting to call signIn()
     scopes: ['https://www.googleapis.com/auth/drive.readonly'],
     // Repleace with your webClientId generated from Firebase console
     webClientId:
       'my client id',
   });
 }

Google sign in button and action

   <TouchableOpacity
     onPress={() => _signIn()}
     style={{height:50,width:50,borderRadius:50}}
   >
      <Image
       style={{height:50,width:50}}
        resizeMode='contain'
        source={ImagePath.GOOGLE_ICON}
     />
   </TouchableOpacity>

  _signIn = async () => {
    //Prompts a modal to let the user sign in into your application.
    try {
      await GoogleSignin.hasPlayServices({
        //Check if device has Google Play Services installed.
        //Always resolves to true on iOS.
        showPlayServicesUpdateDialog: true,
      });
      const userInfo = await GoogleSignin.signIn();
      alert(JSON.stringify(userInfo))
      console.log('User Info --> ', userInfo);
      this.setState({ userInfo: userInfo });
    } catch (error) {
      console.log('Message', error.message);
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        console.log('User Cancelled the Login Flow');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        console.log('Signing In');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        console.log('Play Services Not Available or Outdated');
      } else {
        alert(JSON.stringify(error))
        console.log('Some Other Error Happened',error);
      }
    }
  };

These are my signing config

       release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }

I expect successful google sign in and user data in response. Any kind of help will be appreciated.Thank you


问:
play framework inter-app communication
Since Play currently supports using only one database per application, what's the best way for one Play application to access the data of another?  Are there any better methods than simply fetching data in JSON format?</p>

答:
I believe that the best method is to use a REST call to interact with the other application (if the other application is calling the Play one) or use the WS library to call webservices of the target application if you want to call it from Play.

Personally, I dislike the idea of writing stuff to a "common database/table" as this means both applications must be completely aware of the structure of the table, and any changes on one end will imply changes on the table and the other side. It also means you create a specific channel between these 2 applications that it will be hard to reuse if, in the future,  you want more applications to take part in it.

I would favor using REST (preferably) or SOAP for this. It will decouple the applications and make it simpler (specially with Play). And if for some reason the target app doesn't support REST/SOAP, a simple wrapper application to manage the communication would solve this.

Title: play framework inter-app communication


问:
Vuejs: Event on route change
On my main page I have dropdowns that show v-show=show by clicking on the link @click = "show=!show" and I want to set show=false when I change the route. Please advise me on how to realize this thing.

答:
Watcher with the deep option didn't work for me.

Instead, I use updated() lifecycle hook which gets executed everytime the component's data changes.
Just use it like you do with mounted().

mounted() {
   /* to be executed when mounted */
},
updated() {
   console.log(this.$route)
}
```

For your reference, visit the documentation.

Title: Vuejs: Event on route change

Body:
Watcher with the deep option didn't work for me.

Instead, I use updated() lifecycle hook which gets executed everytime the component's data changes.
Just use it like you do with mounted().

mounted() {
   /* to be executed when mounted */
},
updated() {
   console.log(this.$route)
}

For your reference, visit the documentation.


问:
how can i pass value from javascript to my php function codeigniter
Thank for help and attention.I'm apprentice

I tried this already

if i did it wrong way your can tell me anything.i learning. thanks.

checkfb() is a php function and outside script i want to call checkfb() in script function with pass javascript value.if in php looklike simply pass by value checkfb($fbFName,$fbLName,$Email); ?> but cant do cuz in script scope.i am sorry if i made your misunderstanding.

```<code>function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });

public function checkfb($FName,$LName,$Email){

    print_r('checkfb') ; exit();
  }
  //code work for log in facebook already but i wanna add data into my database

function getCurrentUserInfo() {
<script>
              FB.api('/me?fields=first_name,last_name,email,link,gender,picture', function(userInfo) {

                  fbFName = userInfo.first_name;
                  fbLName = userInfo.last_name;
                  fbEmail = userInfo.email;
                  fbLink = userInfo.link;
                  fbGender = userInfo.gender;
                  fbpicture = userInfo.picture;
                  alert(fbID);
                  console.log(fbID);
                  console.log(fbFName);
                  console.log(fbLName);
                  console.log(fbEmail);

              });
          }
          function checkLoginState() {
              FB.getLoginStatus(function(response){
                  statusChangeCallback(response);
              });
          }
      </script>
</code>```

答:
Just call the JS function, use the php variables as parameters. Change

```<code>function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });
</code>```

to

```<code>function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                   checkfb('<?php=$fbFName?>','<?php=$fbLName?>','<?php=$Email?>'); ?>
              });
</code>```

Body:
Thank for help and attention.I'm apprentice

I tried this already

if i did it wrong way your can tell me anything.i learning. thanks.

checkfb() is a php function and outside script i want to call checkfb() in script function with pass javascript value.if in php looklike simply pass by value checkfb($fbFName,$fbLName,$Email); ?> but cant do cuz in script scope.i am sorry if i made your misunderstanding.

function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });

public function checkfb($FName,$LName,$Email){

    print_r('checkfb') ; exit();
  }
  //code work for log in facebook already but i wanna add data into my database

function getCurrentUserInfo() {

Body:
Just call the JS function, use the php variables as parameters. Change

function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });

to

function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                   checkfb('<?php=$fbFName?>','<?php=$fbLName?>','<?php=$Email?>'); ?>
              });


问:
Identify Locale Date string correctly
I have a date string that is formatted depending on the language/locale of the browser. For example, "03/05/2019" in en-US is March 5, 2019 (mm/dd/yyyy) but in en-NZ, it's May 3, 2019 (dd/mm/yyyy).

I need to know how to convert the string to date using JavaScript with the corresponding locale. I cannot hardcode the format because the locale really depends on the browser. I tried using Moment.js but I cannot seem to make it work. It returns invalid date for dates like "16/05/2019". It looks like it's not following the locale which I set to en-NZ.

Here is the momentjs code that I have tried:

```<code>moment().locale('en-NZ').format('L')
</code>```

This will return the en-NZ format of the current date which is 27/05/2019 but when I try to include a date string:

```<code>moment('16/05/2019').locale('en-NZ').format('L')
</code>```

This returns 'Invalid Date'. Any suggestions on how to do it or even a different plugin that I can use? Thanks.

答:
Unfortunately, the current user's locale is not well provided by a JavaScript-accessible API at present. This answer goes into some of it, but even here in 2019, Chrome doesn't support any of the properties listed there other than navigator.language, which isn't reliable (mine comes back as en-US, but I'm in the UK so it should be en-GB [everything on my system formats my dates in UK format]).

The only way I've found to get the local date format is to as Intl.DateTimeFormat to format a date and then work it out from the result:

const format = new Intl.DateTimeFormat()
  .format(new Date(2019, 11, 25)) // Christmas 2019
  .replace("2019", "YYYY")
  .replace("12", "MM")
  .replace("25", "DD");
console.log(format);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script></code>```

On my system, that returns DD/MM/YYYY because I'm in the UK which, like NZ, uses a rational format. (I'm part American, so I can kid Americans about their weird date format.) Presumably in the U.S. it would return MM/DD/YYYY.

You can then use that format with moment:

const format = new Intl.DateTimeFormat()
    .format(new Date(2019, 11, 25)) // Christmas 2019
    .replace("2019", "YYYY")
    .replace("12", "MM")
    .replace("25", "DD");

document.getElementById("btn").addEventListener("click", function() {
    const str = document.getElementById("date").value.trim();
    const dt = moment.utc(str, format);
    console.log(`The date in ISO format: ${dt.toISOString()}`);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Enter a date in your local format and click Parse It:
<input type="text" id="date" autofocus>
<input type="button" id="btn" value="Parse It">

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script></code>```

You might want to offer your users a box to select their locale, in which case you'd want moment-with-locales.min.js instead of moment.min.js above.

Title: Identify Locale Date string correctly

Body:
I have a date string that is formatted depending on the language/locale of the browser. For example, "03/05/2019" in en-US is March 5, 2019 (mm/dd/yyyy) but in en-NZ, it's May 3, 2019 (dd/mm/yyyy).

I need to know how to convert the string to date using JavaScript with the corresponding locale. I cannot hardcode the format because the locale really depends on the browser. I tried using Moment.js but I cannot seem to make it work. It returns invalid date for dates like "16/05/2019". It looks like it's not following the locale which I set to en-NZ.

Here is the momentjs code that I have tried:

moment().locale('en-NZ').format('L')

This will return the en-NZ format of the current date which is 27/05/2019 but when I try to include a date string:

moment('16/05/2019').locale('en-NZ').format('L')

This returns 'Invalid Date'. Any suggestions on how to do it or even a different plugin that I can use? Thanks.

Body:
Unfortunately, the current user's locale is not well provided by a JavaScript-accessible API at present. This answer goes into some of it, but even here in 2019, Chrome doesn't support any of the properties listed there other than navigator.language, which isn't reliable (mine comes back as en-US, but I'm in the UK so it should be en-GB [everything on my system formats my dates in UK format]).

The only way I've found to get the local date format is to as Intl.DateTimeFormat to format a date and then work it out from the result:

const format = new Intl.DateTimeFormat()
  .format(new Date(2019, 11, 25)) // Christmas 2019
  .replace("2019", "YYYY")
  .replace("12", "MM")
  .replace("25", "DD");
console.log(format);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

On my system, that returns DD/MM/YYYY because I'm in the UK which, like NZ, uses a rational format. (I'm part American, so I can kid Americans about their weird date format.) Presumably in the U.S. it would return MM/DD/YYYY.

You can then use that format with moment:

const format = new Intl.DateTimeFormat()
    .format(new Date(2019, 11, 25)) // Christmas 2019
    .replace("2019", "YYYY")
    .replace("12", "MM")
    .replace("25", "DD");

document.getElementById("btn").addEventListener("click", function() {
    const str = document.getElementById("date").value.trim();
    const dt = moment.utc(str, format);
    console.log(`The date in ISO format: ${dt.toISOString()}`);
});

Enter a date in your local format and click Parse It:
<input type="text" id="date" autofocus>
<input type="button" id="btn" value="Parse It">

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

You might want to offer your users a box to select their locale, in which case you'd want moment-with-locales.min.js instead of moment.min.js above.


问:
KeyCloak restricting user management to certain groups while enabling 'manage-users'
Using the KeyCloak admin console, I am attempting to enact the following use-case.

We have Group X and Group Y.

The role 'Group X Admin' can do the following:

Can create users without a group.

Can assign users without a group to group X.

Can edit and manage users in group X.

Cannot see/edit/manage users in group Y.

It seems that in order to fulfill case 1, I must make 'Group X Admin' a composite role linked to the 'manage-users' role from the realm-management client.
However, upon doing this, the 'Group X Admin' now has permission to view/manage/edit group Y users.

It seems I cannot restrict access to group Y as fine-grained permissions seem to completely overridden by the manage-users role.

Is there a way to grant permissions to Add Users while restricting access to certain groups?

答:
You should have a look at Fine Grain Admin Permissions. It's still in preview (so no support from RedHat) but it's the kind of functionality you are looking for.

I certainly have tested a setup that would fulfill items 3 and 4. The description in chapter 11.3.2 Restrict User Role Mapping should get you sufficiently close to item 2. Item 1 probably needs somewhat more investigation. I can't tell you if it's doable.

Even though Fine Grain Admin Permission is quite powerful, we came to the conclusion that it's not sufficient for our requirements. So we discarded it and went with a different solution (a privileged service in front of Keycloak for delegated user administration).

Update

Some instructions how to set it up:

Enable preview profile (in Keycloak startup script)

Enable permissions on client Realm-management (Clients / Realm-Management / Permissions / Permissions Enabled)

Create a group x-users

Create a group x-admins

Enable permissions on group x-users (Groups / X / Permissions / Permissions Enabled)

Click view-members (on the same page) and add a group policy:

Scopes: view-members

Apply Policy: Create Policy... / Group

Enter name, e.g. x-admin-policy

Enter description

Groups: select group x-admins

Save

Repeat for manage-members


答:
I think you need to take a look at Ajax.

In Javascript Code:

```<code>function myJsCallback(myJsVar) {
  $.get("http://example.com/api/fb/checkfb?myJsVar=" + myJsVar,
  function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
}
</code>```

In PHP

```<code>public function myRouteHandler() {
    $myJsVar = $_GET['myJsVar'];
    // check whatever here
}
</code>```

Title: how can i pass value from javascript to my php function codeigniter

Body:
I think you need to take a look at Ajax.

In Javascript Code:

function myJsCallback(myJsVar) {
  $.get("http://example.com/api/fb/checkfb?myJsVar=" + myJsVar,
  function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
}

In PHP

public function myRouteHandler() {
    $myJsVar = $_GET['myJsVar'];
    // check whatever here
}


问:
Which is the best way to yield thread?
Program language: C++ 11

I use pipeline threads mode to deal data.

One thread generate data.

One thread process data.

While no data to deal, which is the best way to yield thread?

Now I use

```<code>std::this_thread::sleep_for(100ms);
</code>```

I wonder if there is a better way to yield?

If sleep is well enough, how long time to sleep is better?

答:
Introduce a wait condition on which your consumer thread needs to wait.
Once the data is generated by producer it can notify your consumer thread, till then consumer waits.</p>

Title: Which is the best way to yield thread?

Body:
Program language: C++ 11

I use pipeline threads mode to deal data.

One thread generate data.

One thread process data.

While no data to deal, which is the best way to yield thread?

Now I use

std::this_thread::sleep_for(100ms);

I wonder if there is a better way to yield?

If sleep is well enough, how long time to sleep is better?


问:
Looking up encrypted keys in a key value store
I have a requirement to encrypt the keys in a redis cache. Redis is a key - value store.
I can encrypt the keys  using a standard encryption algorithm while inserting into the cache fine. But how do I do a lookup afterwards?

So say, I want to lookup a key "234" .i encrypt "234" using the same algorithm but the encrypted value will be different every time. So it won't match the encrypted value that's in the cache.

How do I solve this problem?

答:
Don't confuse Encryption keys with the key used to look up in your "Key / value store". Encryption keys are used for encrypting stuff, whereas the "Key" in your "Key / value store" is just a name to index your values by.

In your case you Encryption key would be encrypted and then goes into the Value part. Your index would still work, as this is not encrypted.


问:
MRPT SLAM MRPT::slam::CMetricMapBuilderICP warning Pose Extrapolation failed
I am using MRPT library's Map Builder ICP to implement a 2D slam on C++ by using Sick LMS151 to get CObservation2DRangeScan.
Whenever I am providing the 2D range scan to the map builder, it generates a warning that the Pose Extrapolation has failed. How do I know where the fault is in my codes?

```<code>mrpt::slam::CMetricMapBuilderICP mapBuilder;

double RANGE_MAX = 20.0;
double RANGE_MIN = 0.05;

py::list processObservation(double timestamp, py::list scanRanges, py::tuple pose) {
    /* Takes observation and pose and returns the pose that is predicted by SLAM */
    mrpt::obs::CObservation2DRangeScan *rangescan = new mrpt::obs::CObservation2DRangeScan();
    //Set Intensities to false, as our lidar does not send it
    rangescan->setScanHasIntensity(false);
    //Set Tolerance of Scan to +- 0.8radians in pitch and roll
    rangescan->isPlanarScan(0.08);
    rangescan->timestamp = mrpt::system::time_tToTimestamp(timestamp);
    rangescan->aperture = M_PI*1.5;
    rangescan->maxRange = RANGE_MAX;
    mrpt::poses::CPose3D Pose;
    //Sensor Pose for Observation
    Pose.setFromValues(pose[0].cast<double>()+base_to_lidar,pose[1].cast<double>(),0,0,0,pose[2].cast<double>());
    rangescan->setSensorPose(Pose);

    std::vector <float>scanranges;
    std::vector <char>valid(scanranges.size());

    for(auto i: scanRanges) {
        float range = i.cast<float>();
        valid.push_back(range<=RANGE_MAX && range>=RANGE_MIN);
        scanranges.push_back(range);
    }

    rangescan->loadFromVectors(scanranges.size(), &scanranges[0], &valid[0]);

    mrpt::obs::CObservation2DRangeScan::Ptr obs_ptr(rangescan);

    try {
        mapBuilder.processObservation(obs_ptr);
    }
    catch(...) {
        std::cerr<<"Cannot Process Observation. The old pose will be returned\n";
    }

    mrpt::poses::CPose3DPDF::Ptr predicted_pose = mapBuilder.getCurrentPoseEstimation();

    mrpt::math::CMatrixDouble cov;
    mrpt::poses::CPose3D mean;
    predicted_pose->getCovarianceDynAndMean(cov, mean);

    std::vector <double> pos_vector;
    pos_vector.push_back(mean.x());
    pos_vector.push_back(mean.y());
    pos_vector.push_back(mean.yaw());
    pos_vector.insert(pos_vector.end(), cov.begin(), cov.end());
    py::list list_pose = py::cast(pos_vector);
    return list_pose;
}

</code>```

The expected output was to be the 2D pose as predicted by the ICP-slam algorithm, which is not the case.

However, the output is as follows:

```<code>[10:36:40.1430|WARN |CMetricMapBuilderICP] processObservation(): new pose extrapolation failed, using last pose as is.
Cannot Process Observation. The old pose will be returned
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
</code>```

[x, y, yaw, covariances]

答:
As long as this does not happen all the time, it is just a warning, not an error, so you should not worry too much. </p>

<p>It means that the initial pose used by ICP will be the last pose, without an additional refining step that consists in extrapolating (guessing) the robot pose at the timestamp of the LiDAR, using its velocity vector. </p>

Body:
I am using MRPT library's Map Builder ICP to implement a 2D slam on C++ by using Sick LMS151 to get CObservation2DRangeScan.
Whenever I am providing the 2D range scan to the map builder, it generates a warning that the Pose Extrapolation has failed. How do I know where the fault is in my codes?

mrpt::slam::CMetricMapBuilderICP mapBuilder;

double RANGE_MAX = 20.0;
double RANGE_MIN = 0.05;

py::list processObservation(double timestamp, py::list scanRanges, py::tuple pose) {
    /* Takes observation and pose and returns the pose that is predicted by SLAM */
    mrpt::obs::CObservation2DRangeScan *rangescan = new mrpt::obs::CObservation2DRangeScan();
    //Set Intensities to false, as our lidar does not send it
    rangescan->setScanHasIntensity(false);
    //Set Tolerance of Scan to +- 0.8radians in pitch and roll
    rangescan->isPlanarScan(0.08);
    rangescan->timestamp = mrpt::system::time_tToTimestamp(timestamp);
    rangescan->aperture = M_PI*1.5;
    rangescan->maxRange = RANGE_MAX;
    mrpt::poses::CPose3D Pose;
    //Sensor Pose for Observation
    Pose.setFromValues(pose[0].cast<double>()+base_to_lidar,pose[1].cast<double>(),0,0,0,pose[2].cast<double>());
    rangescan->setSensorPose(Pose);

    std::vector <float>scanranges;
    std::vector <char>valid(scanranges.size());

    for(auto i: scanRanges) {
        float range = i.cast<float>();
        valid.push_back(range<=RANGE_MAX && range>=RANGE_MIN);
        scanranges.push_back(range);
    }

    rangescan->loadFromVectors(scanranges.size(), &scanranges[0], &valid[0]);

    mrpt::obs::CObservation2DRangeScan::Ptr obs_ptr(rangescan);

    try {
        mapBuilder.processObservation(obs_ptr);
    }
    catch(...) {
        std::cerr<<"Cannot Process Observation. The old pose will be returned\n";
    }

    mrpt::poses::CPose3DPDF::Ptr predicted_pose = mapBuilder.getCurrentPoseEstimation();

    mrpt::math::CMatrixDouble cov;
    mrpt::poses::CPose3D mean;
    predicted_pose->getCovarianceDynAndMean(cov, mean);

    std::vector <double> pos_vector;
    pos_vector.push_back(mean.x());
    pos_vector.push_back(mean.y());
    pos_vector.push_back(mean.yaw());
    pos_vector.insert(pos_vector.end(), cov.begin(), cov.end());
    py::list list_pose = py::cast(pos_vector);
    return list_pose;
}

The expected output was to be the 2D pose as predicted by the ICP-slam algorithm, which is not the case.

However, the output is as follows:

[10:36:40.1430|WARN |CMetricMapBuilderICP] processObservation(): new pose extrapolation failed, using last pose as is.
Cannot Process Observation. The old pose will be returned
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

[x, y, yaw, covariances]

Body:
As long as this does not happen all the time, it is just a warning, not an error, so you should not worry too much.

It means that the initial pose used by ICP will be the last pose, without an additional refining step that consists in extrapolating (guessing) the robot pose at the timestamp of the LiDAR, using its velocity vector.


问:
PHP: are switch-case statements with strings inefficient?
In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps a dozen. </p>

<p>What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter? </p>

答:
Strings can't be recognised as class constants. But the answer on your question is that it doesnt really matter if you do it like this:</p>

```<code>switch (className::{$errorCode}) { // $errorCode == name of the constant, like NOT_FOUND
// Cases here.
}
</code>```

Body:
In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps a dozen.

What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter?

Body:
Strings can't be recognised as class constants. But the answer on your question is that it doesnt really matter if you do it like this:

switch (className::{$errorCode}) { // $errorCode == name of the constant, like NOT_FOUND
// Cases here.
}


答:
So you want to:

Convert the main_tbl_name.column_two to rows

For each of these generated rows, link to one of the existing table rows
?

If so, you can do something like below:

WITH DATA AS
     ( SELECT 44 AS COLUMN_ONE  ,'WORD1 WORD2 WORD3  WORD4 WORD5 WORD6' COLUMN_TWO FROM DUAL     )
SELECT COLUMN_ONE  ,TRIM(REGEXP_SUBSTR(COLUMN_TWO,  '[^ ]+', 1, LEVEL)) COLUMN_TWO
FROM DATA
CONNECT BY INSTR(COLUMN_TWO, ' ', 1, LEVEL - 1) > 0;

COLUMN_ONE  COLUMN_TWO
44          WORD1
44          WORD2
44          WORD3
44          WORD4
44          WORD5
44          WORD6
```

Cheers!!!
Dhilen

Title: How to use select query inside the select column name by iterating column row values using oracle?

Body:
Query:

select column_one, column_two, column_three
from main_tbl_name

Output:

column_one  column_two
--------------------------------------------------------------------------------
data1       SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE
data2       SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA
data3       DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS

I have another query:

select column_one, column_two, column_three
from another_tbl_name
where column_four in (main_tbl_name.column_two)

I need to split up the values of main_tbl_name.column_two into for example like ('SBANAR','SBARTO','SCBADP','SCCHBA','SCHPIT','SCTHAB','SDPCLV','SDPRPN','SDPSEC','SERIE')

In the above second query if some of the values exist, append each iterated value in main_tbl_name.column_three

So my final output should be

column_one  column_two                                                                  column_three
-------------------------------------------------------------------------------------------------------------------------
data1       SBANAR SBARTO SCBADP SCCHBA SCHPIT SCTHAB SDPCLV SDPRPN SDPSEC SERIE        SBANAR SBARTO SCCHBA SDPCLV SDPSEC
data2       SRALEN SRETIN SRUNLI SSAPEL SSATAR SSCMAR SSDECA                            SRALEN SSCMAR SSDECA
data3       DRAP14 E05A E1 ECOMOD ENJO01 ENPC01 ESPHSA ESS                              DRAP14 E05A ESPHSA ESS

Body:
So you want to:

Convert the main_tbl_name.column_two to rows

For each of these generated rows, link to one of the existing table rows
?

If so, you can do something like below:

WITH DATA AS
     ( SELECT 44 AS COLUMN_ONE  ,'WORD1 WORD2 WORD3 <!-- language: lang-sql --> WORD4 WORD5 WORD6' COLUMN_TWO FROM DUAL     )
SELECT COLUMN_ONE  ,TRIM(REGEXP_SUBSTR(COLUMN_TWO, <!-- language: lang-sql --> '[^ ]+', 1, LEVEL)) COLUMN_TWO
FROM DATA
CONNECT BY INSTR(COLUMN_TWO, ' ', 1, LEVEL - 1) > 0;

COLUMN_ONE  COLUMN_TWO
44          WORD1
44          WORD2
44          WORD3
44          WORD4
44          WORD5
44          WORD6

Cheers!!!
Dhilen


答:
Which is the best way to yield thread?

It is std::this_thread::yield.

Now I use

```<code>std::this_thread::sleep_for(100ms);
</code>```

While sleeping does yield the thread as a side-effect, that's not all that it does. As the name implies, it blocks the thread for a given time.

However, it is unclear how yielding or sleeping would be useful in a producer / consumer case such as what you describe. What you probably should do is wait on a condition variable instead.

Title: Which is the best way to yield thread?

Body:
Which is the best way to yield thread?

It is std::this_thread::yield.

Now I use

std::this_thread::sleep_for(100ms);

While sleeping does yield the thread as a side-effect, that's not all that it does. As the name implies, it blocks the thread for a given time.

However, it is unclear how yielding or sleeping would be useful in a producer / consumer case such as what you describe. What you probably should do is wait on a condition variable instead.


问:
Response from geocoding API
I'm able to get the fully formatted address from the api,

"1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"

for example.

How do i "breaking to pieces" this formatted address(city, street, country etc)?

code for getting the fully address -

```<code>   final formattedAddress =decodedResponse['results'][0]['formatted_address']
</code>```

答:
According to the result from the api(https://developers.google.com/maps/documentation/geocoding/intro#GeocodingResponses)

I can write decodedResponse['results'][0]['address_components'][0]['long_name']

The second [0] indicate the location of the type

Title: Response from geocoding API

Body:
I'm able to get the fully formatted address from the api,

"1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"

for example.

How do i "breaking to pieces" this formatted address(city, street, country etc)?

code for getting the fully address -

   final formattedAddress =decodedResponse['results'][0]['formatted_address']


问:
regex for allowing SINGLE white space in between words
I m using the following regex for the same:
^\S.*\S$

but this regex is not working in case of multiple spaces in between words.
and one more thing, it doesnt allow you to enter a single character

I want to validate no leading and trailing space and single white space in between words, words can include anything alphanumeric as well as special character.

if i m trying to enter 'a' in the text box, its not accepting

答:
In case only charactors are needed, use this:</p>

```<code>^[a-z|A-Z]+(?: [a-z|A-Z]+)*$
</code>```

Body:
In case only charactors are needed, use this:

^[a-z|A-Z]+(?: [a-z|A-Z]+)*$


问:
Problem using if and Else to render text in R shiny
I am trying to set up a shiny app which allows individuals to select an option and then with that option a specific text appears if they select the other option different text appears.

Currently i am getting an error, i have tried to use the if else, I am new to shiny and fairly new to R so am struggling with the code.

I have tried playing about with using a reactive x but couldn't get it to work either potentially because this is not numeric?

```<code># Sidebar with a select input for number of bins
sidebarLayout(
    sidebarPanel(
        selectInput(inputId = "Options",
                    label = "Option",
                    choices = c("Option 1","Option 2"))
    ),

    # Show a text output
    mainPanel(
        textOutput(outputId = "ParticpantInformation1"),
        textOutput(outputId = "ParticpantInformation2")

    )),

# Define server logic required to rendertext
server <- function(input, output) {

    if (input$Options=="Option 1") output$ParticpantInformation1 <- renderText("Option 1")
    else output$ParticpantInformation2 <-renderText("Option 2")
</code>```

I am hoping for it to render either one set of text or the other onto the main panel of the app

Currently i get an Error - "cannot coerce type 'closure' to vector of type 'character' "

答:
You don't need that if(). You can directly refer to the user selection like this:

```<code>library(shiny)

ui <- fluidPage(
  # Sidebar with a select input for number of bins
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "Options",
                  label = "Option",
                  choices = list("Option 1" = "My option 1 text", "Option 2" = "My option 2 text"))
    ),

    # Show a text output
    mainPanel(
      textOutput(outputId = "ParticpantInformation")
    ))
)

server <- function(input, output, session) {
  output$ParticpantInformation <- renderText({input$Options})
}

shinyApp(ui = ui, server = server)
</code>```

For an alternative please see ?conditionalPanel, but for this case it's unnecessary complex.

Body:
I am trying to set up a shiny app which allows individuals to select an option and then with that option a specific text appears if they select the other option different text appears.

Currently i am getting an error, i have tried to use the if else, I am new to shiny and fairly new to R so am struggling with the code.

I have tried playing about with using a reactive x but couldn't get it to work either potentially because this is not numeric?

# Sidebar with a select input for number of bins
sidebarLayout(
    sidebarPanel(
        selectInput(inputId = "Options",
                    label = "Option",
                    choices = c("Option 1","Option 2"))
    ),

    # Show a text output
    mainPanel(
        textOutput(outputId = "ParticpantInformation1"),
        textOutput(outputId = "ParticpantInformation2")

    )),

# Define server logic required to rendertext
server <- function(input, output) {

    if (input$Options=="Option 1") output$ParticpantInformation1 <- renderText("Option 1")
    else output$ParticpantInformation2 <-renderText("Option 2")

I am hoping for it to render either one set of text or the other onto the main panel of the app

Currently i get an Error - "cannot coerce type 'closure' to vector of type 'character' "

Body:
You don't need that if(). You can directly refer to the user selection like this:

library(shiny)

ui <- fluidPage(
  # Sidebar with a select input for number of bins
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "Options",
                  label = "Option",
                  choices = list("Option 1" = "My option 1 text", "Option 2" = "My option 2 text"))
    ),

    # Show a text output
    mainPanel(
      textOutput(outputId = "ParticpantInformation")
    ))
)

server <- function(input, output, session) {
  output$ParticpantInformation <- renderText({input$Options})
}

shinyApp(ui = ui, server = server)

For an alternative please see ?conditionalPanel, but for this case it's unnecessary complex.


问:
Can't get Resource from POST/PUT request (.NET FHIR client, web api 2)
When I try to send a POST / PUT request using .NET FHIR API to asp.net Web API 2 server, I get the error message:

Hl7.Fhir.Rest.FhirOperationException: the operation failed due to a

  client error (UnsupportedMediaType). The body has no content.

1) Do I need to create some kind of MediaType Handler / Formatter?

2) Is there an open source server in which code implements the best practices of the .NET FHIR API?

I looked at Fiddler, seems fhir client sends correct JSON in the body

```<code>fhirClient = new FhirClient(serverUrl);
fhirClient.PreferredFormat = ResourceFormat.Json;

Patient patient = new Patient();
//fill patient

    var response = fhirClient.Update(patient);
</code>```

...

// web api 2 server:
WebApiConfig.cs:

```<code>config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/fhir+json"));
</code>```

I tried:

```<code>[HttpPut]
public void Update([FromBody] Resource resource, string id = null)
{
// updating logic
}

//or
[HttpPut]
public void Update(Resource resource, string id = null)
{
// updating logic
}
</code>```

but, when I tried

```<code>[HttpPut]
public void Update([FromBody] object resource, string id = null)
{
</code>```

I can see inside "object" a deserialized Patient and use jsonParser to get it back

答: Indeed, see also here: HL7 FHIR serialisation to json in asp.net web api - that answer is based on the code you found above.</p>

Body:
When I try to send a POST / PUT request using .NET FHIR API to asp.net Web API 2 server, I get the error message:

Hl7.Fhir.Rest.FhirOperationException: the operation failed due to a

  client error (UnsupportedMediaType). The body has no content.

1) Do I need to create some kind of MediaType Handler / Formatter?

2) Is there an open source server in which code implements the best practices of the .NET FHIR API?

I looked at Fiddler, seems fhir client sends correct JSON in the body

fhirClient = new FhirClient(serverUrl);
fhirClient.PreferredFormat = ResourceFormat.Json;

Patient patient = new Patient();
//fill patient

    var response = fhirClient.Update(patient);

...

// web api 2 server:
WebApiConfig.cs:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/fhir+json"));

I tried:

[HttpPut]
public void Update([FromBody] Resource resource, string id = null)
{
// updating logic
}

//or
[HttpPut]
public void Update(Resource resource, string id = null)
{
// updating logic
}

but, when I tried

[HttpPut]
public void Update([FromBody] object resource, string id = null)
{

I can see inside "object" a deserialized Patient and use jsonParser to get it back