问:
Making bitmaps with magenta background appear transparent in WPF
I'm in process of converting some legacy software that is 15 years old into WPF and its graphics are often some 8-bit bitmaps with magenta background, something like this:

With Gdi32 it was common approach to use magenta as transparency key to draw graphics. With System.Drawing it would be a one liner, i.e. _myImg.MakeTransparent(Color.Magenta). But what about WPF? Is there even such a thing as standard practice for aforementioned scenario?

I was really hoping this would work out of the box:

    <Image Width="128">
        <Image.Source>
            <BitmapImage UriSource="Media\opacityTest.bmp" />
        </Image.Source>
        <Image.OpacityMask>
            <SolidColorBrush Color="Magenta" />
        </Image.OpacityMask>
    </Image>
```

Alas, although it is allowed, it does nothing:

Am I missing something or is this impossible in WPF?

Ultimately, I may have to write code to convert these bitmaps into transparent pngs, cache them somewhere and load those instead. If so, does anyone know of any resources that can help me accomplish this aside from Gdi+?

There is a similar question: Make part of an image transparent. But no definitive answer (or I really can't quite believe it's not possible).

答:
I ended up creating a new image (32bit pargb) based on the original image and a color key, here's the code for whatever it's worth:

```<code>BitmapSource MakeTransparent(BitmapSource img, Color maskColor)
{
    var format = PixelFormats.Pbgra32;
    var stride = ((img.PixelWidth * format.BitsPerPixel + 31) & ~31) >> 3;
    var pixels = new byte[img.PixelHeight * stride];

    img.CopyPixels(pixels, stride, 0);

    for (var i = 0; i < stride * img.PixelHeight; i += 4)
        if (Color.FromRgb(pixels[i + 2], pixels[i + 1], pixels[i]) == maskColor)
            for (var j = i; j < i + 4; j++)
                pixels[j] = 0;

    return BitmapSource.Create(
        img.PixelWidth, img.PixelHeight,
        img.DpiX, img.DpiY,
        format,
        null,
        pixels,
        stride);
}
</code>```

It does not use System.Drawing so no Gdi+ required, it simply modifies the pixel array replacing the specified maskColor with premultiplied alpha rgb values set to 0.

Example usage:
TestImage = MakeTransparent(new BitmapImage(new Uri(@"opacityTest.bmp", UriKind.Relative)), Colors.Magenta);

The result:

Body:
I'm in process of converting some legacy software that is 15 years old into WPF and its graphics are often some 8-bit bitmaps with magenta background, something like this:

With Gdi32 it was common approach to use magenta as transparency key to draw graphics. With System.Drawing it would be a one liner, i.e. _myImg.MakeTransparent(Color.Magenta). But what about WPF? Is there even such a thing as standard practice for aforementioned scenario?

I was really hoping this would work out of the box:

    <Image Width="128">
        <Image.Source>
            <BitmapImage UriSource="Media\opacityTest.bmp" />
        </Image.Source>
        <Image.OpacityMask>
            <SolidColorBrush Color="Magenta" />
        </Image.OpacityMask>
    </Image>

Alas, although it is allowed, it does nothing:

Am I missing something or is this impossible in WPF?

Ultimately, I may have to write code to convert these bitmaps into transparent pngs, cache them somewhere and load those instead. If so, does anyone know of any resources that can help me accomplish this aside from Gdi+?

There is a similar question: Make part of an image transparent. But no definitive answer (or I really can't quite believe it's not possible).

Body:
I ended up creating a new image (32bit pargb) based on the original image and a color key, here's the code for whatever it's worth:

BitmapSource MakeTransparent(BitmapSource img, Color maskColor)
{
    var format = PixelFormats.Pbgra32;
    var stride = ((img.PixelWidth * format.BitsPerPixel + 31) & ~31) >> 3;
    var pixels = new byte[img.PixelHeight * stride];

    img.CopyPixels(pixels, stride, 0);

    for (var i = 0; i < stride * img.PixelHeight; i += 4)
        if (Color.FromRgb(pixels[i + 2], pixels[i + 1], pixels[i]) == maskColor)
            for (var j = i; j < i + 4; j++)
                pixels[j] = 0;

    return BitmapSource.Create(
        img.PixelWidth, img.PixelHeight,
        img.DpiX, img.DpiY,
        format,
        null,
        pixels,
        stride);
}

It does not use System.Drawing so no Gdi+ required, it simply modifies the pixel array replacing the specified maskColor with premultiplied alpha rgb values set to 0.

Example usage:
TestImage = MakeTransparent(new BitmapImage(new Uri(@"opacityTest.bmp", UriKind.Relative)), Colors.Magenta);

The result:


来源: stackexchange

问:
Function works as intended but when converted into an onEdit() function it doesn't run till the end
I have made this nice code which does the job if I fire it from the script editor, which is to check some dates and send out some e-mails if some dates are too close to each other, but if I convert it into an onEdit() function and do an edit it launched but doesn't finishes which is such a shame. The code I am using is below. Does anyone know why it does this?</p>

```<code>function onEdit1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var readMeSheet = ss.getSheetByName("ReadMe");
  var today = new Date();
  readMeSheet.getRange(37,1).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var dateOfLastCheck = new Date(readMeSheet.getRange(37,2).getValue());
  var overdueCheck = Math.floor(today.getTime()-dateOfLastCheck.getTime());
  var days = (1000*60*60*24);
  var temp = overdueCheck/days;

  if ( overdueCheck/days > 2 ) {
  readMeSheet.getRange(37,2).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var lastActiveSheet = ss.getActiveSheet().getName();
  ss.setActiveSheet(ss.getSheetByName('Active Jobs'));
  var fEmptyRow = getFirstEmptyRow('Active Jobs');

  for ( i=2; i<fEmptyRow; i++ ){
  var jobDate = new Date(ss.getActiveSheet().getRange(i,15).getValue());
  var dif = Math.floor(jobDate.getTime()-today.getTime());
    if ( dif/days < 3) {
      switch(ss.getActiveSheet().getRange(i,8).getValue()){
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.com";
          break
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.*******.com";
          break
      }

      switch(ss.getActiveSheet().getRange(i,8).getValue()){
          case "*******":
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
      }

                         if (MailApp.getRemainingDailyQuota() > 0) {
                            //GmailApp.sendEmail(ss.getActiveSheet().getRange(i,8).getValue() + emailExtension + teamLeader, 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              GmailApp.sendEmail("*******@*******.com", 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              'Hello, could you please amend the job if it is not on schedule to complete within the next 3 days and inform the PAT leader? If everything is on track please disregard this e-mail. :)')
                                                                   }
                                                                 }
                                }
  ss.setActiveSheet(ss.getSheetByName(lastActiveSheet));
}
}

function getFirstEmptyRow(sheet) {
  var spr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
  var column = spr.getRange(2,1,spr.getMaxRows()-1,1);
  var values = column.getValues(); // get all data in one call
  for(var ct = values.length-1; ct > -1; ct--){
    if(values[ct][0] != ""){
      var emptyRow = ct + 3;
      break;
    }
  }
  return emptyRow;
}
</code>```

答:
You should know the difference between simple triggers, which are functions named in a specific way like onEdit, and installable triggers that you create. As Documentation says,

Because simple triggers fire automatically, without asking the user for authorization, they are subject to several restrictions: [...] They cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization

If this appears strange to you, imagine if there was no such restriction; then when someone created a spreadsheet with onEdit trigger and shared it with you, the trigger would start doing things like sending/reading email from your account, without your knowledge.

An installable trigger has the authorization of the user who creates the trigger, who can authorize it to send email, etc, from their account.

ContentLicense: CC BY-SA 3.0

Body:
I have made this nice code which does the job if I fire it from the script editor, which is to check some dates and send out some e-mails if some dates are too close to each other, but if I convert it into an onEdit() function and do an edit it launched but doesn't finishes which is such a shame. The code I am using is below. Does anyone know why it does this?

function onEdit1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var readMeSheet = ss.getSheetByName("ReadMe");
  var today = new Date();
  readMeSheet.getRange(37,1).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var dateOfLastCheck = new Date(readMeSheet.getRange(37,2).getValue());
  var overdueCheck = Math.floor(today.getTime()-dateOfLastCheck.getTime());
  var days = (1000*60*60*24);
  var temp = overdueCheck/days;

  if ( overdueCheck/days > 2 ) {
  readMeSheet.getRange(37,2).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var lastActiveSheet = ss.getActiveSheet().getName();
  ss.setActiveSheet(ss.getSheetByName('Active Jobs'));
  var fEmptyRow = getFirstEmptyRow('Active Jobs');

  for ( i=2; i<fEmptyRow; i++ ){
  var jobDate = new Date(ss.getActiveSheet().getRange(i,15).getValue());
  var dif = Math.floor(jobDate.getTime()-today.getTime());
    if ( dif/days < 3) {
      switch(ss.getActiveSheet().getRange(i,8).getValue()){
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.com";
          break
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.*******.com";
          break
      }

      switch(ss.getActiveSheet().getRange(i,8).getValue()){
          case "*******":
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
      }

                         if (MailApp.getRemainingDailyQuota() > 0) {
                            //GmailApp.sendEmail(ss.getActiveSheet().getRange(i,8).getValue() + emailExtension + teamLeader, 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              GmailApp.sendEmail("*******@*******.com", 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              'Hello, could you please amend the job if it is not on schedule to complete within the next 3 days and inform the PAT leader? If everything is on track please disregard this e-mail. :)')
                                                                   }
                                                                 }
                                }
  ss.setActiveSheet(ss.getSheetByName(lastActiveSheet));
}
}

function getFirstEmptyRow(sheet) {
  var spr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
  var column = spr.getRange(2,1,spr.getMaxRows()-1,1);
  var values = column.getValues(); // get all data in one call
  for(var ct = values.length-1; ct > -1; ct--){
    if(values[ct][0] != ""){
      var emptyRow = ct + 3;
      break;
    }
  }
  return emptyRow;
}


问:
Android Studio - Rewarded Video Ad loaded but not shown
I tried the following code (main_activity.java)

```<code>        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
// Use an activity context to get the rewarded video instance.
        mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
        mRewardedVideoAd.setRewardedVideoAdListener(this);
        loadRewardedVideoAd();
    }

    private void loadRewardedVideoAd() {
        mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
                new AdRequest.Builder().build());

        if (mRewardedVideoAd.isLoaded()) {
            mRewardedVideoAd.show();
        }
</code>```

logcat says, that the Ad is loaded but it doesn´t show up. I want to display the ad in a seperate fragment, so maybe the "(this)" is wrong?

Thank you for your help...
See this reference: https://developers.google.com/admob/android/rewarded-video

答:
I fixed it:</p>

```<code> @Override
    public void onRewardedVideoAdLoaded() {
        mRewardedVideoAd.show();
    }
</code>```

Body:
I tried the following code (main_activity.java)

        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
// Use an activity context to get the rewarded video instance.
        mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
        mRewardedVideoAd.setRewardedVideoAdListener(this);
        loadRewardedVideoAd();
    }

    private void loadRewardedVideoAd() {
        mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
                new AdRequest.Builder().build());

        if (mRewardedVideoAd.isLoaded()) {
            mRewardedVideoAd.show();
        }

logcat says, that the Ad is loaded but it doesn´t show up. I want to display the ad in a seperate fragment, so maybe the "(this)" is wrong?

Thank you for your help...
See this reference: https://developers.google.com/admob/android/rewarded-video

Body:
I fixed it:

 @Override
    public void onRewardedVideoAdLoaded() {
        mRewardedVideoAd.show();
    }


问:
How to configure MySQL with MySQLTuner correctly
I'm a newbie and I just installed my first server, I am using MySQLTuner to optimize the MySQL database but I don't know what is the better way to tune according to MySQLTuner's output. How to tune my.cnf according to MySQLTuner output?

Here is the MySQLTuner output:

```<code> >>  MySQLTuner 1.7.4 - Major Hayden <major@mhtx.net>
 >>  Bug reports, feature requests, and downloads at http://mysqltuner.com/
 >>  Run with '--help' for additional options and output filtering

[--] Skipped version check for MySQLTuner script
[OK] Logged in using credentials from debian maintenance account.
[OK] Currently running supported MySQL version 10.1.28-MariaDB-1~trusty
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: /var/lib/mysql/s118874.err(0B)
[!!] Log file /var/lib/mysql/s118874.err doesn't exist
[!!] Log file /var/lib/mysql/s118874.err isn't readable.

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE
[--] Data in MyISAM tables: 1G (Tables: 53)
[--] Data in InnoDB tables: 2G (Tables: 502)
[OK] Total fragmented tables: 0

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] There is no basic password file list!

-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 1d 13h 39m 11s (9M q [73.549 qps], 390K conn, TX: 13G, RX: 1G)
[--] Reads / Writes: 93% / 7%
[--] Binary logging is enabled (GTID MODE: OFF)
[--] Physical Memory     : 23.5G
[--] Max MySQL memory    : 4.1G
[--] Other process memory: 12.1G
[--] Total buffers: 2.6G global + 7.5M per thread (200 max threads)
[--] P_S Max memory usage: 98M
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 4.1G (17.61% of installed RAM)
[OK] Maximum possible memory usage: 4.1G (17.61% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/9M)
[!!] Highest connection usage: 100%  (200/200)
[OK] Aborted connections: 0.00%  (0/390176)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[OK] Query cache efficiency: 27.0% (2M cached / 9M selects)
[!!] Query cache prunes per day: 406250
[OK] Sorts requiring temporary tables: 0% (452 temp sorts / 1M sorts)
[OK] No joins without indexes
[!!] Temporary tables created on disk: 31% (505K on disk / 1M total)
[OK] Thread cache hit rate: 99% (346 created / 390K connections)
[!!] Table cache hit rate: 4% (400 open / 9K opened)
[OK] Open file limit used: 7% (77/1K)
[OK] Table locks acquired immediately: 99% (7M immediate / 7M locks)
[OK] Binlog cache memory access: 100.00% (501178 Memory / 501178 Total)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 98.8M
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 16 thread(s).
[--] Using default value is good enough for your version (10.1.28-MariaDB-1~trusty)

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 29.4% (39M used / 134M cache)
[OK] Key buffer size / total MyISAM indexes: 128.0M/150.6M
[OK] Read Key buffer hit rate: 100.0% (2B cached / 38K reads)
[OK] Write Key buffer hit rate: 99.3% (48K cached / 48K writes)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[!!] InnoDB buffer pool / data size: 2.0G/2.0G
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (3.125 %): 32.0M * 2/2.0G should be equal 25%
[!!] InnoDB buffer pool instances: 8
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[OK] InnoDB Read buffer efficiency: 100.00% (1820526478 hits/ 1820563369 total)
[!!] InnoDB Write Log efficiency: 5.26% (27496 hits/ 522990 total)
[OK] InnoDB log waits: 0.00% (0 waits / 550486 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is enabled.
[OK] Aria pagecache size / total Aria indexes: 128.0M/1B
[OK] Aria pagecache hit rate: 97.8% (22M cached / 478K reads)

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Reduce or eliminate persistent connections to reduce connection usage
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Increasing the query_cache size over 128M may reduce performance
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries which have no LIMIT clause
    Increase table_open_cache gradually to avoid file descriptor limits

    Beware that open_files_limit (1024) variable
    should be greater than table_open_cache (400)
    Consider installing Sys schema from https://github.com/mysql/mysql-sys

Variables to adjust:
    max_connections (> 200)
    wait_timeout (< 300)
    interactive_timeout (< 28800)
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_size (> 256M) [see warning above]
    tmp_table_size (> 64M)
    max_heap_table_size (> 64M)
    table_open_cache (> 400)
    innodb_buffer_pool_size (>= 2G) if possible.
    innodb_log_file_size should be (=256M) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
    innodb_buffer_pool_instances(=2)
</code>```

My current setting on MySQL:

```<code>[client]
port            = 3306
socket          = /var/run/mysqld/mysqld.sock

[mysqld_safe]
socket          = /var/run/mysqld/mysqld.sock
nice            = 0

[mysqld]
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc_messages_dir = /usr/share/mysql
lc_messages     = en_US
skip-external-locking
bind-address            = 127.0.0.1

max_connections         = 200
connect_timeout         = 5
wait_timeout            = 300
max_allowed_packet      = 16M
thread_cache_size       = 128
sort_buffer_size        = 4M
bulk_insert_buffer_size = 16M
tmp_table_size          = 64M
max_heap_table_size     = 64M
performance_schema = ON

myisam_recover_options = BACKUP
key_buffer_size         = 128M
#open-files-limit       = 2000
table_open_cache        = 400
myisam_sort_buffer_size = 512M
concurrent_insert       = 2
read_buffer_size        = 2M
read_rnd_buffer_size    = 1M

query_cache_limit               = 2G
query_cache_size                = 256M
#query_cache_strip_comments =1
query_cache_type                = 1
log_warnings            = 2
slow_query_log_file     = /var/log/mysql/mariadb-slow.log
long_query_time = 10
#log_slow_rate_limit    = 1000
log_slow_verbosity      = query_plan

#log-queries-not-using-indexes
#log_slow_admin_statements

#server-id              = 1
#report_host            = master1
#auto_increment_increment = 2
#auto_increment_offset  = 1
log_bin                 = /var/log/mysql/mariadb-bin
log_bin_index           = /var/log/mysql/mariadb-bin.index
# not fab for performance, but safer
#sync_binlog            = 1
expire_logs_days        = 10
max_binlog_size         = 100M
# slaves
#relay_log              = /var/log/mysql/relay-bin
#relay_log_index        = /var/log/mysql/relay-bin.index
#relay_log_info_file    = /var/log/mysql/relay-bin.info
#log_slave_updates
#read_only

#sql_mode               = NO_ENGINE_SUBSTITUTION,TRADITIONAL
default_storage_engine  = InnoDB
innodb_log_file_size    = 32M
innodb_buffer_pool_size = 2G
innodb_log_buffer_size  = 8M
innodb_file_per_table   = 1
innodb_open_files       = 400
innodb_io_capacity      = 400
innodb_flush_method     = O_DIRECT

# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

[galera]
# Mandatory settings
#wsrep_on=ON
#wsrep_provider=
#wsrep_cluster_address=
#binlog_format=row
#default_storage_engine=InnoDB
#innodb_autoinc_lock_mode=2
#
# Allow server to accept connections on all interfaces.
#
#bind-address=0.0.0.0
#
# Optional setting
#wsrep_slave_threads=1
#innodb_flush_log_at_trx_commit=0

[mysqldump]
quick
quote-names
max_allowed_packet      = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completion

[isamchk]
key_buffer              = 16M

!includedir /etc/mysql/conf.d/
</code>```

free -m output

```<code>             total       used       free     shared    buffers     cached
Mem:         24102      21972       2129         65        441      12206
-/+ buffers/cache:       9324      14777
Swap:           87          0         87
</code>```

htop

答:
It sounds like the Query cache is not useful for you.  Turn it off (size and type = 0).  Do not change the size to 2G, that will significantly slow down the system due to pruning several times per second.  (Caveat:  If you are using Aurora, it is OK.)

Check the OS's file limit.  It seems to be 1024, which is putting a lid on table_open_cache, etc.  Change the OS limit, then increase the MySQL settings.

Some of the output says that you have poor indexes or queries, change long_query_time to 1, then look at the slowlog after awhile.

24GB of RAM, yet not much allocated to MySQL.  The innodb_buffer_pool_size is the most important tunable.  Wilson's advice is fine for now.

For more tuning advice, http://mysql.rjweb.org/doc.php/mysql_analysis#tuning .

ContentLicense: CC BY-SA 4.0

Body:
I'm a newbie and I just installed my first server, I am using MySQLTuner to optimize the MySQL database but I don't know what is the better way to tune according to MySQLTuner's output. How to tune my.cnf according to MySQLTuner output?

Here is the MySQLTuner output:

 >>  MySQLTuner 1.7.4 - Major Hayden <major@mhtx.net>
 >>  Bug reports, feature requests, and downloads at http://mysqltuner.com/
 >>  Run with '--help' for additional options and output filtering

[--] Skipped version check for MySQLTuner script
[OK] Logged in using credentials from debian maintenance account.
[OK] Currently running supported MySQL version 10.1.28-MariaDB-1~trusty
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: /var/lib/mysql/s118874.err(0B)
[!!] Log file /var/lib/mysql/s118874.err doesn't exist
[!!] Log file /var/lib/mysql/s118874.err isn't readable.

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE
[--] Data in MyISAM tables: 1G (Tables: 53)
[--] Data in InnoDB tables: 2G (Tables: 502)
[OK] Total fragmented tables: 0

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] There is no basic password file list!

-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 1d 13h 39m 11s (9M q [73.549 qps], 390K conn, TX: 13G, RX: 1G)
[--] Reads / Writes: 93% / 7%
[--] Binary logging is enabled (GTID MODE: OFF)
[--] Physical Memory     : 23.5G
[--] Max MySQL memory    : 4.1G
[--] Other process memory: 12.1G
[--] Total buffers: 2.6G global + 7.5M per thread (200 max threads)
[--] P_S Max memory usage: 98M
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 4.1G (17.61% of installed RAM)
[OK] Maximum possible memory usage: 4.1G (17.61% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/9M)
[!!] Highest connection usage: 100%  (200/200)
[OK] Aborted connections: 0.00%  (0/390176)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[OK] Query cache efficiency: 27.0% (2M cached / 9M selects)
[!!] Query cache prunes per day: 406250
[OK] Sorts requiring temporary tables: 0% (452 temp sorts / 1M sorts)
[OK] No joins without indexes
[!!] Temporary tables created on disk: 31% (505K on disk / 1M total)
[OK] Thread cache hit rate: 99% (346 created / 390K connections)
[!!] Table cache hit rate: 4% (400 open / 9K opened)
[OK] Open file limit used: 7% (77/1K)
[OK] Table locks acquired immediately: 99% (7M immediate / 7M locks)
[OK] Binlog cache memory access: 100.00% (501178 Memory / 501178 Total)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 98.8M
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 16 thread(s).
[--] Using default value is good enough for your version (10.1.28-MariaDB-1~trusty)

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 29.4% (39M used / 134M cache)
[OK] Key buffer size / total MyISAM indexes: 128.0M/150.6M
[OK] Read Key buffer hit rate: 100.0% (2B cached / 38K reads)
[OK] Write Key buffer hit rate: 99.3% (48K cached / 48K writes)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[!!] InnoDB buffer pool / data size: 2.0G/2.0G
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (3.125 %): 32.0M * 2/2.0G should be equal 25%
[!!] InnoDB buffer pool instances: 8
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[OK] InnoDB Read buffer efficiency: 100.00% (1820526478 hits/ 1820563369 total)
[!!] InnoDB Write Log efficiency: 5.26% (27496 hits/ 522990 total)
[OK] InnoDB log waits: 0.00% (0 waits / 550486 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is enabled.
[OK] Aria pagecache size / total Aria indexes: 128.0M/1B
[OK] Aria pagecache hit rate: 97.8% (22M cached / 478K reads)

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Reduce or eliminate persistent connections to reduce connection usage
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Increasing the query_cache size over 128M may reduce performance
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries which have no LIMIT clause
    Increase table_open_cache gradually to avoid file descriptor limits

    Beware that open_files_limit (1024) variable
    should be greater than table_open_cache (400)
    Consider installing Sys schema from https://github.com/mysql/mysql-sys

Variables to adjust:
    max_connections (> 200)
    wait_timeout (< 300)
    interactive_timeout (< 28800)
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_size (> 256M) [see warning above]
    tmp_table_size (> 64M)
    max_heap_table_size (> 64M)
    table_open_cache (> 400)
    innodb_buffer_pool_size (>= 2G) if possible.
    innodb_log_file_size should be (=256M) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
    innodb_buffer_pool_instances(=2)

My current setting on MySQL:

[client]
port            = 3306
socket          = /var/run/mysqld/mysqld.sock

[mysqld_safe]
socket          = /var/run/mysqld/mysqld.sock
nice            = 0

[mysqld]
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc_messages_dir = /usr/share/mysql
lc_messages     = en_US
skip-external-locking
bind-address            = 127.0.0.1

max_connections         = 200
connect_timeout         = 5
wait_timeout            = 300
max_allowed_packet      = 16M
thread_cache_size       = 128
sort_buffer_size        = 4M
bulk_insert_buffer_size = 16M
tmp_table_size          = 64M
max_heap_table_size     = 64M
performance_schema = ON

myisam_recover_options = BACKUP
key_buffer_size         = 128M
#open-files-limit       = 2000
table_open_cache        = 400
myisam_sort_buffer_size = 512M
concurrent_insert       = 2
read_buffer_size        = 2M
read_rnd_buffer_size    = 1M

query_cache_limit               = 2G
query_cache_size                = 256M
#query_cache_strip_comments =1
query_cache_type                = 1
log_warnings            = 2
slow_query_log_file     = /var/log/mysql/mariadb-slow.log
long_query_time = 10
#log_slow_rate_limit    = 1000
log_slow_verbosity      = query_plan

#log-queries-not-using-indexes
#log_slow_admin_statements

#server-id              = 1
#report_host            = master1
#auto_increment_increment = 2
#auto_increment_offset  = 1
log_bin                 = /var/log/mysql/mariadb-bin
log_bin_index           = /var/log/mysql/mariadb-bin.index
# not fab for performance, but safer
#sync_binlog            = 1
expire_logs_days        = 10
max_binlog_size         = 100M
# slaves
#relay_log              = /var/log/mysql/relay-bin
#relay_log_index        = /var/log/mysql/relay-bin.index
#relay_log_info_file    = /var/log/mysql/relay-bin.info
#log_slave_updates
#read_only

#sql_mode               = NO_ENGINE_SUBSTITUTION,TRADITIONAL
default_storage_engine  = InnoDB
innodb_log_file_size    = 32M
innodb_buffer_pool_size = 2G
innodb_log_buffer_size  = 8M
innodb_file_per_table   = 1
innodb_open_files       = 400
innodb_io_capacity      = 400
innodb_flush_method     = O_DIRECT

# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

[galera]
# Mandatory settings
#wsrep_on=ON
#wsrep_provider=
#wsrep_cluster_address=
#binlog_format=row
#default_storage_engine=InnoDB
#innodb_autoinc_lock_mode=2
#
# Allow server to accept connections on all interfaces.
#
#bind-address=0.0.0.0
#
# Optional setting
#wsrep_slave_threads=1
#innodb_flush_log_at_trx_commit=0

[mysqldump]
quick
quote-names
max_allowed_packet      = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completion

[isamchk]
key_buffer              = 16M

!includedir /etc/mysql/conf.d/

free -m output

             total       used       free     shared    buffers     cached
Mem:         24102      21972       2129         65        441      12206
-/+ buffers/cache:       9324      14777
Swap:           87          0         87

htop


问:
Bind Two Properties to DataGridTemplateColumn TextBox WPF MVVM
I want to bind two properties to my DataGridTemplateColumn that contains a TextBox.

I have a column called HST. In that column I want users to enter a formula and when focus is left, or the column is no longer in edit state, the value is displayed, similar behavior with MS excel.

I have two properties where I have the formula stored as well as where I have the value from the formula stored.

```<code> public String SubTotal
    {
        get
        {
            String[] l_ComputeArr = l_HST.Split('=');
            if (l_ComputeArr.Length > 1)
            {
                DataTable dt = new DataTable();
                try
                {
                    var v = dt.Compute(l_ComputeArr[1], "");
                    l_SubTotal = v.ToString();
                }
                catch
                {

                }

            }
            return l_SubTotal;
        }
        set
        {
            if (l_SubTotal != value)
            {
                l_SubTotal = value;
            }
            RaisePropertyChanged("SubTotal");
        }
    }
    public String HST
    {
        get { return l_HST; }
        set
        {
            if (l_HST != value)
            {
                l_HST = value;
            }
            RaisePropertyChanged("HST");
            RaisePropertyChanged("SubTotal");
        }
    }
</code>```

Subtotal has the value and HST has the formula

I want to make HST hidden and have similar behavior with MS Excel, where the formula is displayed when Subtotal is being edited and the value is displayed after the edit is complete

I have a class called observable object that my viewmodels Inherit from.

This class has a method RaisePropertyChanged, which updates the View Elements.

```<code> public abstract class ObservableObject: INotifyPropertyChanged
{

    [field: NonSerialized]
      public event PropertyChangedEventHandler PropertyChanged;

      protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
      {
         var handler = this.PropertyChanged;
         if (handler != null)
         {
              handler(this, e);
          }
      }

      protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpresssion)
      {
         var propertyName = PropertySupport.ExtractPropertyName(propertyExpresssion);
         this.RaisePropertyChanged(propertyName);
      }

      protected void RaisePropertyChanged(String propertyName)
       {
           VerifyPropertyName(propertyName);
           OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
       }

       /// <summary>
       /// Warns the developer if this Object does not have a public property with
       /// the specified name. This method does not exist in a Release build.
       /// </summary>
       [Conditional("DEBUG")]
       [DebuggerStepThrough]
       public void VerifyPropertyName(String propertyName)
       {
           // verify that the property name matches a real,
           // public, instance property on this Object.
           if (TypeDescriptor.GetProperties(this)[propertyName] == null)
          {
               Debug.Fail("Invalid property name: " + propertyName);
           }
       }
   }
</code>```

My question:

I want to have similar ms excel behavior on my datagrid.

By that I mean, I do not want to have a separate column displaying the formula from the column displaying the evaluation of the expression/formula

In ms excel a column displays the expression/formula when in edit state, and displays the value of that expression when in view state.

答:
```<code><DataGrid.Columns>
    <DataGridTemplateColumn>
        <!--
        Template used when cell is in editing state.
        HST appears to be your formula.
        -->
        <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <TextBox Text="{Binding HST}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellEditingTemplate>

        <!--
        Template used when cell is not in editing state.
        -->
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Subtotal}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>
</code>```

Body:
I want to bind two properties to my DataGridTemplateColumn that contains a TextBox.

I have a column called HST. In that column I want users to enter a formula and when focus is left, or the column is no longer in edit state, the value is displayed, similar behavior with MS excel.

I have two properties where I have the formula stored as well as where I have the value from the formula stored.

 public String SubTotal
    {
        get
        {
            String[] l_ComputeArr = l_HST.Split('=');
            if (l_ComputeArr.Length > 1)
            {
                DataTable dt = new DataTable();
                try
                {
                    var v = dt.Compute(l_ComputeArr[1], "");
                    l_SubTotal = v.ToString();
                }
                catch
                {

                }

            }
            return l_SubTotal;
        }
        set
        {
            if (l_SubTotal != value)
            {
                l_SubTotal = value;
            }
            RaisePropertyChanged("SubTotal");
        }
    }
    public String HST
    {
        get { return l_HST; }
        set
        {
            if (l_HST != value)
            {
                l_HST = value;
            }
            RaisePropertyChanged("HST");
            RaisePropertyChanged("SubTotal");
        }
    }

Subtotal has the value and HST has the formula

I want to make HST hidden and have similar behavior with MS Excel, where the formula is displayed when Subtotal is being edited and the value is displayed after the edit is complete

I have a class called observable object that my viewmodels Inherit from.

This class has a method RaisePropertyChanged, which updates the View Elements.

 public abstract class ObservableObject: INotifyPropertyChanged
{

    [field: NonSerialized]
      public event PropertyChangedEventHandler PropertyChanged;

      protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
      {
         var handler = this.PropertyChanged;
         if (handler != null)
         {
              handler(this, e);
          }
      }

      protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpresssion)
      {
         var propertyName = PropertySupport.ExtractPropertyName(propertyExpresssion);
         this.RaisePropertyChanged(propertyName);
      }

      protected void RaisePropertyChanged(String propertyName)
       {
           VerifyPropertyName(propertyName);
           OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
       }

       ///
       /// Warns the developer if this Object does not have a public property with
       /// the specified name. This method does not exist in a Release build.
       ///
       [Conditional("DEBUG")]
       [DebuggerStepThrough]
       public void VerifyPropertyName(String propertyName)
       {
           // verify that the property name matches a real,
           // public, instance property on this Object.
           if (TypeDescriptor.GetProperties(this)[propertyName] == null)
          {
               Debug.Fail("Invalid property name: " + propertyName);
           }
       }
   }

My question:

I want to have similar ms excel behavior on my datagrid.

By that I mean, I do not want to have a separate column displaying the formula from the column displaying the evaluation of the expression/formula

In ms excel a column displays the expression/formula when in edit state, and displays the value of that expression when in view state.


问:
Read text between specific tag of .XML file and display it in a .txt file using batch file
I have to know the Jenkins version which is only present in the 'config.xml' file, below are the contents of it:

```<code>< version > 1.652 < / version >
</code>```

(I have modified the syntax of the xml line so that it is visible as plane text)
I'm trying to pull the version number between the tags 1.652 and echo "1.652" to a .txt file.

I'm a beginner and really did not find a specific code online to do it.

答:
The simple solution that directly answers question is to put this PowerShell one-liner into your .bat script:

```<code>powershell "([xml](gc config.xml)).SelectSingleNode('//version/text()').data" >out.txt
</code>```

That will objectify your XML data, select the child text node of the first <version> tag, and output its value to out.txt.

I'm a little suspicious about your writing the version value to a .txt file, though, when it's already written in config.xml.  Is that necessary?  It sounds like you're about to employ some Rube Goldberg level of complexity to export the version data to a text file then redirect the value back into a variable.  If that's what you're planning, that's more complicated than it needs to be.  If you're comparing the version number against something, stay in PowerShell to perform the comparison.

Here's a native PowerShell .ps1 script example:

```<code>[version]$minimumVer = "1.652"
[version]$jenkinsVer = ([xml](gc config.xml)).SelectSingleNode('//version/text()').data

if ($minimumVer -gt $jenkinsVer) {
    "Fail.  Jenkins must be version $minimumVer or newer for this to work."
}
else {
    "Happiness and rainbows."
}
</code>```

Here's a PowerShell one(ish)-liner formatted for a .bat script.  It uses exit [boolean] to set %ERRORLEVEL% for conditional execution (the && and || stuff).

```<code>@echo off & setlocal

set "minVersion=1.652"

set "psCmd=powershell "exit ([version](([xml](gc config.xml)).SelectSingleNode(^
'//version/text()').data) -ge [version]'%minVersion%')""

%psCmd% && (
    echo Fail.  Jenkins must be version %minVersion% or newer for this to work.
) || (
    echo Happiness and rainbows.
)
</code>```

Body:
I have to know the Jenkins version which is only present in the 'config.xml' file, below are the contents of it:

< version > 1.652 < / version >

(I have modified the syntax of the xml line so that it is visible as plane text)
I'm trying to pull the version number between the tags 1.652 and echo "1.652" to a .txt file.

I'm a beginner and really did not find a specific code online to do it.

Body:
The simple solution that directly answers question is to put this PowerShell one-liner into your .bat script:

powershell "([xml](gc config.xml)).SelectSingleNode('//version/text()').data" >out.txt

That will objectify your XML data, select the child text node of the first <version> tag, and output its value to out.txt.

I'm a little suspicious about your writing the version value to a .txt file, though, when it's already written in config.xml.  Is that necessary?  It sounds like you're about to employ some Rube Goldberg level of complexity to export the version data to a text file then redirect the value back into a variable.  If that's what you're planning, that's more complicated than it needs to be.  If you're comparing the version number against something, stay in PowerShell to perform the comparison.

Here's a native PowerShell .ps1 script example:

[version]$minimumVer = "1.652"
[version]$jenkinsVer = ([xml](gc config.xml)).SelectSingleNode('//version/text()').data

if ($minimumVer -gt $jenkinsVer) {
    "Fail.  Jenkins must be version $minimumVer or newer for this to work."
}
else {
    "Happiness and rainbows."
}

Here's a PowerShell one(ish)-liner formatted for a .bat script.  It uses exit [boolean] to set %ERRORLEVEL% for conditional execution (the && and || stuff).

@echo off & setlocal

set "minVersion=1.652"

set "psCmd=powershell "exit ([version](([xml](gc config.xml)).SelectSingleNode(^
'//version/text()').data) -ge [version]'%minVersion%')""

%psCmd% && (
    echo Fail.  Jenkins must be version %minVersion% or newer for this to work.
) || (
    echo Happiness and rainbows.
)


问:
unexpected Identifier return for no forseeable reason
I'm not sure whats going on here I keep getting an unexpected identifier return on my first line of code but I can't tell whats going on is there something wrong with my code or is it my compiler?

```<code>private static final float IDEAL_FRAME_RATE = 100;

KeyInput currentKeyInput;
GameSystem system;
PFont smallFont, largeFont;
boolean paused;

void setup() {
  size(1360, 640, P2D);
  frameRate(IDEAL_FRAME_RATE);

  // Prepare font
  final String fontFilePath = "Lato-Regular.ttf";
  smallFont = createFont(fontFilePath, 20f, true);
  largeFont = createFont(fontFilePath, 96f, true);
  textFont(largeFont, 96f);
  textAlign(CENTER, CENTER);

  rectMode(CENTER);
  ellipseMode(CENTER);

  currentKeyInput = new KeyInput();

  newGame(true, true);  // demo play (computer vs computer), shows         instruction window
}

void draw() {
  if(keyIsDown(72))
    println("H");
  background(255f);
  background(random(255), random(255), random(255));
  system.run();
}

void newGame(boolean demo, boolean instruction) {
  system = new GameSystem(demo, instruction);
}

void mousePressed() {
  system.showsInstructionWindow = !system.showsInstructionWindow;
}
</code>```

There are six other classes that go with this one if there is nothing wrong with this one could it be due to another lass? If I need to link then I will gladly cause I'm stuck and really want to get this done

答:
Java doesn't have modules like VB does (at least last time I checked). So you're missing a class statement to wrap your code I guess.

```<code>public class SomeClass {
   //...
}
</code>```

See https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html

Body:
I'm not sure whats going on here I keep getting an unexpected identifier return on my first line of code but I can't tell whats going on is there something wrong with my code or is it my compiler?

private static final float IDEAL_FRAME_RATE = 100;

KeyInput currentKeyInput;
GameSystem system;
PFont smallFont, largeFont;
boolean paused;

void setup() {
  size(1360, 640, P2D);
  frameRate(IDEAL_FRAME_RATE);

  // Prepare font
  final String fontFilePath = "Lato-Regular.ttf";
  smallFont = createFont(fontFilePath, 20f, true);
  largeFont = createFont(fontFilePath, 96f, true);
  textFont(largeFont, 96f);
  textAlign(CENTER, CENTER);

  rectMode(CENTER);
  ellipseMode(CENTER);

  currentKeyInput = new KeyInput();

  newGame(true, true);  // demo play (computer vs computer), shows         instruction window
}

void draw() {
  if(keyIsDown(72))
    println("H");
  background(255f);
  background(random(255), random(255), random(255));
  system.run();
}

void newGame(boolean demo, boolean instruction) {
  system = new GameSystem(demo, instruction);
}

void mousePressed() {
  system.showsInstructionWindow = !system.showsInstructionWindow;
}

There are six other classes that go with this one if there is nothing wrong with this one could it be due to another lass? If I need to link then I will gladly cause I'm stuck and really want to get this done

Body:
Java doesn't have modules like VB does (at least last time I checked). So you're missing a class statement to wrap your code I guess.

public class SomeClass {
   //...
}

See https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html


问:
Eclipse "Permission denied" error when trying to launch app
I'm trying to get started creating some apps for Android but I keep running into this Eclipse error:

NAND: could not read
  file...android-sdk_r07-windows\android-sdk-windows/platforms\android-7\images/system.img,
  Permission denied.

Do you think I should delete the package and re-install? I'm wondering whether it could be a corrupted file, although it says "permission denied" which makes me think not so. I just installed the plugin for Eclipse and created my emulator but I can't run because of this error.

I have googled searched this and could not find a relevant answer. Any help would be greatly appreciated. :)

答:
The file seems to be locked or otherwise could not be read.

First you could try to run Eclipse as an Administrator (especially if you are running Windows 7, which has stricter file access than XP).

May I suggest that you download Process Explorer http://technet.microsoft.com/en-us/sysinternals/bb896653 and hit Control-F to search for system.img. Then you'll probably find which process is locking up your file. You can kill the handle in the bottom view of process explorer.

If all else fails you can reinstall Eclipse and/or ADT from scratch. Good luck!

ContentLicense: CC BY-SA 2.5


问:
Counting choice streaks in Python
I have a dataset that looks like the following:

```<code>Subject | Session | Trial | Choice
--------+---------+-------+-------
1       | 1       | 1     | A
1       | 1       | 2     | B
1       | 1       | 3     | B
1       | 1       | 4     | B
1       | 1       | 5     | B
1       | 1       | 6     | A
2       | 1       | 1     | A
2       | 1       | 2     | A
2       | 1       | 3     | A
</code>```

I would like to use a Python script to generate the following table:

```<code>Subject | Session | streak_count
--------+---------+-------------
1       | 1       | 3
2       | 1       | 1
</code>```

Where streak_count is a count of the total number of choice streaks made by a given subject during a given session, and a streak is any number of choices of one particular item in a row (>0).

I've tried using some of the suggestions to similar questions here, but I'm having trouble figuring out how to count these instances, rather than measure their length, etc., which seem to be more common queries.

答:
I think this is what you are asking for; </p>

```<code>import itertools

data = [
    [1, 1, 1, 'A'],
    [1, 1, 2, 'B'],
    [1, 1, 3, 'B'],
    [1, 1, 4, 'B'],
    [1, 1, 5, 'B'],
    [1, 1, 6, 'A'],
    [2, 1, 1, 'A'],
    [2, 1, 2, 'A'],
    [2, 1, 3, 'A']
]

grouped = itertools.groupby(data, lambda x: x[0])

results = dict()
this, last = None, None
for key, group in grouped:
    results[key] = 0
    for c, d in enumerate(group):
        this = d
        streak = c == 0 or this[3] != last[3]]
        if streak:
            results[key] += 1
        last = this

print results
</code>```

<p>This yields; </p>

```<code>{1: 3, 2: 1}
</code>```

Title: Counting choice streaks in Python

Body:
I have a dataset that looks like the following:

Subject | Session | Trial | Choice
--------+---------+-------+-------
1       | 1       | 1     | A
1       | 1       | 2     | B
1       | 1       | 3     | B
1       | 1       | 4     | B
1       | 1       | 5     | B
1       | 1       | 6     | A
2       | 1       | 1     | A
2       | 1       | 2     | A
2       | 1       | 3     | A

I would like to use a Python script to generate the following table:

Subject | Session | streak_count
--------+---------+-------------
1       | 1       | 3
2       | 1       | 1

Where streak_count is a count of the total number of choice streaks made by a given subject during a given session, and a streak is any number of choices of one particular item in a row (>0).

I've tried using some of the suggestions to similar questions here, but I'm having trouble figuring out how to count these instances, rather than measure their length, etc., which seem to be more common queries.

Body:
I think this is what you are asking for;

import itertools

data = [
    [1, 1, 1, 'A'],
    [1, 1, 2, 'B'],
    [1, 1, 3, 'B'],
    [1, 1, 4, 'B'],
    [1, 1, 5, 'B'],
    [1, 1, 6, 'A'],
    [2, 1, 1, 'A'],
    [2, 1, 2, 'A'],
    [2, 1, 3, 'A']
]

grouped = itertools.groupby(data, lambda x: x[0])

results = dict()
this, last = None, None
for key, group in grouped:
    results[key] = 0
    for c, d in enumerate(group):
        this = d
        streak = c == 0 or this[3] != last[3]]
        if streak:
            results[key] += 1
        last = this

print results

This yields;

{1: 3, 2: 1}


问:
Swift 4 : Set Different Date and Time
I know how to get local date and time, but what I want to do is getting the date and time from different places. For example, I want to find out what the time and date is in New York. How can i solve this simple problem?

Here is my code for local date and time :

```<code>let date = NSDate()
let calendar = Calendar.current

let components = calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date as Date)

let currentDate = calendar.date(from: components)
</code>```

I searched about it here, but i didn't find what i want and I'm still looking for the date libaries. If you know any source or sample to redirect me, I really appreciate that.

答:
If you just want to format the date to a string, consider using a DateFormatter instead:

```<code>let date = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "America/New_York")
formatter.dateStyle = .long
formatter.timeStyle = .long
formatter.string(from: date)
</code>```

If you want to get the date components and process them, use the dateComponents(in:from:) method.

```<code>let components = Calendar.current.dateComponents(in: TimeZone(identifier: "America/New_York")!, from: date)
</code>```

Title: Swift 4 : Set Different Date and Time

Body:
I know how to get local date and time, but what I want to do is getting the date and time from different places. For example, I want to find out what the time and date is in New York. How can i solve this simple problem?

Here is my code for local date and time :

let date = NSDate()
let calendar = Calendar.current

let components = calendar.dateComponents([.hour, .minute, .month, .year, .day, .second, .weekOfMonth], from: date as Date)

let currentDate = calendar.date(from: components)

I searched about it here, but i didn't find what i want and I'm still looking for the date libaries. If you know any source or sample to redirect me, I really appreciate that.

Body:
If you just want to format the date to a string, consider using a DateFormatter instead:

let date = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "America/New_York")
formatter.dateStyle = .long
formatter.timeStyle = .long
formatter.string(from: date)

If you want to get the date components and process them, use the dateComponents(in:from:) method.

let components = Calendar.current.dateComponents(in: TimeZone(identifier: "America/New_York")!, from: date)


问:
Conversion failed when converting varchar value to data type int in SQL
I am having some difficulty getting the difference between two time values in SQL. I want to select all the values that have less than 5 seconds difference between the start and stop of the date value.

My data looks like this

```<code>Stop
-----------------------
2017-10-04 16:32:06:000

Start
-----------------------
2017-10-04 16:32:02:000
</code>```

The above scenario would be one of those calls. My code in the where clause to obtain only values in the data that are less than 5 seconds:

```<code>  datediff(second, cast(stop as int), cast(start as int)) < 5
</code>```

I also tried just datediff without the cast as int and still received the same error:

Conversion failed when converting the varchar vlue '2017-10-04 20:58:46:000' to data type int

答:
Instead of using datediff() add seconds to the start time:

```<code>where stop < dateadd(second, 5, start)
</code>```

You should be storing the date/times as date/time types, not as strings.  However, you at least have a standard format, so you can be explicit about the type casts if you like:

```<code>where convert(datetime, stop) < dateadd(second, 5, convert(datetime, start))
</code>```

This is actually  more accurate, because datediff() counts "time boundaries" between two values, not actual seconds.

The main thing with datediff(), though, is that the arguments are not integers.  So you could do:

```<code>datediff(second, start, stop) < 5
</code>```

But the first method is better.

Body:
I am having some difficulty getting the difference between two time values in SQL. I want to select all the values that have less than 5 seconds difference between the start and stop of the date value.

My data looks like this

Stop
-----------------------
2017-10-04 16:32:06:000

Start
-----------------------
2017-10-04 16:32:02:000

The above scenario would be one of those calls. My code in the where clause to obtain only values in the data that are less than 5 seconds:

  datediff(second, cast(stop as int), cast(start as int)) < 5

I also tried just datediff without the cast as int and still received the same error:

Conversion failed when converting the varchar vlue '2017-10-04 20:58:46:000' to data type int

Body:
Instead of using datediff() add seconds to the start time:

where stop < dateadd(second, 5, start)

You should be storing the date/times as date/time types, not as strings.  However, you at least have a standard format, so you can be explicit about the type casts if you like:

where convert(datetime, stop) < dateadd(second, 5, convert(datetime, start))

This is actually  more accurate, because datediff() counts "time boundaries" between two values, not actual seconds.

The main thing with datediff(), though, is that the arguments are not integers.  So you could do:

datediff(second, start, stop) < 5

But the first method is better.


问:
How to write square brackets in markdown
I need to write in my gitlab project wiki page a code block that contains square brackets. Unfortunately the square brackets are turn into a link.
I assume gitlab is using markdown language or the gfm flavor.

This is my code:

```<code>```javascript
"{bla, """", [[foo],[]]}"
```
</code>```

The foo],[ part is turn into a link. So basicaly I need a way to write a square brackets tah are not treated as a link. Surprisingly google doesn't provide any answer for such a trivial issue.

答:
The current answer is that you can't do this.  It is a know bug in GitLab, specifically in Wiki pages.  GitLab markdown correctly handles square brackets in comments, and code blocks entered in issues, but NOT in wiki pages.

Please add your vote (thumbs up) on the issue to try and get it resolved:

https://gitlab.com/gitlab-org/gitlab-ce/issues/18725

Your (not very appealing) options boil down to these:

Use a single line code entry `"{bla, """", [[foo],[]]}"`

Use another syntax in your code block (e.g. {{), and include a note outside the code block saying to replace {{ with [[, etc - Note that you can use double brackets inside single quote blocks in GitLab Markdown.

Use a screenshot of your code.

None of these are very nice solutions, but all you have at the moment.

Body:
I need to write in my gitlab project wiki page a code block that contains square brackets. Unfortunately the square brackets are turn into a link.
I assume gitlab is using markdown language or the gfm flavor.

This is my code:

```javascript
"{bla, """", [[foo],[]]}"
```

The foo],[ part is turn into a link. So basicaly I need a way to write a square brackets tah are not treated as a link. Surprisingly google doesn't provide any answer for such a trivial issue.


问:
Why does '&SAMLRequest' get appended to my ADFS entrypoint URL?
I am using adfs IDP and saml for sso using passport-saml.

My entry point is as follows:

```<code>https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https://<domain-name>/saml/metadata
</code>```

When I give this URL, the adfs sso login page loads fine, but when I run the application, &SAMLRequest gets appended with this URL:

```<code>https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https%3A%2F%2F<domain-name>%2Fsaml%2Fmetadata&SAMLRequest=nVNBbtswEPyKwLskS0lQh7BsODaKGkhbw1Z76CVgyJVDgCJV7ipxfl9KtgIfGh18IrA7HM7OLGeLY22iV%2FConS1YlkzYYj5DUZuGL1t6sTv42wJSFGAWed8oWOstdwI1citqQE6S75ffH3meTHjjHTnpDIs264I93cL09uY5z%2FPptMrvIBdimrHo9%2FBguBGAiC1sLJKwFEqT7EucZXGWl%2FmE5xm%2FuUvus%2Fs%2FLNqeqR%2B0VdoexnU8n0DIv5XlNt7%2B3JcsWiKCp%2FDwyllsa%2FB78K9awq%2FdY8FeiBrkaao7IdK4VlXaACbS1SxaBw%2B0FdSLHkGmQlWYGkw3qtlYTVoQqL0%2BWGcTgc1xYdxB29LtmmKMpfM5rYGEEiTYKRDe2%2BQvkhg3QAzDsrlxUpgYjo0HxBgsaXqPtZqlF7xD6j8C0Wa9dUbL92tS%2F%2Bp8LehzdJZkfUWruOqhHGqhzVKpTlzIyBj3tvIQjCsY%2BRZYOkg77yKofjNDhgTHqzZz5epGeI1dmHAUkgaLL4lXJji4g%2Boaw0dhksuOOpS34XhzXnWLDTIMVnphsXGeztH8T8%2F81PvEjo%2Fu5e%2Bd%2FwM%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsig%23rsa-sha1&Signature=EdEYkblB2aOEWvoeMtmWVOkeePocMAeRu2gGBRWrjyQvx%2BEP8eekHSb4IQwodJIui%2BXw%2F%2B0ziKD%2FmwFgaIlFhmWa3ZXpiluzhG8OjK2CaH1trnXNrZM3L%2FYANlXwVl2Z4WF4GF8EP7tmIci8XxFrdP%2Fz3EZ2rlCRdELJV%2FK9wNUUiMFF6FLdExcvZieb5ug15I9wynZndhzAZL46f3cjPvMpsJ9oekR8OKIejXmYOevW0OMq%2BbGGipHKE6B1WwTSaPWGrhdEYPSTHvKpmWrz%2F%2FDscCdF9zLqv%2FGY7TgMhTg9FtlfeQ2jnqeaABBilgYaF4B5zLfCGKk5BmxqwzazGg%3D%3D
</code>```

The & symbol causes the page to  load with an error, but when I replace this symbol with any other symbol, the page loads fine. Why is that, and how can I fix it?

答:
loginToRp is supposed to be the name of the application but you have set it to metadata?

The point is to avoid asking the user to pick an application because you have already specified it.

Body:
I am using adfs IDP and saml for sso using passport-saml.

My entry point is as follows:

https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https://<domain-name>/saml/metadata

When I give this URL, the adfs sso login page loads fine, but when I run the application, &SAMLRequest gets appended with this URL:

https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https%3A%2F%2F<domain-name>%2Fsaml%2Fmetadata&SAMLRequest=nVNBbtswEPyKwLskS0lQh7BsODaKGkhbw1Z76CVgyJVDgCJV7ipxfl9KtgIfGh18IrA7HM7OLGeLY22iV%2FConS1YlkzYYj5DUZuGL1t6sTv42wJSFGAWed8oWOstdwI1citqQE6S75ffH3meTHjjHTnpDIs264I93cL09uY5z%2FPptMrvIBdimrHo9%2FBguBGAiC1sLJKwFEqT7EucZXGWl%2FmE5xm%2FuUvus%2Fs%2FLNqeqR%2B0VdoexnU8n0DIv5XlNt7%2B3JcsWiKCp%2FDwyllsa%2FB78K9awq%2FdY8FeiBrkaao7IdK4VlXaACbS1SxaBw%2B0FdSLHkGmQlWYGkw3qtlYTVoQqL0%2BWGcTgc1xYdxB29LtmmKMpfM5rYGEEiTYKRDe2%2BQvkhg3QAzDsrlxUpgYjo0HxBgsaXqPtZqlF7xD6j8C0Wa9dUbL92tS%2F%2Bp8LehzdJZkfUWruOqhHGqhzVKpTlzIyBj3tvIQjCsY%2BRZYOkg77yKofjNDhgTHqzZz5epGeI1dmHAUkgaLL4lXJji4g%2Boaw0dhksuOOpS34XhzXnWLDTIMVnphsXGeztH8T8%2F81PvEjo%2Fu5e%2Bd%2FwM%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsig%23rsa-sha1&Signature=EdEYkblB2aOEWvoeMtmWVOkeePocMAeRu2gGBRWrjyQvx%2BEP8eekHSb4IQwodJIui%2BXw%2F%2B0ziKD%2FmwFgaIlFhmWa3ZXpiluzhG8OjK2CaH1trnXNrZM3L%2FYANlXwVl2Z4WF4GF8EP7tmIci8XxFrdP%2Fz3EZ2rlCRdELJV%2FK9wNUUiMFF6FLdExcvZieb5ug15I9wynZndhzAZL46f3cjPvMpsJ9oekR8OKIejXmYOevW0OMq%2BbGGipHKE6B1WwTSaPWGrhdEYPSTHvKpmWrz%2F%2FDscCdF9zLqv%2FGY7TgMhTg9FtlfeQ2jnqeaABBilgYaF4B5zLfCGKk5BmxqwzazGg%3D%3D

The & symbol causes the page to  load with an error, but when I replace this symbol with any other symbol, the page loads fine. Why is that, and how can I fix it?


问:
Trying to pull a value out of a kendo popup window using Excel VBA
I'm trying to pull a value out of a kendo popup window but can't seem to get the right combo/syntax.
Im looking for 9070009 in the "dipatchIdentLablel"

I have tried:

```<code>.Document.getElementById("AddSucessWindow").Value  'I know, too broad, too many possibilities
.Document.getElementById("AddSucessWindow").Text
.Document.getElementById("AddSucessWindow").getElementById("dispatchIdentLablel").Value
.Document.getElementById("AddSucessWindow").getElementById("dispatchIdentLablel").Text
.Document.getElementById("dispachIdentLablel").Value
.Document.getElementById("dispachIdentLablel").Text
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").Value
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").Text
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").innerText
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").HTML
.Document.getElementById("AddSucessWindow").getElementsByTagName("span").Value
.Document.getElementById("AddSucessWindow").getElementsByTagName("span").Text
</code>```

No errors on any, but the result is"empty" on all

Here is a portion of the web page code. I've removed a bunch of unneccessary stuff for ease of reading.

```<code><div tabindex="0" class="k-window-content k-content" id="AddSucessWindow" role="dialog" aria-labelledby="AddSucessWindow_wnd_title" data-role="window">
  <div>
    <table>
        <tbody>
            <tr>
                <td class="columnLabel">
                    <label for="Dispatch_Load_Id:">Dispatch Load Id:</label>
                </td>
                <td class="columnData">
                <span id="dispatchIdentLablel" name="dispatchIdentLablel"></span>
                 9070009        '<<--Shows as element  (text)
                </td>
           </tr>
    </table>
</div>
<div class="divCenter">
    <button Type="Button" id="AddSucessWindowClose">Close</button><script>
jQuery(function(){jQuery("#AddSucessWindowClose").kendoButton({});});
</script>
</div>
</code>```

I can get the button to close the window using this

```<code>.Document.getElementById("AddSucessWindowClose").Click
</code>```

I know I'm overlooking something or have the syntax wrong. Any insight appreciated !!

答:
You should be able to use querySelector() looking for the columnData class:

```<code>.Document.querySelector(".columnData").innerText
</code>```

Note that this worked for me when testing with just the HTML in the OP. If there are other elements with the same class on the page, may have to tweak it.

Body:
I'm trying to pull a value out of a kendo popup window but can't seem to get the right combo/syntax.
Im looking for 9070009 in the "dipatchIdentLablel"

I have tried:

.Document.getElementById("AddSucessWindow").Value  'I know, too broad, too many possibilities
.Document.getElementById("AddSucessWindow").Text
.Document.getElementById("AddSucessWindow").getElementById("dispatchIdentLablel").Value
.Document.getElementById("AddSucessWindow").getElementById("dispatchIdentLablel").Text
.Document.getElementById("dispachIdentLablel").Value
.Document.getElementById("dispachIdentLablel").Text
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").Value
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").Text
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").innerText
.Document.getElementById("dispachIdentLablel").getElementsByName("dispatchIdentLablel").HTML
.Document.getElementById("AddSucessWindow").getElementsByTagName("span").Value
.Document.getElementById("AddSucessWindow").getElementsByTagName("span").Text

No errors on any, but the result is"empty" on all

Here is a portion of the web page code. I've removed a bunch of unneccessary stuff for ease of reading.

                    Dispatch Load Id:

                 9070009        '<<--Shows as element  (text)

    <button Type="Button" id="AddSucessWindowClose">Close</button>

I can get the button to close the window using this

.Document.getElementById("AddSucessWindowClose").Click

I know I'm overlooking something or have the syntax wrong. Any insight appreciated !!

Body:
You should be able to use querySelector() looking for the columnData class:

.Document.querySelector(".columnData").innerText

Note that this worked for me when testing with just the HTML in the OP. If there are other elements with the same class on the page, may have to tweak it.


问:
Express-Validator: Validation Error Message not Appearing for custom validator
If I try to register a duplicate user Name, it all works, except for the error message saying it has already been registered.  All the other error messages work; just not this one.

```<code>router.post('/register', function(req, res){
var name = req.body.name;
var email = req.body.email;
// var username = req.body.username;
var username = req.body.name;
var password = req.body.password;
var password2 = req.body.password2;

req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('name', 'This name is already registered.')
.custom(function(name, req){
    return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
            console.log(name);
            console.log(user);
            if (err) throw err;
            if(user == null) {
                resolve();
            } else {
                console.log('rejecting');
                reject();
            }
        });
    });
});

req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
// req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

var errors = req.validationErrors();

if(errors){
    res.render('register',{
        errors:errors
    });
} else {
    var newUser = new User({
        name: name,
</code>```

What am I missing?

答:
I am quite sure the way you chain custom() in your code is for the new API only. You are otherwise using the legacy API. For the legacy API you have to define the custom validators when you apply the middleware (in app.js or something similar). For example:

```<code>app.use(expressValidator({
  customValidators: {
    isUniqueName: function(name) {
      return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
          console.log(name);
          console.log(user);
          if (err) throw err;
          if (user == null) {
            resolve();
          } else {
            console.log('rejecting');
            reject();
          }
        });
      });
    },
  },
}));
</code>```

and in the controller:

```<code>req.checkBody('name', 'This name is already registered.').isUniqueName();
</code>```

I would generally recommend changing to the new API. It shouldn't take too much time when you already know what you want to validate. It's written more about that here.

Body:
If I try to register a duplicate user Name, it all works, except for the error message saying it has already been registered.  All the other error messages work; just not this one.

router.post('/register', function(req, res){
var name = req.body.name;
var email = req.body.email;
// var username = req.body.username;
var username = req.body.name;
var password = req.body.password;
var password2 = req.body.password2;

req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('name', 'This name is already registered.')
.custom(function(name, req){
    return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
            console.log(name);
            console.log(user);
            if (err) throw err;
            if(user == null) {
                resolve();
            } else {
                console.log('rejecting');
                reject();
            }
        });
    });
});

req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
// req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

var errors = req.validationErrors();

if(errors){
    res.render('register',{
        errors:errors
    });
} else {
    var newUser = new User({
        name: name,

What am I missing?

Body:
I am quite sure the way you chain custom() in your code is for the new API only. You are otherwise using the legacy API. For the legacy API you have to define the custom validators when you apply the middleware (in app.js or something similar). For example:

app.use(expressValidator({
  customValidators: {
    isUniqueName: function(name) {
      return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
          console.log(name);
          console.log(user);
          if (err) throw err;
          if (user == null) {
            resolve();
          } else {
            console.log('rejecting');
            reject();
          }
        });
      });
    },
  },
}));

and in the controller:

req.checkBody('name', 'This name is already registered.').isUniqueName();

I would generally recommend changing to the new API. It shouldn't take too much time when you already know what you want to validate. It's written more about that here.


问:
Sort Entry Set of String, Integer by more than one field
Have a Map<String, Integer> and trying to sort on value and length of String. I am trying to compare two different things in the statement so don't know if I need two different statements.  This is being used to compare digit root so the String length and then the digit root is the value and the value.

For example:

```<code>("103",4); (1+0+3 == 4)
("4",4); (4 ==4)
("11101",4); (1+1+1+0+1 == 4)
("5",5); (5 == 5 )
("1003",4); (1+0+0+3 == 4)
</code>```

But ("103",4) > ("4",4) because the length of "103" > "4", and ("11101",4) > ("103",4);, length "11101" > "103"

```<code>Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int length = o1.getKey().length().compareTo(o2.getKey().length());
if(length != 0) {
 return length;
}
return (o1.getValue()).compareTo(o2.getValue());
}
});
</code>```

Edit Answered to the above Question(Also, response given)

```<code> Map<String,Integer> unsortMap = new.
                        TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4); Map<String,

 Integer> result =unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)) )
   .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap
     (Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 System.println(result);
</code>```

答:
If you already have a map, and you want to order it, by lenght key, and by value then:

```<code>Map<String,Integer> unsortMap = new TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4);

Map<String, Integer> result = unsortMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length))

        ).sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.out.println(result);

out => {4=4, 103=4, 1003=4, 11101=4, 5=5}
</code>```

Body:
Have a Map<String, Integer> and trying to sort on value and length of String. I am trying to compare two different things in the statement so don't know if I need two different statements.  This is being used to compare digit root so the String length and then the digit root is the value and the value.

For example:

("103",4); (1+0+3 == 4)
("4",4); (4 ==4)
("11101",4); (1+1+1+0+1 == 4)
("5",5); (5 == 5 )
("1003",4); (1+0+0+3 == 4)

But ("103",4) > ("4",4) because the length of "103" > "4", and ("11101",4) > ("103",4);, length "11101" > "103"

Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int length = o1.getKey().length().compareTo(o2.getKey().length());
if(length != 0) {
 return length;
}
return (o1.getValue()).compareTo(o2.getValue());
}
});

Edit Answered to the above Question(Also, response given)

 Map<String,Integer> unsortMap = new.
                        TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4); Map<String,

 Integer> result =unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)) )
   .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap
     (Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 System.println(result);

Body:
If you already have a map, and you want to order it, by lenght key, and by value then:

Map<String,Integer> unsortMap = new TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4);

Map<String, Integer> result = unsortMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length))

        ).sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.out.println(result);

out => {4=4, 103=4, 1003=4, 11101=4, 5=5}


问:
Merge multiple variables in R
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))
</code>```

How can I merge them to just two columns? so the result is:

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))
</code>```

答:
The base transform will do this:

```<code>d <- transform(d,
               DV1 = rowSums(d[c("DV1_A", "DV1_B", "DV1_C")], na.rm=T),
               DV2 = rowSums(d[c("DV2_A", "DV2_B", "DV2_C")], na.rm=T)
          )
</code>```

Title: Merge multiple variables in R

Body:
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))

How can I merge them to just two columns? so the result is:

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))

Body:
The base transform will do this:

d <- transform(d,
               DV1 = rowSums(d[c("DV1_A", "DV1_B", "DV1_C")], na.rm=T),
               DV2 = rowSums(d[c("DV2_A", "DV2_B", "DV2_C")], na.rm=T)
          )


问:
Use RegExp in Awk
I have CSV file:

```<code><iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

```<code>44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

I have worked RegExp in Grep

```<code>$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda
</code>```

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

```<code>$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5
</code>```

Just Awk work fine:

```<code>$ awk -F "|" '{print $1"|"$2}' example.txt
<iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

答:
Try:

```<code>$ awk -F'<iframe src="https://localhost/get/|"></iframe>' '{print $2 $3}' file
44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

This works by setting the input field separator to be either iframe src="https://localhost/get/ or "> in which case the output you want is the second field followed by the third field.

Alternative Method Using Match

```<code>$ awk -F "|" 'match($1, /[[:xdigit:]]{20}/, a) {print a[0]"|"$2}' file
44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

Note that awk supports POSIX regular expressions.  That means that it recognizes character classes like [[:digit:]] or [[:alnum:]] but not necessarily \d or \w.  As a GNU-specific extension, gawk supports \w (but not \d).  For portability, stick to the POSIX classes as shown in man 7 regex.

Yet another method

Your regex [A-Za-z]*+\d++\w++ can be translated into awk as follows:

```<code>$ awk -F "|" 'match($1, /[[:alpha:]]*[[:digit:]]+[[:alnum:]]+/, a) {print a[0]"|"$2}' file
44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

Note that this method requires that the 20-character hex string contains at least one digit.

Title: Use RegExp in Awk

Body:
I have CSV file:

|name_1
|name_2
|name_3
|name_4
|name_5

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5

I have worked RegExp in Grep

$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5

Just Awk work fine:

$ awk -F "|" '{print $1"|"$2}' example.txt
|name_1
|name_2
|name_3
|name_4
|name_5

Body:
Try:

$ awk -F'<iframe src="https://localhost/get/|"></iframe>' '{print $2 $3}' file
44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5

This works by setting the input field separator to be either iframe src="https://localhost/get/ or "></iframe> in which case the output you want is the second field followed by the third field.

Alternative Method Using Match

$ awk -F "|" 'match($1, /[[:xdigit:]]{20}/, a) {print a[0]"|"$2}' file
44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5

Note that awk supports POSIX regular expressions.  That means that it recognizes character classes like [[:digit:]] or [[:alnum:]] but not necessarily \d or \w.  As a GNU-specific extension, gawk supports \w (but not \d).  For portability, stick to the POSIX classes as shown in man 7 regex.

Yet another method

Your regex [A-Za-z]*+\d++\w++ can be translated into awk as follows:

$ awk -F "|" 'match($1, /[[:alpha:]]*[[:digit:]]+[[:alnum:]]+/, a) {print a[0]"|"$2}' file
44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5

Note that this method requires that the 20-character hex string contains at least one digit.


问:
how to change the QR code color in Matlab?
Hi I'm using MatLab to generate my QR code, basically this toolbox basing on zxing library.

I need to change the color of the code into blue. I mean the black pattern part needs to be blue. I guess its just the setting, right? But I didn't find the right one to change. Do somebody know how to do it?

Thank you!

Example codes:

```<code>m='qq';
qr=qrcode_gen(m);
colormap(gray);
imagesc(qr);
axis image;
</code>```

答:
Just change this line setting the colormap you prefer:

```<code>colormap(gray);
</code>```

For example:

```<code>colormap(parula(5))
</code>```

Body:
Hi I'm using MatLab to generate my QR code, basically this toolbox basing on zxing library.

I need to change the color of the code into blue. I mean the black pattern part needs to be blue. I guess its just the setting, right? But I didn't find the right one to change. Do somebody know how to do it?

Thank you!

Example codes:

m='qq';
qr=qrcode_gen(m);
colormap(gray);
imagesc(qr);
axis image;

Body:
Just change this line setting the colormap you prefer:

colormap(gray);

For example:

colormap(parula(5))


问:
Graphing MIDI events in iOS using AudioKit
I want to create a graphical representation of a MIDI file. I am using AudioKit for my audio processing needs in my app.

I am loading the MIDI with an AKSequencer and using an AKMIDISampler to add a WAV file to the sequence.

Is there a way to do something like the view in GarageBand where you see the notes in a graphical representation using AudioKit?

The WAV part is not important for this. I jus want to be able to do draw the contents of the MIDI file.

Thanks!

答: It sounds like what you are asking for is what is referred to as a Piano Roll in a typical DAW (like GarageBand).  AudioKit does not currently provide a built-in Piano Roll.  However, as AudioKit is open source, it could certainly be contributed sometime in the future.</p>


问:
NGINX: set_by_lua doesn't work
I have NGINX running as a proxy service and want to set SSL key depending on the $ENV variable (in Docker Compose file).

I added to the nginx.conf:

```<code>env ENVKEY;
</code>```

And then in the config file:

```<code>server {

    resolver 10.0.0.4 valid=300s;
    resolver_timeout 60s;

    server_name  _;

    listen 443;

    ssl on;

#    perl_set $envkey 'sub { return $ENV{"ENVKEY"}; }';
    set_by_lua $envkey 'return os.getenv("ENVKEY")';

    ssl_certificate /etc/nginx/ssl/jm-website-$envkey.crt;
    ssl_certificate_key /etc/nginx/ssl/jm-website-$envkey.key;
</code>```

I also tried to use perl_set - but it can be used in the location only, but ssl_certificate - in the http or server blocks.

Using set_by_lua - I have an error:

nginx: [emerg] BIO_new_file("/etc/nginx/ssl/jm-website-$envkey.crt")
  failed (SSL: error:02001002:system library:fopen:No such file or
  directory:fopen('/etc/nginx/ssl/jm-website-$envkey.crt','r')
  error:2006D080:BIO routines:BIO_new_file:no such file)

Although variable present in the environment:

```<code>root@d0718b0a3361:/etc/nginx# echo $ENVKEY
dev
</code>```

What I'm doing wrong here?
Maybe there is better approach?

答:
I do know that this is an old thread. I'm posting this for posterity's sake.

I was having the same problem as you were/are.

What is happening is that there's an order to when the lua blocks gets executed. set_by_lua happens right after the certificate is validated.

What you could do is either render you nginx.conf using a render engine of your choice (e.g.: python jinja) or you could write your own ssl_certificate_by_lua_block that reads from an environment variable. Here is an exemple of an implementation using said block. You could also check how Kong does it.

Hope it helps :)

Title: NGINX: set_by_lua doesn't work

Body:
I have NGINX running as a proxy service and want to set SSL key depending on the $ENV variable (in Docker Compose file).

I added to the nginx.conf:

env ENVKEY;

And then in the config file:

server {

    resolver 10.0.0.4 valid=300s;
    resolver_timeout 60s;

    server_name  _;

    listen 443;

    ssl on;

#    perl_set $envkey 'sub { return $ENV{"ENVKEY"}; }';
    set_by_lua $envkey 'return os.getenv("ENVKEY")';

    ssl_certificate /etc/nginx/ssl/jm-website-$envkey.crt;
    ssl_certificate_key /etc/nginx/ssl/jm-website-$envkey.key;

I also tried to use perl_set - but it can be used in the location only, but ssl_certificate - in the http or server blocks.

Using set_by_lua - I have an error:

nginx: [emerg] BIO_new_file("/etc/nginx/ssl/jm-website-$envkey.crt")
  failed (SSL: error:02001002:system library:fopen:No such file or
  directory:fopen('/etc/nginx/ssl/jm-website-$envkey.crt','r')
  error:2006D080:BIO routines:BIO_new_file:no such file)

Although variable present in the environment:

root@d0718b0a3361:/etc/nginx# echo $ENVKEY
dev

What I'm doing wrong here?
Maybe there is better approach?


问:
kendo ui autocomplete - set data on load
I have a textbox for which I added kendoAutoComplete function. This is working fine. However, I wanted to set some value to this textbox upon the page load (I get the value from DB). With KendoAutoComplete, I am unable to set this.

I can either implement KendoAutoComplete or set datsource. Both of them work fine separately. Where as, if I include the code related to both - it doesnt work.  Below is the code.  Can you please throw me some inputs if you have come across this issue?

myController.js

```<code>$("#txtPartNumbers").kendoAutoComplete({
            dataSource: {
                serverFiltering: true,
                enforceMinLength: true,
                transport: {
                    read: {
                        url: ApiBaseUrl.val + 'inventoryLocation/getParts',
                        type: "get",
                        dataType: "json",
                        data: function () {
                            return { partNumber: $scope.autoCompleteText }
                        }
                    }
                },
            },
            change: function(e) {
                $scope.autoCompleteText = this.value();
            },
            filter: "startswith",
            //placeholder: "Select Inventory Parts..",
            minLength: 3,
            separator: ", "
        });
</code>```

cshtml

```<code><div class="sectionFloatLeft">
   <label>Part Number(s):</label><br />
   <input id="txtPartNumbers" type="text" ng-model="filterByPartNumbers" class="form-control filterTextArea" style="width: 300px;height:80px;" placeholder="Enter Part Numbers (Comma sepatared)" />
</div>
</code>```

I am setting "filterByPartNumbers" value in my controller

```<code>....
var data = getDataFromDB();
$scope.filterByPartNumbers = data.partNumbers;
...
</code>```

Appreciate you help.

答:
I was able to set the value as below:

```<code>$("#txtPartNumbers").data("kendoAutoComplete").value(data.partNumbers);
</code>```

Thanks!

Body:
I have a textbox for which I added kendoAutoComplete function. This is working fine. However, I wanted to set some value to this textbox upon the page load (I get the value from DB). With KendoAutoComplete, I am unable to set this.

I can either implement KendoAutoComplete or set datsource. Both of them work fine separately. Where as, if I include the code related to both - it doesnt work.  Below is the code.  Can you please throw me some inputs if you have come across this issue?

myController.js

$("#txtPartNumbers").kendoAutoComplete({
            dataSource: {
                serverFiltering: true,
                enforceMinLength: true,
                transport: {
                    read: {
                        url: ApiBaseUrl.val + 'inventoryLocation/getParts',
                        type: "get",
                        dataType: "json",
                        data: function () {
                            return { partNumber: $scope.autoCompleteText }
                        }
                    }
                },
            },
            change: function(e) {
                $scope.autoCompleteText = this.value();
            },
            filter: "startswith",
            //placeholder: "Select Inventory Parts..",
            minLength: 3,
            separator: ", "
        });

cshtml

   Part Number(s):

   <input id="txtPartNumbers" type="text" ng-model="filterByPartNumbers" class="form-control filterTextArea" style="width: 300px;height:80px;" placeholder="Enter Part Numbers (Comma sepatared)" />

I am setting "filterByPartNumbers" value in my controller

....
var data = getDataFromDB();
$scope.filterByPartNumbers = data.partNumbers;
...

Appreciate you help.

Body:
I was able to set the value as below:

$("#txtPartNumbers").data("kendoAutoComplete").value(data.partNumbers);

Thanks!


问:
How can I show the "Open with" file dialog?
Is there any simple way to open the "Open with" file dialog?</p>

答:
Some reverse-engineering with ProcExp revealed a rundll32.exe command line that worked.  Here's a sample program that uses it:

```<code>using System;
using System.Diagnostics;
using System.IO;

class Program {
    static void Main(string[] args) {
        ShowOpenWithDialog(@"c:\temp\test.txt");
    }
    public static void ShowOpenWithDialog(string path) {
        var args = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "shell32.dll");
        args += ",OpenAs_RunDLL " + path;
        Process.Start("rundll32.exe", args);
    }
}
</code>```

Tested on Win7, I cannot guess how well this will work on other versions of Windows.

Body:
Some reverse-engineering with ProcExp revealed a rundll32.exe command line that worked.  Here's a sample program that uses it:

using System;
using System.Diagnostics;
using System.IO;

class Program {
    static void Main(string[] args) {
        ShowOpenWithDialog(@"c:\temp\test.txt");
    }
    public static void ShowOpenWithDialog(string path) {
        var args = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "shell32.dll");
        args += ",OpenAs_RunDLL " + path;
        Process.Start("rundll32.exe", args);
    }
}

Tested on Win7, I cannot guess how well this will work on other versions of Windows.