问:
Prefill Google Sheet sidebar with Apps Script Properties Service values
I have written a code to show the form in a sidebar in google sheets and store the entered values such as full name, email address, mobile no. etc, in Apps Script Properties but the only issue I am facing is when I close the form and reopen it, the form does not show the last stored values as well as confirmation message on submit.

I want the form to show the last stored value from the Apps Script Properties and confirmation message on submit.

Please help.

Code.gs

```<code>function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Sidebar')
    .addItem('Show sidebar', 'showSidebar')
    .addToUi();
}

function showSidebar() {
  var userName = Session.getActiveUser().getEmail();
  var scriptProperties = PropertiesService.getScriptProperties();
  const html = HtmlService.createTemplateFromFile('index');
  html.data = {
    'fullName': scriptProperties.getProperty('fullName'),
    'emailAddress': scriptProperties.getProperty('emailAddress'),
    'mobileNumber': scriptProperties.getProperty('mobileNumber'),
    'city': scriptProperties.getProperty('city'),
    'weekday': scriptProperties.getProperty('weekday'),
    'triggerTime': scriptProperties.getProperty('triggerTime')
  };

  var popFullName = scriptProperties.getProperty('fullName');
  console.log({ html })
  var evaluatHTML = html.evaluate().setTitle('Sidebar')
  SpreadsheetApp.getUi().showSidebar(evaluatHTML)
};

function setfullName(fullName) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('fullName', fullName);
};

function setEmailAddress(emailAddress) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('emailAddress', emailAddress);
};

function setMobileNumber(mobileNumber) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('mobileNumber', mobileNumber);
};

function setCity(city) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('city', city);
};

function setday(day) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('weekday', day);
};

function setselectTime(selectTime) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('triggerTime', selectTime);
};

function testProp() {
  var popFullName = PropertiesService.getScriptProperties().getProperty('fullName');
  var popEmailAddress = PropertiesService.getScriptProperties().getProperty('emailAddress');
  var popMobileNumber = PropertiesService.getScriptProperties().getProperty('mobileNumber');
  var popcity = PropertiesService.getScriptProperties().getProperty('city');
  var popsetday = PropertiesService.getScriptProperties().getProperty('weekday');
  var popsettriggertime = PropertiesService.getScriptProperties().getProperty('triggerTime');
  console.log({ popFullName })
  console.log({ popEmailAddress })
  console.log({ popMobileNumber })
  console.log({ popcity })
  console.log({ popsetday })
  console.log({ popsettriggertime })
};
</code>```

index.html

```<code><!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
  <style>
    .form-row {
      margin-bottom: 15px;
    }
  </style>
</head>

<body>
  <div class="content-body">

    <div class="row">
      <div class="input-field col s12">
        <input id="fullName" type="text" class="validate">
        <label class="active" for="fullName">Full Name</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <input id="emailAddress" type="text" class="validate">
        <label for="emailAddress">Email Address</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <input id="mobileNumber" type="number" class="validate">
        <label for="mobileNumber">Mobile Number</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <input id="city" type="text" class="validate">
        <label for="city">City</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <select id="day">
<option value="">Choose</option>
<option value="MONDAY">MONDAY</option>
<option value="TUESDAY">TUESDAY</option>
<option value="WEDNESDAY">WEDNESDAY</option>
<option value="THURSDAY">THURSDAY</option>
<option value="FRIDAY">FRIDAY</option>
<option value="SATURDAY">SATURDAY</option>
<option value="SUNDAY">SUNDAY</option>
</select>
        <label>Select Day</label>
      </div>
    </div>

    <div class="row">
      <div class="input-field col s12">
        <select id="selectTime">
<option value="">Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
        <label>Select Time</label>
      </div>
    </div>

    <div class="row">
      <button id="btn" class="btn waves-effect waves-light" onclick="setValueToProperties()" type="submit" name="action">Submit</button>
    </div>

    <div class="row">
      <button class="btn waves-effect waves-light" onClick="google.script.host.close()">Close</button>
    </div>

  </div>

  <script>
    function setValueToProperties() {
    const fullName = document.getElementById('fullName').value;
    google.script.run.setfullName(fullName);

    const emailAddress = document.getElementById('emailAddress').value;
    google.script.run.setEmailAddress(emailAddress);

    const mobileNumber = document.getElementById('mobileNumber').value;
    google.script.run.setMobileNumber(mobileNumber);

    const city = document.getElementById('city').value;
    google.script.run.setCity(city);

    const day = document.getElementById('day').value;
    google.script.run.setday(day);

    const selectTime = document.getElementById('selectTime').value;
    google.script.run.setselectTime(selectTime);

  }
  </script>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
    });
  </script>

  <script>
    var data = <?!=JSON.stringify(data);?>
  </script>

  <script>
    $(document).ready(function(){
             const keys = ["fullName", "emailAddress", "mobileNumber", "city", "day", "selectTime"];
             $.each(keys, function(key){
                 let val = data[keys[key]] ;
                 $("#"+keys[key]).val(val);
             });
  </script>

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

</body>

</html>
</code>```

答:
It is also possible to prefill the form without jQuery as folllows

in gs

```<code>function showSidebar() {
  var userName = Session.getActiveUser().getEmail();
  const html = HtmlService.createTemplateFromFile('index');
  var evaluatHTML = html.evaluate().setTitle('Sidebar')
  SpreadsheetApp.getUi().showSidebar(evaluatHTML)
};

function myProperties(){
  var scriptProperties = PropertiesService.getScriptProperties();
  data = {
    'fullName': scriptProperties.getProperty('fullName'),
    'emailAddress': scriptProperties.getProperty('emailAddress'),
    'mobileNumber': scriptProperties.getProperty('mobileNumber'),
    'city': scriptProperties.getProperty('city'),
    'day': scriptProperties.getProperty('weekday'),
    'selectTime': scriptProperties.getProperty('triggerTime')
  };
  Logger.log(JSON.stringify(data))
  return JSON.stringify(data)
}
</code>```

the complete html could be

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" />

    <style>
      .form-row {
        margin-bottom: 15px;
      }
    </style>
  </head>

  <body>
    <script>
      <?
        var data = JSON.parse(myProperties());
        var days = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY']
      ?>
    </script>
    <div class="content-body">
      <div class="row">
        <div class="input-field col s12">
          <input id="fullName" type="text" class="validate" value="<?= data.fullName ?>" />
          <label class="active" for="fullName">Full Name</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <input id="emailAddress" type="text" class="validate" value="<?= data.emailAddress ?>" />
          <label for="emailAddress">Email Address</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <input id="mobileNumber" type="number" class="validate" value="<?= data.mobileNumber ?>" />
          <label for="mobileNumber">Mobile Number</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <input id="city" type="text" class="validate"  value="<?= data.city ?>" />
          <label for="city">City</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <select id="day">
            <option value="" disabled selected >Choose ...</option>
              <? for (var i = 0; i < days.length; i++) { ?>
                <option value="<?=days[i]?>" <?= ((days[i]==data.day && data.day!='')?'selected':'') ?> ><?=days[i]?></option>
              <? } ?>
          </select>
          <label>Select Day</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <select id="selectTime">
            <option value="" disabled selected >Choose ...</option>
              <? for (var i = 0; i < 24; i++) { ?>
                <option value="<?=i?>" <?= ((i.toString()==data.selectTime && data.selectTime!='')?'selected':'') ?> ><?=i?></option>
              <? } ?>
          </select>
          <label>Select Time</label>
        </div>
      </div>

      <div class="row">
        <button id="btn" class="btn waves-effect waves-light" onclick="setValueToProperties()" type="submit" name="action">Submit</button>
      </div>

      <div class="row">
        <button class="btn waves-effect waves-light" onClick="google.script.host.close()">Close</button>
      </div>
    </div>

    <input id="test1" type="text" class="validate" />

    <script>
      function setValueToProperties() {
        const fullName = document.getElementById("fullName").value;
        google.script.run.setfullName(fullName);

        const emailAddress = document.getElementById("emailAddress").value;
        google.script.run.setEmailAddress(emailAddress);

        const mobileNumber = document.getElementById("mobileNumber").value;
        google.script.run.setMobileNumber(mobileNumber);

        const city = document.getElementById("city").value;
        google.script.run.setCity(city);

        const day = document.getElementById("day").value;
        google.script.run.setday(day);

        const selectTime = document.getElementById("selectTime").value;
        google.script.run.setselectTime(selectTime);
      }
    </script>

    <script>
      document.addEventListener("DOMContentLoaded", function () {
        var elems = document.querySelectorAll("select");
        var instances = M.FormSelect.init(elems);
      });
    </script>

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

  </body>
</html>
</code>```

Body:
I have written a code to show the form in a sidebar in google sheets and store the entered values such as full name, email address, mobile no. etc, in Apps Script Properties but the only issue I am facing is when I close the form and reopen it, the form does not show the last stored values as well as confirmation message on submit.

I want the form to show the last stored value from the Apps Script Properties and confirmation message on submit.

Please help.

Code.gs

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Sidebar')
    .addItem('Show sidebar', 'showSidebar')
    .addToUi();
}

function showSidebar() {
  var userName = Session.getActiveUser().getEmail();
  var scriptProperties = PropertiesService.getScriptProperties();
  const html = HtmlService.createTemplateFromFile('index');
  html.data = {
    'fullName': scriptProperties.getProperty('fullName'),
    'emailAddress': scriptProperties.getProperty('emailAddress'),
    'mobileNumber': scriptProperties.getProperty('mobileNumber'),
    'city': scriptProperties.getProperty('city'),
    'weekday': scriptProperties.getProperty('weekday'),
    'triggerTime': scriptProperties.getProperty('triggerTime')
  };

  var popFullName = scriptProperties.getProperty('fullName');
  console.log({ html })
  var evaluatHTML = html.evaluate().setTitle('Sidebar')
  SpreadsheetApp.getUi().showSidebar(evaluatHTML)
};

function setfullName(fullName) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('fullName', fullName);
};

function setEmailAddress(emailAddress) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('emailAddress', emailAddress);
};

function setMobileNumber(mobileNumber) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('mobileNumber', mobileNumber);
};

function setCity(city) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('city', city);
};

function setday(day) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('weekday', day);
};

function setselectTime(selectTime) {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('triggerTime', selectTime);
};

function testProp() {
  var popFullName = PropertiesService.getScriptProperties().getProperty('fullName');
  var popEmailAddress = PropertiesService.getScriptProperties().getProperty('emailAddress');
  var popMobileNumber = PropertiesService.getScriptProperties().getProperty('mobileNumber');
  var popcity = PropertiesService.getScriptProperties().getProperty('city');
  var popsetday = PropertiesService.getScriptProperties().getProperty('weekday');
  var popsettriggertime = PropertiesService.getScriptProperties().getProperty('triggerTime');
  console.log({ popFullName })
  console.log({ popEmailAddress })
  console.log({ popMobileNumber })
  console.log({ popcity })
  console.log({ popsetday })
  console.log({ popsettriggertime })
};

index.html

<!DOCTYPE html>

  <base target="_top">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

        <input id="fullName" type="text" class="validate">
        Full Name

        <input id="emailAddress" type="text" class="validate">
        Email Address

        <input id="mobileNumber" type="number" class="validate">
        Mobile Number

        <input id="city" type="text" class="validate">
        City

        <select id="day">
<option value="">Choose</option>
<option value="MONDAY">MONDAY</option>
<option value="TUESDAY">TUESDAY</option>
<option value="WEDNESDAY">WEDNESDAY</option>
<option value="THURSDAY">THURSDAY</option>
<option value="FRIDAY">FRIDAY</option>
<option value="SATURDAY">SATURDAY</option>
<option value="SUNDAY">SUNDAY</option>
</select>
        Select Day

        <select id="selectTime">
<option value="">Choose</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
        Select Time

      <button id="btn" class="btn waves-effect waves-light" onclick="setValueToProperties()" type="submit" name="action">Submit</button>

      <button class="btn waves-effect waves-light" onClick="google.script.host.close()">Close</button>

Body:
It is also possible to prefill the form without jQuery as folllows

in gs

function showSidebar() {
  var userName = Session.getActiveUser().getEmail();
  const html = HtmlService.createTemplateFromFile('index');
  var evaluatHTML = html.evaluate().setTitle('Sidebar')
  SpreadsheetApp.getUi().showSidebar(evaluatHTML)
};

function myProperties(){
  var scriptProperties = PropertiesService.getScriptProperties();
  data = {
    'fullName': scriptProperties.getProperty('fullName'),
    'emailAddress': scriptProperties.getProperty('emailAddress'),
    'mobileNumber': scriptProperties.getProperty('mobileNumber'),
    'city': scriptProperties.getProperty('city'),
    'day': scriptProperties.getProperty('weekday'),
    'selectTime': scriptProperties.getProperty('triggerTime')
  };
  Logger.log(JSON.stringify(data))
  return JSON.stringify(data)
}

the complete html could be

<!DOCTYPE html>
<html>
  <head>
    <base target="_top" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" />

    <style>
      .form-row {
        margin-bottom: 15px;
      }
    </style>
  </head>

  <body>
    <script>
      <?
        var data = JSON.parse(myProperties());
        var days = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY']
      ?>
    </script>
    <div class="content-body">
      <div class="row">
        <div class="input-field col s12">
          <input id="fullName" type="text" class="validate" value="<?= data.fullName ?>" />
          <label class="active" for="fullName">Full Name</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <input id="emailAddress" type="text" class="validate" value="<?= data.emailAddress ?>" />
          <label for="emailAddress">Email Address</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <input id="mobileNumber" type="number" class="validate" value="<?= data.mobileNumber ?>" />
          <label for="mobileNumber">Mobile Number</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <input id="city" type="text" class="validate"  value="<?= data.city ?>" />
          <label for="city">City</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <select id="day">
            <option value="" disabled selected >Choose ...</option>
              <? for (var i = 0; i < days.length; i++) { ?>
                <option value="<?=days[i]?>" <?= ((days[i]==data.day && data.day!='')?'selected':'') ?> ><?=days[i]?></option>
              <? } ?>
          </select>
          <label>Select Day</label>
        </div>
      </div>

      <div class="row">
        <div class="input-field col s12">
          <select id="selectTime">
            <option value="" disabled selected >Choose ...</option>
              <? for (var i = 0; i < 24; i++) { ?>
                <option value="<?=i?>" <?= ((i.toString()==data.selectTime && data.selectTime!='')?'selected':'') ?> ><?=i?></option>
              <? } ?>
          </select>
          <label>Select Time</label>
        </div>
      </div>

      <div class="row">
        <button id="btn" class="btn waves-effect waves-light" onclick="setValueToProperties()" type="submit" name="action">Submit</button>
      </div>

      <div class="row">
        <button class="btn waves-effect waves-light" onClick="google.script.host.close()">Close</button>
      </div>
    </div>

    <input id="test1" type="text" class="validate" />

    <script>
      function setValueToProperties() {
        const fullName = document.getElementById("fullName").value;
        google.script.run.setfullName(fullName);

        const emailAddress = document.getElementById("emailAddress").value;
        google.script.run.setEmailAddress(emailAddress);

        const mobileNumber = document.getElementById("mobileNumber").value;
        google.script.run.setMobileNumber(mobileNumber);

        const city = document.getElementById("city").value;
        google.script.run.setCity(city);

        const day = document.getElementById("day").value;
        google.script.run.setday(day);

        const selectTime = document.getElementById("selectTime").value;
        google.script.run.setselectTime(selectTime);
      }
    </script>

    <script>
      document.addEventListener("DOMContentLoaded", function () {
        var elems = document.querySelectorAll("select");
        var instances = M.FormSelect.init(elems);
      });
    </script>

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

  </body>
</html>


来源: stackexchange

问:
Determine video bitrate Python
I have a video downloaded from Telegram and I need to determine its bitrate.
I have moviepy (pip install moviepy, not the developer version).
Also, I have ffmpeg, but I don't know how to use it in python.
Also, any other library would work for me.</p>

答:
http://timivanov.ru/kak-uznat-bitrate-i-fps-video-ispolzuya-python-i-ffmpeg/
try this:

```<code>def get_bitrate(file):
try:
   probe = ffmpeg.probe(file)
   video_bitrate = next(s for s in probe['streams'] if s['codec_type'] == 'video')
   bitrate = int(int(video_bitrate['bit_rate']) / 1000)
   return bitrate
</code>```

except Exception as er:
return er

ContentLicense: CC BY-SA 4.0

Title: Determine video bitrate Python

Body:
http://timivanov.ru/kak-uznat-bitrate-i-fps-video-ispolzuya-python-i-ffmpeg/
try this:

def get_bitrate(file):
try:
   probe = ffmpeg.probe(file)
   video_bitrate = next(s for s in probe['streams'] if s['codec_type'] == 'video')
   bitrate = int(int(video_bitrate['bit_rate']) / 1000)
   return bitrate

except Exception as er:
return er


问:
Change navigation bar on android with RN with expo?
I started using React Native with Expo and I encountered my first problem. I want to change the color of the navigation bar on Android. Unfortunately, I can't figure out how to do that.

I tried to use https://github.com/thebylito/react-native-navigation-bar-color#readme but it prints out the following error:

TypeError: TypeError: null is not an object (evaluating 'NavigationBarColor.changeNavigationBarColor')

if (Platform.OS == 'android') {
  changeNavigationBarColor('#f00', true);
}
```

答:
So now you can change the color of NavigationBar on the fly.

Expo released a package - expo-navigation-bar

Simply install it

expo install expo-navigation-bar
```
<p>Usage is well explained in the docs here</p>
<p>For changing the navigation bar color simply run,</p>
<pre class="lang-js prettyprint-override"><code>NavigationBar.setBackgroundColorAsync("white");
</code>```

Body:
So now you can change the color of NavigationBar on the fly.

Expo released a package - expo-navigation-bar

Simply install it

expo install expo-navigation-bar

Usage is well explained in the docs here

For changing the navigation bar color simply run,

NavigationBar.setBackgroundColorAsync("white");


问:
Checking time-stamps if they are from today in MySQL
I have a database with several tables. Each of these tables has a column 'created' which contains time-stamps of when that particular row was created in the database.

Now, I want to create a MySQL script that checks once every week if there is data coming into these tables. So, there should be data coming everyday. How do I create a MySQL script that allows me to do this for all the tables in the database?

Note: Remember I want to do this for all the tables in the database with a single script. That's the main thing I want to know.

答:
```<code>select * from table
where created between subdate(current_date, interval 7 day) and current_date;
</code>```

Selecting datetimes up to current_date includes everything up to the start of "today" (ie "the previous midnight").

ContentLicense: CC BY-SA 3.0

Body:
select * from table
where created between subdate(current_date, interval 7 day) and current_date;

Selecting datetimes up to current_date includes everything up to the start of "today" (ie "the previous midnight").


问:
High resolution video file not playing in exoplayer
I need some help, I am developing video player with the help of Exo player and this is working fine but when I am trying to play big resolution file like 4k or 2k so I am getting this error- mediacodec video renderer error index=0 , format = format, please tell me how to fix this error. I have attached a screenshot of the error

My code

```<code> privat[![enter image description here][1]][1]e void playVideo() {
        String path = mVideoFile.get(position).getPath();
        Uri uri = Uri.parse(path);
        player = new SimpleExoPlayer.Builder(this).build();
        DefaultDataSourceFactory defaultDataSourceFactory = new DefaultDataSourceFactory(
                this, Util.getUserAgent(this, "App")
        );
        concatenatingMediaSource = new ConcatenatingMediaSource();
        for (int i = 0; i<mVideoFile.size(); i++){
            new File(String.valueOf(mVideoFile.get(i)));
            MediaSource mediaSource = new ProgressiveMediaSource.Factory(defaultDataSourceFactory)
                    .createMediaSource(Uri.parse(String.valueOf(uri)));
            concatenatingMediaSource.addMediaSource(mediaSource);

            playerView.setPlayer(player);
            playerView.setKeepScreenOn(true);
            player.prepare(concatenatingMediaSource);
          //  player.seekTo(position, C.TIME_UNSET);

            playError();

        }
    }

    private void playError() {
        player.addListener(new Player.Listener() {
            @Override
            public void onPlayerError(ExoPlaybackException error) {

                Toast.makeText(VideoPlayerActivity.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
            }
        });
        player.setPlayWhenReady(true);
    }
</code>```

答:
The video you shared in the comments is encoded with H264 codec using high profile - see the output below from ffprobe:

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'production ID_4297545.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: mp42mp41isomavc1
    creation_time   : 2020-05-02T14:48:25.000000Z
  Duration: 00:00:12.56, start: 0.000000, bitrate: 15077 kb/s
  Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709, progressive), 3840x2160, 15074 kb/s, 25 fps, 25 tbr, 25 tbn (default)
    Metadata:
      creation_time   : 2020-05-02T14:48:25.000000Z
      handler_name    : L-SMASH Video Handler
      vendor_id       : [0][0][0][0]
      encoder         : AVC Coding
```

Android devices by default support Baseline profile - you can see the supported media information here: https://developer.android.com/guide/topics/media/media-formats#video-formats

You may find that some devices do actually support high profile encodings, but it is not guaranteed so it is usually better to re encode your video to baseline profile to ensure the widest device coverage possible.

Body:
I need some help, I am developing video player with the help of Exo player and this is working fine but when I am trying to play big resolution file like 4k or 2k so I am getting this error- mediacodec video renderer error index=0 , format = format, please tell me how to fix this error. I have attached a screenshot of the error

My code

 privat[![enter image description here][1]][1]e void playVideo() {
        String path = mVideoFile.get(position).getPath();
        Uri uri = Uri.parse(path);
        player = new SimpleExoPlayer.Builder(this).build();
        DefaultDataSourceFactory defaultDataSourceFactory = new DefaultDataSourceFactory(
                this, Util.getUserAgent(this, "App")
        );
        concatenatingMediaSource = new ConcatenatingMediaSource();
        for (int i = 0; i<mVideoFile.size(); i++){
            new File(String.valueOf(mVideoFile.get(i)));
            MediaSource mediaSource = new ProgressiveMediaSource.Factory(defaultDataSourceFactory)
                    .createMediaSource(Uri.parse(String.valueOf(uri)));
            concatenatingMediaSource.addMediaSource(mediaSource);

            playerView.setPlayer(player);
            playerView.setKeepScreenOn(true);
            player.prepare(concatenatingMediaSource);
          //  player.seekTo(position, C.TIME_UNSET);

            playError();

        }
    }

    private void playError() {
        player.addListener(new Player.Listener() {
            @Override
            public void onPlayerError(ExoPlaybackException error) {

                Toast.makeText(VideoPlayerActivity.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
            }
        });
        player.setPlayWhenReady(true);
    }

Body:
The video you shared in the comments is encoded with H264 codec using high profile - see the output below from ffprobe:

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'production ID_4297545.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: mp42mp41isomavc1
    creation_time   : 2020-05-02T14:48:25.000000Z
  Duration: 00:00:12.56, start: 0.000000, bitrate: 15077 kb/s
  Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709, progressive), 3840x2160, 15074 kb/s, 25 fps, 25 tbr, 25 tbn (default)
    Metadata:
      creation_time   : 2020-05-02T14:48:25.000000Z
      handler_name    : L-SMASH Video Handler
      vendor_id       : [0][0][0][0]
      encoder         : AVC Coding

Android devices by default support Baseline profile - you can see the supported media information here: https://developer.android.com/guide/topics/media/media-formats#video-formats

You may find that some devices do actually support high profile encodings, but it is not guaranteed so it is usually better to re encode your video to baseline profile to ensure the widest device coverage possible.


问:
How to create an loop that will implement my XML lines the amount of times i want it
Is there any way where I can make an loop of an whatever size and it will loop over the number given and add the XML elements. The first part of the code should remain like this and the down part should be dynamic.</p>
```<code>string name = "haus";
XDocument xmlDocument = new XDocument(
  new XDeclaration("1.0", "utf-8", "yes"),
  new XElement("Document",
    new XElement("DocumentInfo",
      new XElement("Created", "2022-02-09T13:52:07.8908726Z"),
      new XElement("ExportSetting", "WithDefaults"),
      new XElement("InstalledProducts",
        new XElement("Product",
          new XElement("DisplayName", "Totally Integrated Automation Portal"),
          new XElement("DisplayVersion", "V16")
        ),
        new XElement("OptionPackage",
          new XElement("DisplayName", "TIA Portal Version Control Interface"),
          new XElement("ObjectList",
            new XElement("MultilingualText",
              new XAttribute("ID", 1),
              new XAttribute("CompositionName", "Comment"),
              new XElement("ObjectList",
                new XElement("MultilingualTextItem",
                  new XAttribute("ID", 2),
                  new XAttribute("CompositionName", "Items"),
                  new XElement("AttributeList",
                    new XElement("Culture", "de-DE"),
                    new XElement("Text")
                  )
                )
              )
            ),
            // From here it should do this for the given number for example 10
            new XElement("Hmi.TextGraphicList.TextListEntry",
              new XAttribute("ID", 3),
              new XAttribute("CompositionName", "Entries"),
              new XElement("AttributeList",
                new XElement("DefaultEntry", "false"),
                new XElement("EntryType","SingleValue"),
                new XElement("From","0"),  // this number should go up by one after every example
                new XElement ("To","0") // same with this
              ),
              new XElement("ObjectList",
                new XElement("MultilingualText",
                  new XAttribute("ID", 4),
                  new XAttribute("CompositionName", "Text"),
                  new XElement("ObjectList",
                    new XElement("MultilingualTextItem",
                      new XAttribute("ID", 5),
                      new XAttribute("CompositionName", "Items"),
                      new XElement("AttributeList",
                        new XElement("Culture","de-DE"),
                        new XElement("Text",
                          new XElement("body",
                            new XElement("p","kein 0")
                          )
                        )
                      )
                    )
                  )
                )
              )
            )
          )
        )
      )
    )
  )
);

xmlDocument.Save(@"C:\Program Files (x86)\Tools\VisualStudioProjects\CustomersDetails.xml");
</code>```

答:
Use a combination of Enumerable.Range and Select to generate the repeated XML elements:

```<code>XDocument xmlDocument = new XDocument(
  new XDeclaration("1.0", "utf-8", "yes"),
  new XElement("Document",
    new XElement("DocumentInfo",
      new XElement("Created", "2022-02-09T13:52:07.8908726Z"),
      new XElement("ExportSetting", "WithDefaults"),
      new XElement("InstalledProducts",
        new XElement("Product",
          new XElement("DisplayName", "Totally Integrated Automation Portal"),
          new XElement("DisplayVersion", "V16")
        ),
        new XElement("OptionPackage",
          new XElement("DisplayName", "TIA Portal Version Control Interface"),
          new XElement("ObjectList",
            new XElement("MultilingualText",
              new XAttribute("ID", 1),
              new XAttribute("CompositionName", "Comment"),
              new XElement("ObjectList",
                new XElement("MultilingualTextItem",
                  new XAttribute("ID", 2),
                  new XAttribute("CompositionName", "Items"),
                  new XElement("AttributeList",
                    new XElement("Culture", "de-DE"),
                    new XElement("Text")
                  )
                )
              )
            ),
            Enumerable.Range(0, 10).Select(i => new XElement("Hmi.TextGraphicList.TextListEntry",
              new XAttribute("ID", 3),
              new XAttribute("CompositionName", "Entries"),
              new XElement("AttributeList",
                new XElement("DefaultEntry", "false"),
                new XElement("EntryType","SingleValue"),
                new XElement("From", i),
                new XElement ("To", i)
              ),
              new XElement("ObjectList",
                new XElement("MultilingualText",
                  new XAttribute("ID", 4),
                  new XAttribute("CompositionName", "Text"),
                  new XElement("ObjectList",
                    new XElement("MultilingualTextItem",
                      new XAttribute("ID", 5),
                      new XAttribute("CompositionName", "Items"),
                      new XElement("AttributeList",
                        new XElement("Culture","de-DE"),
                        new XElement("Text",
                          new XElement("body",
                            new XElement("p","kein 0")
                          )
                        )
                      )
                    )
                  )
                )
              )
            ))
          )
        )
      )
    )
  )
);
</code>```

Body:
Is there any way where I can make an loop of an whatever size and it will loop over the number given and add the XML elements. The first part of the code should remain like this and the down part should be dynamic.

string name = "haus";
XDocument xmlDocument = new XDocument(
  new XDeclaration("1.0", "utf-8", "yes"),
  new XElement("Document",
    new XElement("DocumentInfo",
      new XElement("Created", "2022-02-09T13:52:07.8908726Z"),
      new XElement("ExportSetting", "WithDefaults"),
      new XElement("InstalledProducts",
        new XElement("Product",
          new XElement("DisplayName", "Totally Integrated Automation Portal"),
          new XElement("DisplayVersion", "V16")
        ),
        new XElement("OptionPackage",
          new XElement("DisplayName", "TIA Portal Version Control Interface"),
          new XElement("ObjectList",
            new XElement("MultilingualText",
              new XAttribute("ID", 1),
              new XAttribute("CompositionName", "Comment"),
              new XElement("ObjectList",
                new XElement("MultilingualTextItem",
                  new XAttribute("ID", 2),
                  new XAttribute("CompositionName", "Items"),
                  new XElement("AttributeList",
                    new XElement("Culture", "de-DE"),
                    new XElement("Text")
                  )
                )
              )
            ),
            // From here it should do this for the given number for example 10
            new XElement("Hmi.TextGraphicList.TextListEntry",
              new XAttribute("ID", 3),
              new XAttribute("CompositionName", "Entries"),
              new XElement("AttributeList",
                new XElement("DefaultEntry", "false"),
                new XElement("EntryType","SingleValue"),
                new XElement("From","0"),  // this number should go up by one after every example
                new XElement ("To","0") // same with this
              ),
              new XElement("ObjectList",
                new XElement("MultilingualText",
                  new XAttribute("ID", 4),
                  new XAttribute("CompositionName", "Text"),
                  new XElement("ObjectList",
                    new XElement("MultilingualTextItem",
                      new XAttribute("ID", 5),
                      new XAttribute("CompositionName", "Items"),
                      new XElement("AttributeList",
                        new XElement("Culture","de-DE"),
                        new XElement("Text",
                          new XElement("body",
                            new XElement("p","kein 0")
                          )
                        )
                      )
                    )
                  )
                )
              )
            )
          )
        )
      )
    )
  )
);

xmlDocument.Save(@"C:\Program Files (x86)\Tools\VisualStudioProjects\CustomersDetails.xml");

Body:
Use a combination of Enumerable.Range and Select to generate the repeated XML elements:

XDocument xmlDocument = new XDocument(
  new XDeclaration("1.0", "utf-8", "yes"),
  new XElement("Document",
    new XElement("DocumentInfo",
      new XElement("Created", "2022-02-09T13:52:07.8908726Z"),
      new XElement("ExportSetting", "WithDefaults"),
      new XElement("InstalledProducts",
        new XElement("Product",
          new XElement("DisplayName", "Totally Integrated Automation Portal"),
          new XElement("DisplayVersion", "V16")
        ),
        new XElement("OptionPackage",
          new XElement("DisplayName", "TIA Portal Version Control Interface"),
          new XElement("ObjectList",
            new XElement("MultilingualText",
              new XAttribute("ID", 1),
              new XAttribute("CompositionName", "Comment"),
              new XElement("ObjectList",
                new XElement("MultilingualTextItem",
                  new XAttribute("ID", 2),
                  new XAttribute("CompositionName", "Items"),
                  new XElement("AttributeList",
                    new XElement("Culture", "de-DE"),
                    new XElement("Text")
                  )
                )
              )
            ),
            Enumerable.Range(0, 10).Select(i => new XElement("Hmi.TextGraphicList.TextListEntry",
              new XAttribute("ID", 3),
              new XAttribute("CompositionName", "Entries"),
              new XElement("AttributeList",
                new XElement("DefaultEntry", "false"),
                new XElement("EntryType","SingleValue"),
                new XElement("From", i),
                new XElement ("To", i)
              ),
              new XElement("ObjectList",
                new XElement("MultilingualText",
                  new XAttribute("ID", 4),
                  new XAttribute("CompositionName", "Text"),
                  new XElement("ObjectList",
                    new XElement("MultilingualTextItem",
                      new XAttribute("ID", 5),
                      new XAttribute("CompositionName", "Items"),
                      new XElement("AttributeList",
                        new XElement("Culture","de-DE"),
                        new XElement("Text",
                          new XElement("body",
                            new XElement("p","kein 0")
                          )
                        )
                      )
                    )
                  )
                )
              )
            ))
          )
        )
      )
    )
  )
);


问:
is there any way to Assert.pass() in TestNg
We have an Assertion where we can fail the script if certain condition is not met. Is there any way to pass it as well. For example rather than failing it, if some situation occurs i want the script to stop from executing forward and mark it as passed.

In short, is there any reverse of Assert.fail()

答:
When your test returns without an Exception or failed assertion, it will pass.

You can simply return; and your test should pass.


问:
AWS CloudFront in front of S3 and ALB
everyone. I have a case about CloudFront + S3 + ECS(ALB).

S3 bucket (enabled static web) (CSR - SPA) include:
/index.html
/admin
/static/(file media)

ECS + ALB: 1 cluster Fargate run web backend

So, the design like this picture:

I configured CloudFront behavior.

Path pattern: /internal/* -> Origin ALB

Path pattern: Default(*) -> Origin S3. S3 used the custom origin with s3 static web url not user the alias.

Result

When I request CloudFrontURL, it shows me the /index.html on the S3 bucket. (It's correct).

But when I request CloudFront/internal. It didn't show me the 404 code.

Then, I find the solution with lambda edge.

(link:

https://medium.com/radon-dev/redirection-on-cloudfront-with-lambda-edge-e72fd633603e

Hosting multiple SPA web apps on S3 + Cloudfront under same URL

).

I modify the example code in the link. My code:

```<code>var path = require('path');
var url = require('url');
exports.handler = (event, context, callback) => {
  // Extract the request from the CloudFront event that is sent to Lambda@Edge
  var request = event.Records[0].cf.request;

  const parsedPath = path.parse(request.uri);
  const parsedURL = url.parse(request.uri);
  // Extract the URI from the request
  var olduri = request.uri;
  if (parsedURL.path.includes('/internal')) {
    var newuri = "EC2Co-EcsEl-1KE5FOHEHN2NH-230429797.ap-southeast-1.elb.amazonaws.com";
    request.uri = newuri;
    console.log("alburi =" + " " + newuri);
  } else if (parsedPath.dir.includes('/') && parsedPath.base != 'index.html' && parsedPath.dir != '/admin') {
    var newuri = olduri.replace(parsedURL.pathname, '/index.html');
    request.uri = newuri;
    console.log("rooturi =" + " " + newuri);
  }
  // Return to CloudFront
  return callback(null, request);
};

</code>```

Result

When I request to the CloudfrontURL/ or CloudFrontURL/abcdxyz... or CloudFrontURL/something.. -> the response is the /index.html (Correct)

When I request to the CloudfrontURL/internal* -> the response is 502. like this

Please, help me. Sry about my English skill.

答:
If you look the error, that means the cloudfront try to get the internal from S3 instead of the ELB.
I suggest you to change your behaviour to have more simple :

1.Create a behavior that specifies a path pattern to route all static content requests to the S3 bucket. For example, you can set the "images/*.jpg" path pattern to route all requests for ".jpg" files in the images directory to the S3 bucket.

2.Edit the Default (*) path pattern behavior and set its Origin as your load balancer.

Or you can have this for example, two behaviours to two origin

Title: AWS CloudFront in front of S3 and ALB

Body:
everyone. I have a case about CloudFront + S3 + ECS(ALB).

S3 bucket (enabled static web) (CSR - SPA) include:
/index.html
/admin
/static/(file media)

ECS + ALB: 1 cluster Fargate run web backend

So, the design like this picture:

I configured CloudFront behavior.

Path pattern: /internal/* -> Origin ALB

Path pattern: Default(*) -> Origin S3. S3 used the custom origin with s3 static web url not user the alias.

Result

When I request CloudFrontURL, it shows me the /index.html on the S3 bucket. (It's correct).

But when I request CloudFront/internal. It didn't show me the 404 code.

Then, I find the solution with lambda edge.

(link:

https://medium.com/radon-dev/redirection-on-cloudfront-with-lambda-edge-e72fd633603e

Hosting multiple SPA web apps on S3 + Cloudfront under same URL

).

I modify the example code in the link. My code:

var path = require('path');
var url = require('url');
exports.handler = (event, context, callback) => {
  // Extract the request from the CloudFront event that is sent to Lambda@Edge
  var request = event.Records[0].cf.request;

  const parsedPath = path.parse(request.uri);
  const parsedURL = url.parse(request.uri);
  // Extract the URI from the request
  var olduri = request.uri;
  if (parsedURL.path.includes('/internal')) {
    var newuri = "EC2Co-EcsEl-1KE5FOHEHN2NH-230429797.ap-southeast-1.elb.amazonaws.com";
    request.uri = newuri;
    console.log("alburi =" + " " + newuri);
  } else if (parsedPath.dir.includes('/') && parsedPath.base != 'index.html' && parsedPath.dir != '/admin') {
    var newuri = olduri.replace(parsedURL.pathname, '/index.html');
    request.uri = newuri;
    console.log("rooturi =" + " " + newuri);
  }
  // Return to CloudFront
  return callback(null, request);
};

Result

When I request to the CloudfrontURL/ or CloudFrontURL/abcdxyz... or CloudFrontURL/something.. -> the response is the /index.html (Correct)

When I request to the CloudfrontURL/internal* -> the response is 502. like this

Please, help me. Sry about my English skill.


问:
Flutter - Isar schema is not defined
I have decided to use Isar database in my next project and I find it much helpful when dealing with local data.

I followed the quickstart guide in its website. I added dependencies. Annotated the contact class. Ran code generator. But at fourth step, I have problem creating schema while creating Isar instance.

```<code>initIsar() async {
  final dir = await getApplicationSupportDirectory();
  final isar = await Isar.open(
    schemas: [ContactSchema],
    directory: dir.path,
    inspector: true,
  );
}
</code>```

The problem is where I typed ContactSchema, it says

```<code>Undefined name 'ContactSchema'.
Try correcting the name to one that is defined, or defining the name.
</code>```

So question I have to ask is, I followed guide but I'm unable to create a schema. How can I create one to make Isar db work?

UPDATE:

```<code>import 'package:isar/isar.dart';

part 'contact.g.dart';

@Collection()
class Contact {
  @Id()
  int? id;

  late String name;
}
</code>```

After adding part 'contact.g.dart', type this command flutter pub run build_runner build and you are good to go.

答:
Hello Zahid If you want to add local db in your next flutter app there are various packgaes on https://pub.dev.

I would highly recomend you to go start with https://pub.dev/packages/floor it is easy to learn light weight to use..

Try this you would loved it.. and how to implement you can google it and here is a tutorial for how to use Floor in your flutter Mobile App.

https://www.youtube.com/watch?v=cQ7W7vpwTbk&t=1055s

Title: Flutter - Isar schema is not defined

Body:
I have decided to use Isar database in my next project and I find it much helpful when dealing with local data.

I followed the quickstart guide in its website. I added dependencies. Annotated the contact class. Ran code generator. But at fourth step, I have problem creating schema while creating Isar instance.

initIsar() async {
  final dir = await getApplicationSupportDirectory();
  final isar = await Isar.open(
    schemas: [ContactSchema],
    directory: dir.path,
    inspector: true,
  );
}

The problem is where I typed ContactSchema, it says

Undefined name 'ContactSchema'.
Try correcting the name to one that is defined, or defining the name.

So question I have to ask is, I followed guide but I'm unable to create a schema. How can I create one to make Isar db work?

UPDATE:

import 'package:isar/isar.dart';

part 'contact.g.dart';

@Collection()
class Contact {
  @Id()
  int? id;

  late String name;
}

After adding part 'contact.g.dart', type this command flutter pub run build_runner build and you are good to go.


问:
Cannot make Project Lombok work on Eclipse
I have followed the tutorial here
http://projectlombok.org/

but after adding import and @Data nothing happens.

Does it work on eclipse helios ?

答:
For me, The cause is different. My project name in settings.gradle was different from project name in eclipse.

So make sure your eclipse project name is as same as rootProject.name in settings.gradle


答:
Ok out of interest i had a look at your question... After a short search i would suggest using the testng "SkipException". I think this could be useful for your usecase. Maybe set a variable when you get your "situation" and have the SkipException in the "before" block of the other testcases so they are skipped.

SkipException Documentation

Title: is there any way to Assert.pass() in TestNg

Body:
We have an Assertion where we can fail the script if certain condition is not met. Is there any way to pass it as well. For example rather than failing it, if some situation occurs i want the script to stop from executing forward and mark it as passed.

In short, is there any reverse of Assert.fail()


问:
Linear Regression :: Normalization (Vs) Standardization
I am using Linear regression to predict data. But, I am getting totally contrasting results when I Normalize (Vs) Standardize variables.

Normalization               = x -xmin/ xmax – xmin

Zero Score Standardization  = x - xmean/ xstd

```<code>a) Also, when to Normalize (Vs) Standardize ?
b) How Normalization affects Linear Regression?
c) Is it okay if I don't normalize all the attributes/lables in the linear regression?
</code>```

Thanks,
Santosh

答: lot of people use Normalisation and Standardisation interchangeably. The purpose remains the same is to bring features into the same scale. The approach is to subtract each value from min value or mean and divide by max value minus min value or SD respectively. The difference you can observe that when using min value u will get all value + ve and mean value u will get bot + ve and -ve values. This is also one of the factors to decide which approach to use.</p>

Body:
I am using Linear regression to predict data. But, I am getting totally contrasting results when I Normalize (Vs) Standardize variables.

Normalization               = x -xmin/ xmax – xmin

Zero Score Standardization  = x - xmean/ xstd

a) Also, when to Normalize (Vs) Standardize ?
b) How Normalization affects Linear Regression?
c) Is it okay if I don't normalize all the attributes/lables in the linear regression?

Thanks,
Santosh


问:
In jest I can't access to my exported module

For example, I can't access to this module, why ?

```<code>let nodeCacheClient;

module.exports = {
    initNodeCache: () => {
        const NodeCache = require("node-cache");
        nodeCacheClient = new NodeCache();
        return nodeCacheClient;
    },
    insertToCacheWithTtl: (key, obj, ttl) => {
        return nodeCacheClient.set(key, obj, ttl);
    },
    getCache: (key) => {
        return nodeCacheClient.get(key);
    },
    deleteKey: (key) => {
        return nodeCacheClient.del(key);
    },
};
</code>```

when I run this test I get this : TypeError: Cannot read property 'get' of undefined Error

```<code>test("login a user", async () => {
        try {
            const response = await axiosInstance.post("users/login", {
                email: "test@gmail.com",
                password: "144847120",
                otpCode: getCacheClient.getCache("test@gmail.com")
            });
            console.log(response.data);
            expect(response.data.status).toBe("success");
        } catch (error) {
            console.log(error + " Error");
            expect(error);
        }
 });
</code>```

答:
It’s totally normal!

Actually you got access to your module, and the error is coming into your module where the “nodeCacheClient” is undefined since it was not defined!

Your error is coming from your “getCache()” function, in this syntax:

```<code>return nodeCacheClient.get(key);
</code>```

Where in your test you didnt call for the “initNodeCache()” method which will do

```<code>nodeCacheClient = new NodeCache();
</code>```

So, for your test scope, the nodeCacheClient is undefined, and that’s why

```<code>nodeCacheClient.get(key);
</code>```

Will return the

```<code>typeError: Cannot read property 'get' of undefined Error
</code>```

Body:
For example, I can't access to this module, why ?

let nodeCacheClient;

module.exports = {
    initNodeCache: () => {
        const NodeCache = require("node-cache");
        nodeCacheClient = new NodeCache();
        return nodeCacheClient;
    },
    insertToCacheWithTtl: (key, obj, ttl) => {
        return nodeCacheClient.set(key, obj, ttl);
    },
    getCache: (key) => {
        return nodeCacheClient.get(key);
    },
    deleteKey: (key) => {
        return nodeCacheClient.del(key);
    },
};

when I run this test I get this : TypeError: Cannot read property 'get' of undefined Error

test("login a user", async () => {
        try {
            const response = await axiosInstance.post("users/login", {
                email: "test@gmail.com",
                password: "144847120",
                otpCode: getCacheClient.getCache("test@gmail.com")
            });
            console.log(response.data);
            expect(response.data.status).toBe("success");
        } catch (error) {
            console.log(error + " Error");
            expect(error);
        }
 });

Body:
It’s totally normal!

Actually you got access to your module, and the error is coming into your module where the “nodeCacheClient” is undefined since it was not defined!

Your error is coming from your “getCache()” function, in this syntax:

return nodeCacheClient.get(key);

Where in your test you didnt call for the “initNodeCache()” method which will do

nodeCacheClient = new NodeCache();

So, for your test scope, the nodeCacheClient is undefined, and that’s why

nodeCacheClient.get(key);

Will return the

typeError: Cannot read property 'get' of undefined Error


问:
How would you grab old responses in cypress?
I have been trying to grab an old response to assert it has a certain response.

The issue is that the same call is posted at the same time and I can only grab the second response.

I was just wondering if there was a way to grab both responses so I can read each body to make sure the correct posts are made

I have used the following

public assertMixPanelCall(call: string): void {
        cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
            if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {
              req.alias = 'correctBody'
            }
          });
        cy.wait('@correctBody');
    }
```

So the response I get is the last response,
But I want to grab the penultimate response

答:
So I found the solution

From wherever I want to start capturing

```<code>cy.intercept('POST', 'https://api-js.mixpanel.com/track/*').as('call');
</code>```

generate array based on the number of calls previously I wish to check

```<code> const genArr = Array.from({length:noOfCalls},(v,k)=>k+1);
    const calls = [];
    cy.wrap(genArr).each(() => {
        calls.push(`@${call}`)
    })
</code>```

make the call based on the amount of times I wish to post the response

```<code>cy.wait(calls).then(differentRequests => {
    differentRequests.forEach(differentRequest => {
        if(atob(differentRequest.request.body.replace('data=','')).includes(call)) {
            pass = true
        }
    });
    expect(pass).to.be.true
  });

}
</code>```

Got the solution from here
https://medium.com/slido-dev-blog/cypress-io-is-pretty-amazing-and-if-you-havent-used-it-yet-and-need-a-jump-start-i-recommend-my-66ee6ac5f8d9

Body:
I have been trying to grab an old response to assert it has a certain response.

The issue is that the same call is posted at the same time and I can only grab the second response.

I was just wondering if there was a way to grab both responses so I can read each body to make sure the correct posts are made

I have used the following

public assertMixPanelCall(call: string): void {
        cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
            if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {
              req.alias = 'correctBody'
            }
          });
        cy.wait('@correctBody');
    }

So the response I get is the last response,
But I want to grab the penultimate response

Body:
So I found the solution

From wherever I want to start capturing

cy.intercept('POST', 'https://api-js.mixpanel.com/track/*').as('call');

generate array based on the number of calls previously I wish to check

 const genArr = Array.from({length:noOfCalls},(v,k)=>k+1);
    const calls = [];
    cy.wrap(genArr).each(() => {
        calls.push(`@${call}`)
    })

make the call based on the amount of times I wish to post the response

cy.wait(calls).then(differentRequests => {
    differentRequests.forEach(differentRequest => {
        if(atob(differentRequest.request.body.replace('data=','')).includes(call)) {
            pass = true
        }
    });
    expect(pass).to.be.true
  });

}

Got the solution from here
https://medium.com/slido-dev-blog/cypress-io-is-pretty-amazing-and-if-you-havent-used-it-yet-and-need-a-jump-start-i-recommend-my-66ee6ac5f8d9


问:
render Multidimensional array react js
how do display the array of the card in two columns instead of one with an image displaying sequentially?

```<code>return  (
    <div>

      {
        data?.length > 0 && data?.map(item=>{
          return(
              <div className='home-container'>
                <div className='card-image-container'>
                  <img className='card-image'  alt="blank" src={item.photo} />
                </div>
                <div className='card-content'>
                <h6 className='home-card-title'>{item.title} </h6>
                  <p className='home-card-desc'>{item.body}</p>
                </div>
              </div>

          )
        })
      }
     </div>
  );
</code>```

can someone tell me how to implement a multi-dimensional array in this?

答:
You can try using grid in css

#grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
```
<pre class="lang-js prettyprint-override"><code>return  (
    <div id='grid-container'>

      {
        data?.length > 0 && data?.map(item=>{
          return(
              <div className='home-container'>
                <div className='card-image-container'>
                  <img className='card-image'  alt="blank" src={item.photo} />
                </div>
                <div className='card-content'>
                <h6 className='home-card-title'>{item.title} </h6>
                  <p className='home-card-desc'>{item.body}</p>
                </div>
              </div>

          )
        })
      }
     </div>
  );
</code>```

To add padding/styling to the grid, you can check out more options here

Title: render Multidimensional array react js

Body:
how do display the array of the card in two columns instead of one with an image displaying sequentially?

return  (

      {
        data?.length > 0 && data?.map(item=>{
          return(

{item.title}

{item.body}

          )
        })
      }

  );

can someone tell me how to implement a multi-dimensional array in this?

Body:
You can try using grid in css

#grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

return  (
    <div id='grid-container'>

      {
        data?.length > 0 && data?.map(item=>{
          return(
              <div className='home-container'>
                <div className='card-image-container'>
                  <img className='card-image'  alt="blank" src={item.photo} />
                </div>
                <div className='card-content'>
                <h6 className='home-card-title'>{item.title} </h6>
                  <p className='home-card-desc'>{item.body}</p>
                </div>
              </div>

          )
        })
      }
     </div>
  );

To add padding/styling to the grid, you can check out more options here


问:
MongoDB transactions and readPreference option
Is there any way to use MongoDB multi-document transactions and readPreference=secondaryPreferred option at the same time? What is my goal: I have some functionality that makes a lot of heavy read operations, and I want to reduce the load from primary replica by executing read operations on secondary replicas.

MongoDB docs say that readPreference should be primary if transactions are used. So I am wondering how I can split load to read replicas. Does anyone know the way how to achieve this?

答:
There is no way to do that because transactions can only be executed in the primary node. After the commit point, the operations are replicated in the secondary members too.

Transactions in MongoDB automatically guarantee Read your own Writes and Monotonic Reads (by design) in order to ensure a good level of consistency. Even if readPreference=secondaryPreferred was possible, these properties would not be granted and the results would be quite unpredictable. The safer way to implement transactions (in particular ACID properties) in a NoSQL DBMS is to pretend to be working on a single instance DB.

This does not mean you cannot have distributed transactions (in fact they exist in MongoDB), but a single source of truth is kind of necessary for each shard.

As @dododo pointed out, this is a restriction that they might relax in the future, as described in the Driver Transactions Specification.


问:
Jenkins installation on Kubernetes issue with volume conflict
I'm following this Link to setup Jenkins on Kubernetes cluster.

The environment information is mentioned below,

```<code>Environment:-

On-Premise Physical Server

# kubectl get nodes
NAME          STATUS   ROLES      AGE     VERSION
master-server Ready    master     2d23h   v1.19.16
node-server1  Ready    worker1    2d23h   v1.19.16
node-server2  Ready    worker2    2d23h   v1.19.16
node-server3  Ready    worker3    2d23h   v1.19.16
</code>```

I have below yaml files.

```<code>deploy-jenkins.yaml
sa-jenkins.yaml
service-jenkins.yaml
volume-jenkins.yaml
</code>```

PersistentVolume i want to use my master server local path, So in the volume-jenkins.yaml file I have updated path and values as below.

  local:
    path: /home/linux-user/kubernetes/jenkins
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - master-server
```
<p>When i apply the <code>yaml</code> files, My jenkins pod remain in <code>pending</code> status always.</p>
<p>Jenkins Pod status:-</p>
```# kubectl get pods -n jenkins
NAME                       READY   STATUS    RESTARTS   AGE
jenkins-69b8564b9f-gm48n   0/1     Pending   0          102m
```
<p>Jenkins Pod describe Status:-</p>
```# kubectl describe pod jenkins-69b8564b9f-gm48n -n jenkins

Events:
  Type     Reason            Age                    From               Message
  ----     ------            ----                   ----               -------
  Warning  FailedScheduling  3m45s (x68 over 104m)  default-scheduler  0/4 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 3 node(s) had volume node affinity conflict.
```
<p>PV describe details:-</p>
```# kubectl describe pv jenkins-pv -n jenkins

Name:              jenkins-pv
Labels:            type=local
Annotations:       <none>
Finalizers:        [kubernetes.io/pv-protection]
StorageClass:      local-storage
Status:            Bound
Claim:             jenkins/jenkins-pvc
Reclaim Policy:    Retain
Access Modes:      RWO
VolumeMode:        Filesystem
Capacity:          10Gi
Node Affinity:
  Required Terms:
    Term 0:        kubernetes.io/hostname in [master-server]
Message:
Source:
    Type:  LocalVolume (a persistent volume backed by local storage on a node)
    Path:  /home/linux-user/kubernetes/jenkins
Events:    <none>
```

What is wrong with my yaml files? and let me know the way to solve the node conflict issue. Thanks in advance.

答:
...i want to use my master server local path

Add nodeSelector and tolerations to your deployment spec:

```<code>apiVersion: apps/v1
kind: Deployment
...
spec:
  ...
  template:
    ...
    spec:
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
      containers:
      - name: jenkins
        ...

</code>```

Body:
I'm following this Link to setup Jenkins on Kubernetes cluster.

The environment information is mentioned below,

Environment:-

On-Premise Physical Server

# kubectl get nodes
NAME          STATUS   ROLES      AGE     VERSION
master-server Ready    master     2d23h   v1.19.16
node-server1  Ready    worker1    2d23h   v1.19.16
node-server2  Ready    worker2    2d23h   v1.19.16
node-server3  Ready    worker3    2d23h   v1.19.16

I have below yaml files.

deploy-jenkins.yaml
sa-jenkins.yaml
service-jenkins.yaml
volume-jenkins.yaml

PersistentVolume i want to use my master server local path, So in the volume-jenkins.yaml file I have updated path and values as below.

  local:
    path: /home/linux-user/kubernetes/jenkins
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - master-server

When i apply the yaml files, My jenkins pod remain in pending status always.

Jenkins Pod status:-

# kubectl get pods -n jenkins
NAME                       READY   STATUS    RESTARTS   AGE
jenkins-69b8564b9f-gm48n   0/1     Pending   0          102m

Jenkins Pod describe Status:-

# kubectl describe pod jenkins-69b8564b9f-gm48n -n jenkins

Events:
  Type     Reason            Age                    From               Message
  ----     ------            ----                   ----               -------
  Warning  FailedScheduling  3m45s (x68 over 104m)  default-scheduler  0/4 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 3 node(s) had volume node affinity conflict.

PV describe details:-

# kubectl describe pv jenkins-pv -n jenkins

Name:              jenkins-pv
Labels:            type=local
Annotations:       <none>
Finalizers:        [kubernetes.io/pv-protection]
StorageClass:      local-storage
Status:            Bound
Claim:             jenkins/jenkins-pvc
Reclaim Policy:    Retain
Access Modes:      RWO
VolumeMode:        Filesystem
Capacity:          10Gi
Node Affinity:
  Required Terms:
    Term 0:        kubernetes.io/hostname in [master-server]
Message:
Source:
    Type:  LocalVolume (a persistent volume backed by local storage on a node)
    Path:  /home/linux-user/kubernetes/jenkins
Events:    <none>

What is wrong with my yaml files? and let me know the way to solve the node conflict issue. Thanks in advance.

Body:
...i want to use my master server local path

Add nodeSelector and tolerations to your deployment spec:

apiVersion: apps/v1
kind: Deployment
...
spec:
  ...
  template:
    ...
    spec:
      nodeSelector:
        node-role.kubernetes.io/master: ""
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
      containers:
      - name: jenkins
        ...


问:
How to change the color of a button?
I'm new to android programming. How do I change the color of a button?</p>

```<code><Button
    android:id="@+id/btn"
    android:layout_width="55dp"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:text="Button Text"
    android:paddingBottom="20dp"/>
</code>```

答:
in new update of android studio you have to change the

button  -> androidx.appcompat.widget.AppCompatButton

then only the button color will changed

res/drawable/button_color_border.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#FFDA8200" />

    <stroke
        android:width="3dp"
        android:color="#FFFF4917" />

</shape>

</code>```

And add button to your XML activity layout and set background
android:background="@drawable/button_color_border".

```<code><androidx.appcompat.widget.AppCompatButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_border"
    android:text="Button" />

</code>```

Title: How to change the color of a button?

Body:
I'm new to android programming. How do I change the color of a button?

<Button
    android:id="@+id/btn"
    android:layout_width="55dp"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:text="Button Text"
    android:paddingBottom="20dp"/>

Body:
in new update of android studio you have to change the

button  -> androidx.appcompat.widget.AppCompatButton

then only the button color will changed

res/drawable/button_color_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#FFDA8200" />

    <stroke
        android:width="3dp"
        android:color="#FFFF4917" />

</shape>

And add button to your XML activity layout and set background
android:background="@drawable/button_color_border".

<androidx.appcompat.widget.AppCompatButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_border"
    android:text="Button" />


问:
grep returns no matches for following expression
Using the (?<=_)(.*)(?=\.) regex with the 23353_test.txt test string returns nothing with grep with the -p option. It doesn’t show errors either. I expect the return to be test. But when the regex  is tried in regex101.com it runs correctly.

答:
1st solution: You should use awk for this requirement, please try following as per your shown samples. Setting field separators as _ OR . and checking condition if number of fields are 3 then printing 2nd field here.

```<code>s='23353_test.txt'
echo "$s" | awk -F'[_.]' 'NF==3{print $2}'
</code>```

2nd solution: Using sed program here with using capturing group capability of sed. Using -E option to enable ERE in sed then in main program using regex ^[^_]*_([^.]*)\..*, which matches from starting till 1st occurrence of _ and creating 1st and only capturing group which has everything which comes between _ and . in it and after it matching literal . till end of line. Then while substituting  whole line with 1st capturing group value.

```<code>s='23353_test.txt'
echo "$s" | sed -E 's/^[^_]*_([^.]*)\..*/\1/'
</code>```

3rd solution: Using GNU awk using awk's match function here. Using regex inside match function to match betwen 1st occurrence of _ till . comes and having it inside a capturing group, we are using array named arr which will store captured values in it, so printing 1st capturing group value by arr[1] in it.

```<code>echo "$s" | awk 'match($0,/^[^_]*_([^.]*)\..*$/,arr){print arr[1]}'
</code>```

4th solution: Using GNU grep here, where using its -o and -P options. Where -o option is for printing matched part only and -P flag is for enabling PCRE regex. Here is Online demo for following regex.

```<code>echo "$s" | grep -oP '^.*?_\K([^.]*)(?=\.\S+$)'
</code>```

Body:
1st solution: You should use awk for this requirement, please try following as per your shown samples. Setting field separators as _ OR . and checking condition if number of fields are 3 then printing 2nd field here.

s='23353_test.txt'
echo "$s" | awk -F'[_.]' 'NF==3{print $2}'

2nd solution: Using sed program here with using capturing group capability of sed. Using -E option to enable ERE in sed then in main program using regex ^[^_]*_([^.]*)\..*, which matches from starting till 1st occurrence of _ and creating 1st and only capturing group which has everything which comes between _ and . in it and after it matching literal . till end of line. Then while substituting  whole line with 1st capturing group value.

s='23353_test.txt'
echo "$s" | sed -E 's/^[^_]*_([^.]*)\..*/\1/'

3rd solution: Using GNU awk using awk's match function here. Using regex inside match function to match betwen 1st occurrence of _ till . comes and having it inside a capturing group, we are using array named arr which will store captured values in it, so printing 1st capturing group value by arr[1] in it.

echo "$s" | awk 'match($0,/^[^_]*_([^.]*)\..*$/,arr){print arr[1]}'

4th solution: Using GNU grep here, where using its -o and -P options. Where -o option is for printing matched part only and -P flag is for enabling PCRE regex. Here is Online demo for following regex.

echo "$s" | grep -oP '^.*?_\K([^.]*)(?=\.\S+$)'


问:
How to used position fixed without overlapping the width of container
Here is the codepen. As you can see using position: sticky; the div width is not overlapping. However when I tried using position: fixed the div width is overlapping. Can anyone help me with how to achieve it? My goal is I what my footer class to fixed at the bottom even I scroll.

* {
-webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    font-size: inherit;
}

.left {
    position: fixed;
    top: 0;
    width: 43px;
    left: 0;
    bottom: 0;
    /* border-right: 1px solid #e8edf3; */
    background-color: red;
    padding: 6px;
    overflow: hidden;
    transition: .18s ease-out width;
}

.main {
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
    left: 42px;
    right: 0;
    bottom: 0;
    overflow: auto;
    transition: .22s ease left;
    background: green;
}

.tool {
    display: flex;
    padding: 3px 4px;
    /* box-sizing: border-box; */
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #e8edf3;
    position: sticky;
    top: 0;
    background-color: #ffffff;
    z-index: 13;
    justify-content: space-between;
}

.footer {
    padding: 3px 4px;
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #e8edf3;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    z-index: 13;
    display: flex;
    justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="left">

</div>
<div class="main">
  <div class="tool">
    <div class="test">Test toolbar design</div>
        <div class="test">Test toolbar design</div>
  </div>
  <div class="footer">
    <div class="test">Test footer design</div>
        <div class="test">Test footer design</div>
  </div>
<div></code>```

答:
Change the footer width to width: calc(100% - 43px);. Where 43px is the value of the left property of its relative parent (.main).

```<code>.footer {
    width: calc(100% - 43px);
}
.left.expand ~ .main .footer {
    width: calc(100% - 320px);
}
</code>```

Body:
Here is the codepen. As you can see using position: sticky; the div width is not overlapping. However when I tried using position: fixed the div width is overlapping. Can anyone help me with how to achieve it? My goal is I what my footer class to fixed at the bottom even I scroll.

* {
-webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    font-size: inherit;
}

.left {
    position: fixed;
    top: 0;
    width: 43px;
    left: 0;
    bottom: 0;
    /* border-right: 1px solid #e8edf3; */
    background-color: red;
    padding: 6px;
    overflow: hidden;
    transition: .18s ease-out width;
}

.main {
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
    left: 42px;
    right: 0;
    bottom: 0;
    overflow: auto;
    transition: .22s ease left;
    background: green;
}

.tool {
    display: flex;
    padding: 3px 4px;
    /* box-sizing: border-box; */
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #e8edf3;
    position: sticky;
    top: 0;
    background-color: #ffffff;
    z-index: 13;
    justify-content: space-between;
}

.footer {
    padding: 3px 4px;
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #e8edf3;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    z-index: 13;
    display: flex;
    justify-content: space-between;
}

Test toolbar design

Test toolbar design

Test footer design

Test footer design

Body:
Change the footer width to width: calc(100% - 43px);. Where 43px is the value of the left property of its relative parent (.main).

.footer {
    width: calc(100% - 43px);
}
.left.expand ~ .main .footer {
    width: calc(100% - 320px);
}


问:
Finding Minimum For every group in ArrayList in Java
I have a class as below.

```<code>public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}
</code>```

I an creating an ArrayList as Below.

```<code>ArrayList<Employee> arrEmployee = new ArrayList<Employee>;
</code>```

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

答:
You'll have to do it youself:

```<code>Map<Integer, Employee> minSalary = new HashMap<Integer, Employee>();
for(Employee emp : employeeList) {
    Integer depId = emp.getDepartmentId();
    if(minSalary.containsKey(depId )) {
        if(emp.getSalary() < minSalary.get(depId).getSalary()) {
            minSalary.put(depId, emp);
        }
    }
    else {
        minSalary.put(depId, emp);
    }
}
</code>```

Note that only one Employee is stored with minimal salary, but it is sufficient when you only want to know the salary. If you really need all employees with the minimal salary, you need a Map<Integer, List<Employee>>.
In that case i'd recommend to store the Employees redundantly in a List<Employee> and a `Map<Integer, List<Employee>> (per departmentID, as suggested by other answers.

Body:
I have a class as below.

public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}

I an creating an ArrayList as Below.

ArrayList<Employee> arrEmployee = new ArrayList<Employee>;

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

Body:
You'll have to do it youself:

Map<Integer, Employee> minSalary = new HashMap<Integer, Employee>();
for(Employee emp : employeeList) {
    Integer depId = emp.getDepartmentId();
    if(minSalary.containsKey(depId )) {
        if(emp.getSalary() < minSalary.get(depId).getSalary()) {
            minSalary.put(depId, emp);
        }
    }
    else {
        minSalary.put(depId, emp);
    }
}

Note that only one Employee is stored with minimal salary, but it is sufficient when you only want to know the salary. If you really need all employees with the minimal salary, you need a Map<Integer, List<Employee>>.
In that case i'd recommend to store the Employees redundantly in a List<Employee> and a `Map<Integer, List<Employee>> (per departmentID, as suggested by other answers.


问:
ZoneInfoNotFoundError: 'No time zone found with key utc'
While trying to load my webpage on the browser, I got the message.

A server error occurred.  Please contact the administrator

And when I go back to check my termimal, I see the message

zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key UTC'

I have checked but don't know what's wrong. I even tried changing the UTC to my original timezone, but it still didn't work.

P.S: I started getting this error after I tried working on templates inheritance

Here's what my settings.py file looks like

```<code>INSTALLED_APPS = [
    'newapp.apps.NewappConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'new.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'new.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
</code>```

答: Add tzdata to your requirements or pip install tzdata

Body:
While trying to load my webpage on the browser, I got the message.

A server error occurred.  Please contact the administrator

And when I go back to check my termimal, I see the message

zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key UTC'

I have checked but don't know what's wrong. I even tried changing the UTC to my original timezone, but it still didn't work.

P.S: I started getting this error after I tried working on templates inheritance

Here's what my settings.py file looks like

INSTALLED_APPS = [
    'newapp.apps.NewappConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'new.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'new.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


问:
Sign-Up Form Working But Errors Not Showing
I made a sign-up form for my website using php on my webpage, and connecting it to mySQL. The database seems to work and the data for signed up users does appear in it. However, on the front-end no messages of "Registration successful" or any errors are being displayed such as "Email already registered" But the queries seem to work as it only registers accounts following the conditions. I would appreciate any help in getting the messages to work.

Attached is the code in question:

Sign-up form:

```<code><?php

require_once "config.php";
require_once "session.php";

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $fullname = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);
    $password_hash = password_hash($password, PASSWORD_BCRYPT);

    if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
        $error = '';
        //Bind parameters (s=string, i=int, b=blob, etc), in our case the username is a string so we use "s"
        $query->bind_param('s', $email);
        $query->execute();
        //Store the result so we can check if account exists in database
        $query->store_result();
           if ($query->num_rows > 0) {
               $error .= '<p class="error">The email address is already registered!</p>';
           } else {
               //Validate password
               if (strlen($password) < 6) {
                   $error .= '<p class="error">Password must have atleast 6 characters</p>';
               }
               //Validate confirm password
               if (empty($confirm_password)) {
                   $error .= '<p class="error">Please enter confirm password.</p>';
               } else {
                   if (empty($error) && ($password != $confirm_password)) {
                       $error .= '<p class="error">Passwords did not match</p>';
                   }
               }
               if (empty($error)) {
                   $insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?,?,?);");
                   $insertQuery->bind_param("sss", $fullname, $email, $password_hash);
                   $result = $insertQuery->execute();
                   if ($result) {
                       $error .= '<p class="success">Your registration was successful</p>';
                   } else {
                       $error .= '<p class="error">Something went wrong!</p>';
                   }
                  $insertQuery->close();
               }
           }
    }
    $query->close();

    //Close DB connection
    mysqli_close($db);
}

?>
</code>```

config.php:

```<code><?php
define('DBSERVER', 'localhost'); //Database server
define('DBUSERNAME', 'root'); //Database username
define('DBPASSWORD',''); //Database password
define('DBNAME', 'users'); //Database name

/* connect to MySQL databse */
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);

//check db connection
if($db === false){
    die("Error: connection error.".mysqli_connect_error());
}
?>
</code>```

session.php:

```<code><?php
//Start the session
session_start();

//if the user is already logged in then redirect user to welcome page
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
    header("location: loggedinuserhome.html");
    exit;
}
?>
</code>```

I am making this form following tutorials so lack deep knowledge of the subject so would love if someone could guide me through it and explicitly point out the error. Thank You!

答: Your Registration Successful message is also stored in $error variable but where you print $error, that is missing.</p>

Body:
I made a sign-up form for my website using php on my webpage, and connecting it to mySQL. The database seems to work and the data for signed up users does appear in it. However, on the front-end no messages of "Registration successful" or any errors are being displayed such as "Email already registered" But the queries seem to work as it only registers accounts following the conditions. I would appreciate any help in getting the messages to work.

Attached is the code in question:

Sign-up form:

<?php

require_once "config.php";
require_once "session.php";

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

    $fullname = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);
    $password_hash = password_hash($password, PASSWORD_BCRYPT);

    if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
        $error = '';
        //Bind parameters (s=string, i=int, b=blob, etc), in our case the username is a string so we use "s"
        $query->bind_param('s', $email);
        $query->execute();
        //Store the result so we can check if account exists in database
        $query->store_result();
           if ($query->num_rows > 0) {
               $error .= '
The email address is already registered!
';
           } else {
               //Validate password
               if (strlen($password) < 6) {
                   $error .= '
Password must have atleast 6 characters
';
               }
               //Validate confirm password
               if (empty($confirm_password)) {
                   $error .= '
Please enter confirm password.
';
               } else {
                   if (empty($error) && ($password != $confirm_password)) {
                       $error .= '
Passwords did not match
';
                   }
               }
               if (empty($error)) {
                   $insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?,?,?);");
                   $insertQuery->bind_param("sss", $fullname, $email, $password_hash);
                   $result = $insertQuery->execute();
                   if ($result) {
                       $error .= '
Your registration was successful
';
                   } else {
                       $error .= '
Something went wrong!
';
                   }
                  $insertQuery->close();
               }
           }
    }
    $query->close();

    //Close DB connection
    mysqli_close($db);
}

?>

config.php:

<?php
define('DBSERVER', 'localhost'); //Database server
define('DBUSERNAME', 'root'); //Database username
define('DBPASSWORD',''); //Database password
define('DBNAME', 'users'); //Database name

/* connect to MySQL databse */
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);

//check db connection
if($db === false){
    die("Error: connection error.".mysqli_connect_error());
}
?>

session.php:

<?php
//Start the session
session_start();

//if the user is already logged in then redirect user to welcome page
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
    header("location: loggedinuserhome.html");
    exit;
}
?>

I am making this form following tutorials so lack deep knowledge of the subject so would love if someone could guide me through it and explicitly point out the error. Thank You!


问:
Pass template function to std::bind?
I want to use std::bind with template function. Is it somehow possible?

P.S. It is IMPORTANT to use std::bind, because I know at least one solution through lambdas and want to find out if there is std::bind solution.

#include <iostream>
#include <functional>
#include <memory>

using namespace std;

struct foo : std::enable_shared_from_this<foo>
{
    void f()
    {
        // doesn't compile, error : no matching function for call to 'bind'
        auto cb = std::bind(&foo::handle, shared_from_this(), placeholders::_1, placeholders::_2);
    }

    template <typename T, typename U>
    void handle(T, U)
    {
    }
};

int main()
{
    return 0;
}
```

答:
&foo::handle is not valid C++, because foo::handle is not a function. foo::handle<int, int> is a function, and foo::handle<double, std::string> is a different function.

You will have to wrap it in something, so you may as well use a lambda.

Title: Pass template function to std::bind?


问:
Rstudio potential memory leak / background activity?
I’m having a lot of trouble working with Rstudio on a new PC. I could not find a solution searching the web.

When Rstudio is on, it is constantly eating up memory until it becomes unworkable. If I work on an existing project, it takes half an hour to an hour to become impossible to work with. If I start a new project without loading any objects or packages, just writing scripts without even running them, it takes longer to reach that point, however, it still does.

When I first start the program, the Task Manager shows memory usage of 950-1000 MB already (sometimes larger), and as I work, it climbs up to 6000 MB at which point it is impossible to work with as every activity is delayed and 'stuck'. Just to compare, on my old PC while working on the program, the Task Manager shows 100-150 MB. When I click the "Memory Usage Report" within Rstudio, the "used by session" is very small, the "used by system" is almost at a maximum yet Rstudio is the only thing taking up they system memory on the PC.

Things I tried: installing older versions of both R and Rstudio, pausing my anti-virus program, changing compatibility mode, zoom on "100%". It feels like Rstudio is continuously running something in the background as the memory usage keeps growing (and quite quickly). But maybe it is something else entirely.

I am currently using the latest versions of R and Rstudio (4.1.2, and 2021.09.0-351), on a PC with processor Intel i7, x64 bit, RAM 16GM, Windows 10.

What should I look for at this point?

答:
On Windows, there is several typical memory or CPU issues with Rstudio. In my answer, I explain how the Rstudio interface itself use memory and CPU, as soon as you open a project (e.g., when Rstudio show you some .Rmd files). The memory / CPU cost associated with the computation is not covered in my answer (i.e. when you have performance issues when executing a line of code = not covered).

When working on 'long' .Rmd files within Rstudio on Windows, the CPU and/or memory usage get sometimes very high and increases progressively (e.g., because of a process named 'Qtwebengineprocess'). To solve the problem caused by long Rmd files loaded within a Rstudio session, you should:

pay attention to the process of Rstudio that consume memory, when scanning your code (i.e. disable or enable stuff in the 'Global options' menu of Rstudio). For example, try to disable 'inline display'(Tools => Global options => Rmarkdown => Show equation and image preview => Never). This post put me on this way to consider that memory / CPU leak are sometimes due to Rstudio itself, nor the data or the code.

set up a bookdown project, in order to split your large Rmd files into several Rmd. See here.

Bonus step, see if there is a conflict in some packages which are loaded with the command tidyverse_conflicts(),  but it's already a 'computing problem' (not covered here).