Apache Keeps reverting to mpm_prefork (Apache 2.4.7 / Ubuntu 14.04.2)

Question: I have had this problem for over a year now whereby each time there is a security update to Ubuntu and I have to reboot the server, Apache 2.4 decides to start using the mpm_prefork worker despite the fact I have mpm_event set as the enabled module in /etc/apache2/mods-enabled.
I went as far as editing the mpm_prefork.conf file in /etc/apache2/mods-available and commenting out where it loads the module but after a reboot this morning apache just would not start at all because it was insisting on starting up using Prefork.
Here is my /etc/apache2/mods-enabled/ directory list
access_compat.load
actions.conf
actions.load
alias.conf
alias.load
auth_basic.load
authn_core.load
authn_file.load
authz_core.load
authz_host.load
authz_user.load
autoindex.conf
autoindex.load
deflate.conf
deflate.load
dir.conf
dir.load
env.load
evasive.conf
evasive.load
expires.load
fastcgi.conf
fastcgi.load
filter.load
headers.load
mime.conf
mime.load
mpm_event.conf
mpm_event.load
negotiation.conf
negotiation.load
pagespeed.conf
pagespeed.load
rewrite.load
setenvif.conf
setenvif.load
socache_shmcb.load
spamhaus.conf
spamhaus.load
ssl.conf
ssl.load
status.conf
status.load

I checked to see if it had been compiled into Apache by running apache2 -l and this was the output
Compiled in modules:
  core.c
  mod_so.c
  mod_watchdog.c
  http_core.c
  mod_log_config.c
  mod_logio.c
  mod_version.c
  mod_unixd.c

And finally the result of a2query -M is
sudo a2query -M
event

But if I reboot right now, Apache is dead on startup because it wants the mpm_prefork module which as I said I have disabled by commenting out in its .conf file to prevent it loading which was not a solution to my problem.
I honestly am stumped as to where Apache 2.4 is just deciding by itself to load the mpm_prefork all the time.
Here is also my apache2.conf file stripped down without the comments
# Global configuration
Mutex file:${APACHE_LOCK_DIR} default
PidFile ${APACHE_PID_FILE}
Timeout 40
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
HostNameLookups Off
ErrorLog ${APACHE_LOG_DIR}/apache-error.log
LogLevel warn
SetEnvIf Remote_Addr "127\.0\.0\.1" loopback
SetEnvIf Remote_Addr "::1" loopback
CustomLog ${APACHE_LOG_DIR}/apache-access.log combined env=!loopback

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf

<Directory />
    Options -Indexes +FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options -Indexes +FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/html/opcache/>
    Options -Indexes +FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

AccessFileName .htaccess

<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

LogFormat "%V %v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
LogFormat "%h %l %u %t \"%r\" %>s %O %b %D \"%{Referer}i\" \"%{User-Agent}i\"" custom

IncludeOptional conf-enabled/*.conf

IncludeOptional sites-enabled/*.conf

Comment: which mpm packages do you have installed? `dpkg -l | grep mpm` for installed and `aptitude search apache.*mpm` to see options. As far as I know, it only lets you even install one at a time (but my web server is still 12.04).
Comment: Hi Peter, thanks for the reply ....  dpkg -l | grep mpm gave the following output `ii  apache2-mpm-event                   2.4.7-1ubuntu4.9                     amd64        transitional event MPM package for apache2` and
`ii  apache2-mpm-prefork                 2.4.7-1ubuntu4.9                     amd64        transitional prefork MPM package for apache2'` ... so I guess it does indeed have two installed but chooses by itself to default to prefork
Answer: The problem looks to be that you have these installed as packages:
apache2-mpm-event 2.4.7-1ubuntu4.9 amd64 transitional event MPM package for apache2
apache2-mpm-prefork 2.4.7-1ubuntu4.9 amd64 transitional prefork MPM package for apache2

When you update, you are specifically telling the server to install the prefork version. If you have a proper install of Apache2 on Ubuntu 14.04, which would NOT have specified the MPM type, a dpkg -l | grep apache2 would include:
apache2 2.4.7-1ubuntu4.9 amd64 Apache HTTP Server

but would NOT show the two packages you have listed.
The proper Apache2 installation on Ubuntu 14.04 is simply:
sudo apt-get install apache2

without any specification of MPM. The basic Multi-Processing Modules are core features of Apache 2.4, and are included with the apache2 install.
You then set MPM as follows:
To determine which MPM is currently in use, run apache2ctl -V. You will see a line such as:
 Server MPM:     prefork

Assuming, for example, that you are running "prefork" (as in the above example apache2ctl -V result above) following the install, the switch to "event" is made with the following commands:
 sudo a2dismod mpm_prefork
 sudo a2enmod mpm_event
 sudo service apache2 restart

which will set up the correct symlink.
Once set up this way, under the correct install, updates WILL NOT change your settings.
NOTE: Your "edits" to *.conf files should be taking place in the /etc/apache2/mods-available directory, where they are protected from over writing during updates. The /etc/apache2/mods-enabled directory will just have symlinks back to /etc/apache2/mods-available.
Comment: Hi Colt, thanks very much for the reply.

My apache was installed as part of the Ubuntu setup and all I ever did was install mpm_event and the set that as my chosen mpm.

This probably explains why there are 2 mpm's showing.

I have done:
`sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo service apache2 restart`

so many times and when it so chooses it just switches back to using prefork. As I said normally after some system or security updates.
Comment: apache2ctl -V gives:

`Server version: Apache/2.4.7 (Ubuntu)
Server built:   Jan 14 2016 17:45:23
Server's Module Magic Number: 20120211:27
Server loaded:  APR 1.5.1-dev, APR-UTIL 1.5.3
Compiled using: APR 1.5.1-dev, APR-UTIL 1.5.3
Architecture:   64-bit
Server MPM:     event
  threaded:     yes (fixed thread count)
    forked:     yes (variable process count)`
Comment: Sorry to ask as I am new here but Is there any way I can reply on comments and correctly format my post? It's all messed up what I posted above in the last 2 comments.
Comment: Also to answer your **note:** yes I only make changes in the conf files in the  /etc/apache2/mods-available folder. Now next step do I uninstall / purge mpm_prefork as per this web page? [link](https://www.howtoinstall.co/en/ubuntu/trusty/apache2-mpm-prefork?action=remove)
Comment: Be careful, **`purge` will get rid of your `conf` files and probably also your web sites** if they are associated with the removed package. If you have a backup of all of this, and are able, you can however get rid of all of the `apache` install and start over with a good install. There is clearly something seriously wrong with your setup. An update should never change your configuration. **IN ANY CASE, backup your system/files before doing any of these!**
Comment: Thanks Colt, I have good backups but will take a fresh one before doing anything that might cause trouble. It's still strange because I have done no fiddling other than installing mpm_event myself quite early on, server is as stable as anything just this switching of mpm's from time to time that annoys me. I will report back tomorrow, need to tackle this one with a clear head. Thanks for your input.
Comment: Okay. Just to make sure I am being clear - if you had a proper Ubuntu intstall of `apche2` as above, _no_ additional install was needed to switch to `mpm_event`. Just the 3-line configuration change (also above) and then, of course, optimizing for `event`. To be sure, I made this exact switch some time ago on `Apache 2.4.7` running under `Ubuntu 14.04`.
Comment: Thanks Colt, I think I may have inadvertantly installed it following someone's guide or tutorial (you know what bad advice is out there). It seems now since yesterday after doing a2enmod and a2dismod again it has stuck. I will keep an eye on it and report back. Thanks for your input.
Comment: @MitchellK - is the problem solved?
Comment: yes it does actually appear to be solved now. There has been 3 sets of security updates over the past week and a couple of reboots I have done manually just to make sure Apache starts up and each time it seems to be starting up perfectly running mpm_event .... so for now I think this is resolved. _I think re-running **a2dismod mpm_prefork and a2enmod mpm_event** again finally made it stick properly_. Thanks for your help.
Answer: I had the same problem since ubuntu 14 LTS and still on Ubuntu 22 LTS.
And i do install apache correctly (with apt install apache2)
And i do disable/enable mod correctly (with a2dismod mpm_prefork & a2enmod mpm_event)
If the problem come back, check how you installed php (for exemple php8.0), did you use libapache2-mod-php8.0 (or apt install php) ? unless you disable the mod it will revert back to prefork :
a2dismod php8.0
Also, if you do your update manually, and read the text, you will have a line saying disabling mpm-event then enabling mpm-prefork which hinted me at this module.
If you want to use php and NOT prefork, you have to use php8.0-fpm


How do you add an incrementing primary key to an existing table?

Question: I'm working on the contributed Login History module which has an existing table that does not have a primary key. I'd like to add a primary key to the table, but am struggle with the db_add_field syntax for upgrades. The existing table is:
/**
 * Implements hook_schema().
 */
function login_history_schema() {
  $schema['login_history'] = array(
    'fields' => array(
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'uid of user.',
      ),
      'login' => array(
        'type' => 'int',
        'not null' => TRUE,
        'description' => "Timestamp for user's login.",
      ),
      'hostname' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
        'description' => "The user's host name.",
      ),
      'one_time' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'Indicates whether the login was from a one-time login link (e.g. password reset).',
      ),
      'user_agent' => array(
        'type' => 'varchar',
        'length' => 256,
        'not null' => TRUE,
        'default' => '',
        'description' => 'User agent (i.e. browser) of the device used during the login.',
      ),
    ),
    'indexes' => array(
      'login_history_uid' => array('uid'),
      'login_history_onetime' => array('one_time'),
      'login_history_uid_host' => array('uid', 'hostname'),
    ),
  );
  return $schema;
}

And what I think should work to add a primary key is a hook_update like this:
/**
 * Add device_id and login_id columns.
 */
function login_history_update_7106() {
  if (!db_field_exists('login_history', 'login_id')) {
    db_add_field(
      'login_history',
      'login_id',
      array(
        'description' => 'The primary identifier for a login.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      array('primary key' => array('login_id')));
  }
}

However, that results in this error:
SQLSTATE[42000]: Syntax error or access violation: 1171 All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead                                                                                [error]

I've tried:

Reading and re-reading the docs for db_add_field and db_change_field
Using db_add_field to add an empty int field and then using db_change_field to make it a serial primary key.
Using db_add_field without the 4th parameter that sets the new primary keys and then trying to use db_add_primary_key('login_history', array('login_id')) but that gives an error before the field is even added saying that auto_increment fields have to be part of a unique key.

I've grepped core and some contrib looking for instances of adding an auto increment primary key and can't find any for Drupal 7.
Answer: This actually seems to be an issue in Drupal Core where creating a serial field on an existing table is not possible in MySQL 5.7+ without first creating an int field and converting that to autoincrement (this issue does not show up in MySQL 5.6 and below). Please see https://www.drupal.org/node/2615496 for a patch that fixes this issue for new releases of MySQL. It might be worthwhile to update that patch to be rolled into 8.x so it will allow us to patch 7.x.
Answer: I believe the problem here is that db_add_field() doesn't insert any data in the new column unless you provide a 'default' or 'initial' key in the spec parameter. But those only take a single value, which is inappropriate for a serial column.
You'll have to accomplish this in a couple of steps: create a new integer field without an index, insert unique data in it (doesn't have to be strictly auto-incremented, but that looks nicer), and then use db_change_field() to make it serial (including the necessary index).
If that doesn't work for some reason, you can create the entire table anew with the auto-increment column, then copy the data to the new table so that it generates your primary key data automatically. Depending on how big {login_history} is, that might be something you do in a batch.
Comment: I agree with the second or third options as workarounds, but those both feel like more work than this should be. Especially reading the docblock above `db_add_field` about how the `$new_keys` should work. Thanks for the ideas!
Comment: I suppose the optimal solution is to get db_add_field() to create unique data for you when it adds a serial column. But with Drupal 8 out, I doubt this would get patched, especially when workarounds are possible.
Answer: This will add an auto increment PRIMARY field to your table with incremental values againt existin records.
/**
 * Add device_id and login_id columns.
 */
function login_history_update_7106() {
  db_query('ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT');
}

Comment: That theoretically works, but won't work across databases, so it doesn't seem like a good match for a contrib module.
Comment: You have to use the API functions DB_ADD_FIELD etc and not just a db_query
Answer: The previous answers already describe the reason for the issue - you are not allowed to add a serial field, because db_add_field cannot add the index at the same time.
The suggested patch is not likely to make it into core in the foreseeable future. That is why you need to add the field as int first, and then change it to serial and add the primary key.
Changing the empty int field into serial will automatically fill it with values, but they may not match the order you expect.
Filling the values may be challenging if you do not have proper unique keys to sort by. Using a temporal table for filling the values with the correct order is a neat trick.
Assuming that you have updated hook_schema() with the new serial field and primary key definition, here is a code snippet for D8:
use Drupal\Core\Database\Database;

/**
 * Add login_id serial column.
 */
function login_history_update_8106() {
  $db = Database::getConnection();
  $schema = $db->schema();
  $spec = login_history_schema();
  $table_definition = $spec['login_history'];

  if (!$schema->fieldExists('login_history', 'login_id')) {
    // Fill-in the auto-increment values in a temp table.
    $schema->createTable('login_history_tmp', $table_definition);
    $db->query("INSERT INTO {login_history_tmp} (<all fields here except for login_id>)
      SELECT <all fields here except for login_id>
        FROM {login_history}
        ORDER BY created");
    // Rename the temp table as primary.
    $schema->dropTable('login_history');
    $schema->renameTable('login_history_tmp', 'login_history');
  }
}


After Clustering, how can I evaluate which features had the biggest impact?

Question: I've just performed unsupervised clustering (using DBSCAN) on a dataset for which I have no expert knowledge on.
I'm interested in working out which features had the greatest impact on my clustering.
For instance, I'd like to know if there is a trend in the points labelled as noise.
Any good tips? (Im using Pandas+Numpy for analysis)
If it helps, my distance metric is Cosine.
Comment: I've been reading about the Silhouette coefficient which seems useful
Comment: The "biggest impact" features are those which differentiate the clusters most strongly. So, perform a series of ANOVA or such, and look at t-values or p-values (without interpreting it as "significance").
Comment: @oliw Silhouette only makes sense for k-means and thelike, because it assumes clusters to be convex and to have approximately the same size. It will fail on recognizing good DBSCAN results.
Answer: Consider an indirect evaluation of your features.

Train a (feature-selecting!) classificator like random forests on your cluster labels
Validate that the classificator works well for this data set, otherwise try other classificators, parameters etc.
Inspect the classificator for the most important features.

DBSCAN doesn't select features, and there is no obvious way to identify the features which have the most impact. However, random forests and decision trees can be used for this. So by training a classifier on the clusters, you can identify which features are most relevant for transferring the cluster structure to new objects.


When did Hashim Amla get out for a duck in ODI?

Question: I remember that Hashim Amla was leading the list of ODI batsmen, having played the most matches without a duck.
But now, he is not in the list, ie, he got out for a duck (I think it is his only duck in ODI history).
When did this happen?
Which bowler took his wicket?
Comment: He was also given out LBW about an hour ago in the practice match for Champion's Trophy, for a second ball duck, on the bowling of Junaid Khan.
Comment: @xylon97, quick update! but the question is about ODI which doesn't include warm-up matches
Answer: He was out for a duck in a match against Australia. He was out for first ball duck in that match(c & b Bollinger). It was played at St George's Park, Port Elizabeth on 23 October 2011. That was the second ODI of the series which SA won by 80 runs.
Here is the score card of that match.
Update:
He was once again out for first ball duck in this match. Mohammad Irfan took his wicket.
Answer: Hashim Amla, right handed batsman from South Africa, has been out for a duck (zero runs) quite a few times in this career, although less than very many batsmen. Here are the details..
In Test matches = 6 times (3 times vs India, 1 vs England, 1 vs Australia, 1 vs Pakistan).
In One Dayers = only once, vs Australia at Port Elizabeth on 23 Oct 2011.
In Twenty20s = only once, vs India at Colombo on 2 October 2012.
Answer: In an ODI match against Pakistan, bowled by M Irfan at 0 runs. This was the series where Afridi made 88 on 48 balls.
Comment: This doesn't seem to add anything to iDev's (updated) answer.


Route IPv6 over OpenVPN IPv4 Tunnel

Question: I have accomplished this once before but I cannot find the tutorial that I used or remember how I did it. I have a server that has an IPv6 block assigned to it. I want to create an OpenVPN tunnel from my home router (Running CentOS 6) to the remote server. I then want to assign local lan machines an ip out of that ipv6 block and route ipv6 over the OpenVPN tunnel. I know it is possible because I have done it in the past.  My remote ISP provided an entire /64 last time so I remember splitting it into a /112 and it worked perfectly. Can someone point me to a tutorial or documentation on how to set this up ?
Answer: This is an excerpt from my openvpn.conf, where my hosting provider assigned me 2a01:411:111:222::/64.
server-ipv6 2a01:411:111:222::/64
push tun-ipv6
ifconfig-ipv6 2a01:411:111:222::1 2a01:411:111:222::2
push "route-ipv6 2a01:411:111:222::/64"
push "route-ipv6 2000::/3"

It successfully assigns IPv6 upon client connection and everything seems to be working fine...
Comment: does it allow you to assign addresses to lan computers behind the openvpn connection tho ?

Route IPv6 over OpenVPN IPv4 Tunnel


Cloud9 Node js Express jade IDE: file structure

Question: In Cloud9 Express IDE example I see in folder/file routes/users.js - please tell me why this is in separate file -what is the intention of users.js as a distinct file? :
<code>/*

    GET users listing.
    */

exports.list = function(req, res){
res.send("respond with a resource");
};
</code>
Answer: ok Im trying to answer that one myself (feel free to chime in):
The basic Express set up folder  structure according to Expressjs.com looks like this:
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
<code>├── error.jade

├── index.jade

└── layout.jade
</code>
It is suggested and not obligatory. However for noobs like me this helpful website says:

If you are getting started with Express it is recommended that you use the structure from the generator.

Edited:
In the particular folder structure generated in Cloud9 Express the file /routes/users IS intrinsic to a typical Express-Jade setup.
Basic routing tutorial here answers what each of these files is doing


Serviço feito em Delphi "se matar" ou dar Stop

Question: Gostaria de saber qual comando utilizar para um serviço Windows "se matar".
Por se tratar de um serviço não tenho a opção Application.Terminate.

Preciso verificar uma certa data, e se passou dessa data, o serviço deve ser parado ou se matar.
Alguém pode me ajudar?
Comment: Experimente o comando `Halt`
Answer: Você pode usar o comando Halt tanto no VCL quanto no Process.
Caso o Halt não seja suficiente você ainda pode um outro comando o ExitProcess.
A forma de uso de ambos é:
Halt(x);
ou
ExitProcess(x);

Obs: Onde x é um código inteiro de retorno para o SO entender o motivo da finalização da Aplicação! Ou seja, é uma mensagem de saída! Não é Obrigatório ser informado valor para esse parâmetro!
Comment: OK, coloquei no fonte só não vou conseguir testar agora. Mas assim que eu testar eu volto aqui e comento ou aceito a resposta. Obrigado.
Comment: Tudo bem amigo, o comando correto para seu caso, e será bem melhor de usar será o `ExitProcess(0);` Em caso de Aplicação o `Halt` pode deixar resto da aplicação na memória não fechando completamente!
Comment: Júnior, o comando ExitProcess(0) foi o que eu precisava. Ele para o serviço. Muito obrigado!
Answer: Para matar o processo estando fora dele.
function StopProcess(ExeFileName: string) : Integer;
const
  PROCESS_TERMINATE = $0001;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
begin
  Result := 0;
  FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  while Integer(ContinueLoop) <> 0 do
  begin
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
      UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
      UpperCase(ExeFileName))) then
      Result := Integer(TerminateProcess(
                        OpenProcess(PROCESS_TERMINATE,
                                    BOOL(0),
                                    FProcessEntry32.th32ProcessID),
                                    0));
     ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  end;
  CloseHandle(FSnapshotHandle);
end;

E para mata-lo estando no process.
Application.Terminate;

Comment: Esse comando "Application.Terminate" eu uso quando o aplicativo é VCL.Forms, funciona, porém no serviço eu digito "Application." e não tem a opção "Terminate". Mas obrigado pela ajuda!
Answer: Veja essa:
uses WinSvc;

//
// start service
//
// return TRUE if successful
//
// sMachine:
//   machine name, ie: \SERVER
//   empty = local machine
//
// sService
//   service name, ie: Alerter
//
function ServiceStart(
  sMachine,
  sService : string ) : boolean;
var
  //
  // service control
  // manager handle
  schm,
  //
  // service handle
  schs   : SC_Handle;
  //
  // service status
  ss     : TServiceStatus;
  //
  // temp char pointer
  psTemp : PChar;
  //
  // check point
  dwChkP : DWord;
begin
  ss.dwCurrentState := -1;

  // connect to the service
  // control manager
  schm := OpenSCManager(
    PChar(sMachine),
    Nil,
    SC_MANAGER_CONNECT);

  // if successful...
  if(schm > 0)then
  begin
    // open a handle to
    // the specified service
    schs := OpenService(
      schm,
      PChar(sService),
      // we want to
      // start the service and
      SERVICE_START or
      // query service status
      SERVICE_QUERY_STATUS);

    // if successful...
    if(schs > 0)then
    begin
      psTemp := Nil;
      if(StartService(
           schs,
           0,
           psTemp))then
      begin
        // check status
        if(QueryServiceStatus(
             schs,
             ss))then
        begin
          while(SERVICE_RUNNING
            <> ss.dwCurrentState)do
          begin
            //
            // dwCheckPoint contains a
            // value that the service
            // increments periodically
            // to report its progress
            // during a lengthy
            // operation.
            //
            // save current value
            //
            dwChkP := ss.dwCheckPoint;

            //
            // wait a bit before
            // checking status again
            //
            // dwWaitHint is the
            // estimated amount of time
            // the calling program
            // should wait before calling
            // QueryServiceStatus() again
            //
            // idle events should be
            // handled here...
            //
            Sleep(ss.dwWaitHint);

            if(not QueryServiceStatus(
                 schs,
                 ss))then
            begin
              // couldn't check status
              // break from the loop
              break;
            end;

            if(ss.dwCheckPoint <
              dwChkP)then
            begin
              // QueryServiceStatus
              // didn't increment
              // dwCheckPoint as it
              // should have.
              // avoid an infinite
              // loop by breaking
              break;
            end;
          end;
        end;
      end;

      // close service handle
      CloseServiceHandle(schs);
    end;

    // close service control
    // manager handle
    CloseServiceHandle(schm);
  end;

  // return TRUE if
  // the service status is running
  Result :=
    SERVICE_RUNNING =
      ss.dwCurrentState;
end;

http://www.chami.com/tips/delphi/031598D.html


Drupal 8 upload and embed a video to WYSIWYG

Question: So what I am searching for is a module that gives us the exactly same functionality that we already have with the image tool in Drupal 8 in the WYSIWYG editor.
And that should be working with just uploaded videos.
I found that this module should be doing it for D7 - https://www.drupal.org/project/video
And also this module https://www.drupal.org/project/video_embed_field is doing it for D8, but only for videos from per say YouTube, Vimeo etc.
So please let me know if you found a way to add a similar to the image (see  attached screenshot) but for video

Cheers and thanks in advance!
Comment: You can achieve this with mix of media modules. Here are some resources you can look  http://flocondetoile.fr/blog/managing-media-drupal-8      http://www.annertech.com/blog/reusable-media-drupal-8-tutorial?utm_source=The+Weekly+Drop&utm_medium=email&utm_campaign=The_Weekly_Drop_Issue_245_06_23_2016
Comment: On top of that you may need `Embed` and `entity embed` modules
Answer: For simple solution Just get video_embed_field which includes module  Video Embed WYSIWYG Enable both of them. You will get options to configure your WYSIWYG here admin/config/content/formats/manage/full_html. Just add the Video button in toolbar and checked the option Video Embed WYSIWYG. I hope you get what you want.
Thanks


PHP does not send echo back

Question: Using API 23. Can't provide LogCat ( i don't have an emulator, i can only test by generating apk).
I've been trying these for all day and I am still stuck.
Android App > send some Strings to a php located in my localhost ( using xampp)> get back those strings and display in TextView.
MainActivity
public class MainActivity extends AppCompatActivity {

Button b1;
TextView t1;
EditText e1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    e1 = (EditText)findViewById(R.id.editText);
    t1 = (TextView)findViewById(R.id.textView);
     b1 = (Button) findViewById(R.id.button);
    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
            GetText();
            } catch (Exception ex) {
                t1.setText("url exception");
            }
        }
    });
}

public void GetText() throws UnsupportedEncodingException {

    String nombre = e1.getText().toString();
    new SignIn().execute(nombre);
}

public class SignIn extends AsyncTask {
    @Override
    protected String doInBackground(String... params) {
        String link="http://localhost:8012/kb_test/ejemplo.php";

        String code = params[0];
        StringBuilder sb = new StringBuilder();
        try {
            String data  = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(code, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();

            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            wr.write( data );
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader (conn.getInputStream()));

            String line = null;

            while((line = reader.readLine()) != null)
            {
                sb.append(line);
                break;
            }
            return sb.toString();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());
        }
        return sb.toString();
    }
    @Override
    protected void onPostExecute(String result){
        Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG);
    }
}

.xml
  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/editText" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:text="Name"
    android:ems="10"
    android:id="@+id/editText"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/textView"
    android:layout_below="@+id/button"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="141dp" />

.php
<?php

   $name   = urldecode($_POST['name']);
  /* $user   = urldecode($_POST['user']);
   $email  = urldecode($_POST['email']);
   $pass   = urldecode($_POST['pass']);*/

  echo 'Name '. $name /*'Email: '.$email' User'. $user ' Pass  :'. $pass*/;

?>
** I am aware that i have to enter my  actuall IP in Localhost.
** Internet permission added.
Thanks to anyone that takes the time to help.
Comment: Please remove `Solved` from your title and post the solution you found as a proper answer.
Comment: local host is the android device which I'm guessing isn't where your server is located?
Comment: Maybe http://stackoverflow.com/a/5806384/1240523?
Comment: Why are you urldecoding the value in the $_POST? DId you have an additional urlencode on the content? http://stackoverflow.com/questions/35516824/does-php-automatically-do-urldecode-on-post
Comment: I got and urlencode just before i send the data on the java
Comment: I've rollback your replacement of the question by a solution. Please find your solution in the revision history and post it as an answer of its own.
Answer: You have an error in your PHP code, it should be:
<?php
    $name = urldecode($_GET['name']);
    $user = urldecode($_GET['user']);
    $email = urldecode($_GET['email']);
    $pass = urldecode($_GET['pass']);
    echo 'Name ' . $name . 'Email: ' . $email . ' User' . $user . ' Pass  :' . $pass;

You are missing . between each of the string concatenations.
If this still does not help, please prepend:
error_reporting(E_ALL) and let us know what is the error when you are trying to reach the script on your webserver.
Comment: Notice: Undefined index: name in C:\xampp\htdocs\kb_test\ejemplo.php on line 3

Notice: Undefined index: user in C:\xampp\htdocs\kb_test\ejemplo.php on line 4

Notice: Undefined index: email in C:\xampp\htdocs\kb_test\ejemplo.php on line 5

Notice: Undefined index: pass in C:\xampp\htdocs\kb_test\ejemplo.php on line 6
Comment: Seems like you are using get method to pass the params. Instead `$_POST` use `$_GET` and all should be good. I updated code for you. Check my answer once again.
Comment: Wel you are only sending the name parameter. No wonder that the script complains about missing user,  email and pass. Use the isset() function before you use a parameter. Check if it exists.
Comment: If you notice the rest of the parameters are between "/*" to make the tests easier. The isset you're suggesting has been tried before, but it wasn't the error source. It is like it connects with the php but the parameter it sends it's empty , because teh echo back its just the echo tag.
Answer: Nonsense that you have no LogCat. Of course there is one if you have connected your device to your pc.
You cannot call getText() in an onClick() handler. As all network code has to be done in an AsyncTask or thread.
Thats why you have a NetworkOnMainThreadException now.
Comment: Thanks for the advice , i've already changed my code to match the correct ways of retrieving text from the GUI, but i still have the same problem. And no , i don't have a LogCat. I only can test the code by building and apk and then transferring to a real device.
Comment: What do you mean by transferring to a real device? Normally you would connect your device with an usb cable to your pc. And the IDE (Eclipse or Android Studio) would upload your app to the device. And let it run. And of course both IDEs have a LogCat where you can follow whats happening.
Comment: Correct ways of retrieving text from the gui? Where are you talking about? We spoke about the correct way to do internet connections. In a thread or AsyncTask. Now do you use one of them now?
Comment: Once again , i am telling you i don't have the device connected via adb. My pc does not support either emulators or debbuging with mobile. And yes, with the getText() i was retrieving  a label from the GUI in an incorrect place where later i would send it by the urlconnection

PHP does not send echo back


Is it possible to combine background RGB with URL?

Question: Is this possible? My code is:
.w-categories li:hover{
  background: rgba(0, 0, 0, 0.1);
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
}

But when I hover over the li , it removes the side background.
No hover

On hover

Background image: background: url(../images/w_icon_tag.png) no-repeat 5px 10px;
Comment: `background` replaces all background properties with whatever you specify (including `background-image`), so you need to be more specific, i.e. use `background-color`.
Comment: thanks bud, that's what I forgot !
Answer: Try using background-color: rgba(...); instead of background: rgba(...);.
Seems to work here: http://jsfiddle.net/MRSallee/D97n9/
Comment: thanks buddy. I just forgot to do the background-color for the hover.. Thanks again !
Answer: Yes it is possible to combine. See Ref
Check out this Demo
background:url(../images/w_icon_tag.png) no-repeat 5px 10px rgba(0, 0, 0, 0.1);


Custom permission always denying access?

Question: In my module:
function mymodule_menu() {
    $items['reports'] = array(
    'page callback' => 'reports',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content', 'hr functionality')
    );
    return $items;
}

function mymodule_permission() {
  return array(
    'hr functionality' => array(
      'title' => t('HR functionality'),
      'description' => t('Do things only HR are allowed to do.'),
    )
  );
}

I set HR to have "HR functionality" permissions. I logged in as a user with HR role, and I get access denied to my reports page. I tried clearing cache, etc. If I remove the "hr functionality" access argument it lets me in.
Even if I log in as admin, I get access denied.
What am I doing wrong here?
EDIT: The method I ended up writing per accepted answer:
function multiple_permission_callback() {
    global $user;
    $permissions = func_get_args();

    if (empty($permissions))
        return false;

    foreach ($permissions as $permission) {
      if (!user_access($permission, $user)) {
        return false;
      }
    }
    return true;
}

Comment: Nice solution :) One thing that might be worth mentioning...if the function is called with no arguments it will always return `TRUE`. That might not be the best security practice. It's an easy fix though, `if (empty($permissions)) { return FALSE; }` before the loop
Comment: Good suggestion. Added.
Answer: The default function for the access callback is user_access(), which has the following signature:
function user_access($string, $account = NULL)

This is the function that will receive your access arguments.
It only takes one permission string at a time, so the second string you're passing in is being used as the $account object. This will cause problems in the user_access() function and is probably why it's returning FALSE all the time.
If you want to test two permissions you could provide your own access callback:
function mymodule_menu() {
  $items['reports'] = array(
    'title' => 'Reports',
    'page callback' => 'reports',
    'type' => MENU_CALLBACK,
    'access callback' => 'mymodule_reports_access'
  );
  return $items;
}

// Potentially accept an account object to make the function more re-usable
function mymodule_reports_access($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }

  return user_access('access content', $account) && user_access('hr functionality', $account);
}

Comment: This not only answered my current question, but one I had last week. Thanks!


How to get the actual value of a field in Views?

Question: I'm using the Views module and Drupal 7 and want to add a class to all rows of my table that have a certain value for a certain field.
The field is a bit field and is included in my query. I have added a PHP field (a separate Views module that is installed) with the following code:
if ($row->field_kampioen || $row->field_spirit) {
    return 'views-table-highlight';
} else {
    return '';
}

This should allow me to set the row class to [php]. This works, but all rows get the css class. When I output this for debugging:
return $row->field_champion . ' ' . $row->field_spirit . ' ';

I see that the classes are all different numbers, and field_champion is equal to field_spirit. This makes me think I'm seeing the ID.
How can I get a TRUE of FALSE? So, how can I get the actual bit value of this field?
It would be nice if I could do this via the Views module only, but I've seen pages where hooks are used. Maybe I'll have to use that.
Comment: are you using drupal 6 or 7?
Comment: Sorry. Drupal 7. I updated my question.
Answer: I'm assuming you are using Drupal 6, since you mentioned about PHP filed.
below is the code to retrieve value from a field and where ['tid_1'] is the token for a field. I think this is similar for Drupal 7 too.
<?php
$static = $this->view->display_handler->get_handlers('field');

$b=$static['tid_1']->last_render; //$b contains the value of the field
$d=$static['tid_2']->last_render; //$d contains the value of the field
//use your logic
 ?>

Comment: Is it possible this method (`last_render`) no longer exists? I know I have an object of type `views_handler_field_field` because I tried using it as an array and got a error stating I couldn't use this type as an array. But `last_render` doesn't give me anything. [Other methods](https://api.drupal.org/api/views/modules!field!views_handler_field_field.inc/class/views_handler_field_field/7) I found give me nothing or the wrong value (for example `get_field` gives me the name of the field, i.e. 'field-spirit-value').
Comment: @Peter i will check this in d7 tommrow.


Can you "copy" a Gemalto hardware MFA device with a virtual app?

Question: We use the Gemalto MFA fob with AWS. It is a given that we know the fob's serial number that was provided to AWS; I presume that serial number constitutes the "secret key" and the TOTP algorithm generates time-based codes from that seed. I was curious whether that hardware device could be replicated by a virtual device in software using the same seed and TOTP algorithm. Do any apps or services exist to do so?
Comment: The serial number is not the key, the shared secret is split between the inside of the token (intended to be tamper-resistant), and the authentication server, loaded at the time you buy the tokens. There can be software based tokens which do the same thing, but if the system is any good you can't move from an existing hardware token to a software one. See https://stackoverflow.com/a/25249610/478656 for some discussion and links for problems RSA SecurID had with this.
Comment: Thanks. To activate the device, I only provided two pieces of information to Amazon:
1. The serial number.
2. Two successive hashes from the device.

At no time was any information from Amazon returned to the device during that activation.

Perhaps, as you say, the device was "pre-registered" with Amazon at the time of manufacture and by providing the serial number I was just enabling AWS to look up the actual shared secret that it had stashed somewhere.
Comment: I am not familiar with how Amazon uses them, but generally you get (for example) 200 keyfobs at a company, upload 200 sets data into the MFA server, then give the keyfobs to people, and let them identify to the server which one they got, so it can connect the right token secret to their user account (that could be you giving the serial number). The two token codes help it sync - the server keeps "the current" OTP it's expecting, and ~10-100 before/after, so you don't get locked out forever if you waste one. It then adjusts when it learns where in the stream you are.
Answer: No, this isn't possible -- it would be a substantial weakness in any such device if it were possible to extract its secret key.
However, if you simply switch to using a virtual device (app), when you set it up, you're provided the secret key used to initialize the device (as a string of characters or a QR code)... which you can use to initialize any number of virtual devices, and they will all display the same code at the same time, as long as their clocks are correct, because the times are anchored to the Unix epoch (not of necessity, but they are in this case).
The merits and risks of such a practice are out of the scope of this answer, but technically speaking, this works.
Comment: Thanks, I thought just a serial number would be rather weak. It hadn't occurred to be until now that the entire device might actually have been "pre-registered" with Amazon specifically to create the real shared secret, so that it can't really be used anywhere else.
Comment: Are you answering this with knowledge of the Amazon / Gemalto specifically? My experience of Gemalto SafeNet MobilePass(+) software tokens is that you can only initialize them once, and doing so on the app contacts the server and completes the provisioning process for that token, and I think that prevents the use of more than one virtual device. (If you could use more than one, wouldn't that mean many people could get away with paying only a single license?). I'd be interested to be wrong, though.
Comment: Not Gemalto but with AWS Virtual MFA.  Unless there has been a significant change, they give you a QR code with a secret key that you can use to initialize any app that does all the TOTP calculations internally.  No server communication is required.


Write javascript for confirm delete in gridview rowdeleting event

Question: I am deleting a row from gridview for which i have used gridview's default delete command field. On clicking, the gridview row deleting command gets fired and the selected row gets deleted. All good till now.
But before the row gets deleted, i need to set confirmation message to user. On clicking of OK button the row should get deleted else not (on click of cancel button).
I have the code as;
return confirm('Are you sure to delete?');

But this works fine if there is a linkbutton (instead of command field) as i could easily write on OnClick event of linkbutton and could add the attributes in Gridview RowDataBound event.
How the same would work for command's field delete button? Please guide!
Thanks!
Comment: would you prefer jquery or are you looking for something in javascript?
Answer: This article explains how to do exactly what you need:
http://www.codeproject.com/KB/webforms/Gridview_Delete_confirmLS.aspx
And here is the code you need to do it:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // loop all data rows
        foreach (DataControlFieldCell cell in e.Row.Cells)
        {
           // check all cells in one row
           foreach (Control control in cell.Controls)
           {
                // Must use LinkButton here instead of ImageButton
                // if you are having Links (not images) as the command button.
                ImageButton button = control as ImageButton;

                if (button != null && button.CommandName == "Delete")
                    // Add delete confirmation
                    button.OnClientClick = "return confirm('Are you sure you want to delete this record?');";
            }
        }
    }
}

Comment: Although this is accepted answer, it doesn't work. It displays correctly the confirmation dialog, but it when I click OK, it doesn't generate postback event. Your code is different from the code on that codeproject page - and that one works. Please update your code.
Comment: Have you considered that there may be an issue with your implementation of the code? Pretty straight-forward stuff here.
Comment: Something is wrong somewhere, of course possibly in my code. But I really need to rewrite that "return confirm('...');" to "if(!confirm('...')) return false;" to work in my Firefox. It effectively means "if true, don't return". Other variants don't work for me. Can you see what's wrong?
Answer: Here is code which you can use....
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach (DataControlField dcf in GridView1.Columns)
        {

            if (dcf.ToString() == "CommandField")
            {
                if (((CommandField)dcf).ShowDeleteButton == true)
                {
                    e.Row.Cells[GridView1.Columns.IndexOf(dcf)].Attributes.Add("onclick", "return confirm('Are you sure you want to delete?');");
                }
            }
        }
    }
}

Comment: no,cannot use linkbutton or template field. I have to use commandfield delete button only
Comment: Will the code work, if i have written the code to delete the gridview row in rowdeleting event?
Comment: yes, it should work, the code in my answer is show confirm on command field.
Answer: Try this.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach (DataControlFieldCell cell in e.Row.Cells)
        {
            foreach (Control control in cell.Controls)
            {
                // Choose between Button, ImageButton and LinkButton.
                // as my ButtonType="Button".
                Button button = control as Button;
                if (button != null && button.CommandName == "Delete")
                {
                    string script = "if(confirm('Are you sure to delete?')) __doPostBack('{0}','{1}${2}'); else return false;";
                    string clickEvent = String.Format(
                        script,
                        GridView1.ClientID,
                        button.CommandName,
                        button.CommandArgument);
                    button.Attributes.Add("onclick", clickEvent);
                    break;
                }
            }
        }
    }
}

Much more dirty than I originally anticipated. Better to use a asp:TemplateField :)
Please note that my ButtonType="Button"
Comment: Will the code if i am writing code to delete the row in Gridview_rowdeleting event?


Javascript group by 2 columns and sum up total

Question: I found a similar problem to mine on above post.
Need to get the total from the below json
const d = [
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];

I used the solution as given in the answers
function groupBy(data, fields, sumBy='Value') {
  let r=[], cmp= (x,y) => fields.reduce((a,b)=> a && x[b]==y[b], true);
  data.forEach(x=> {
    let y=r.find(z=>cmp(x,z));
    let w= [...fields,sumBy].reduce((a,b) => (a[b]=x[b],a), {})
    y ? y[sumBy]=+y[sumBy]+(+x[sumBy]) : r.push(w);
  });
  return r;
}

However I need to achieve the below result for my purpose.
Not sure how to achieve this.
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1, Task 2", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1, Task 2", Value: "35" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1, Task 2", Value: "55" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1, Task 2", Value: "75" }

Comment: please add the data in a valid javascript form and add your try.
Comment: Please [edit] your question to show what research you've done, and any attempts you've made based on that research.
Answer: You can use an object accumulator to group your array based on Phase and Step and sum up Value for same key.

const data = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },  { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ],
      result = Object.values(data.reduce((r,o) => {
        const key = `${o.Phase}_${o.Step}`;
        r[key] = r[key] || {Phase: o.Phase, Step: o.Step, Task: [], Value: 0};
        r[key].Task.push(o.Task);
        r[key].Value += +o.Value;
        return r;
      }, {}))
      .map(o => ({...o, Task: o.Task.join(',')}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can create a dynamic keys based on the Key name in Keys array and group your data array based on this key.

const data = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },  { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ],
      keys = ['Phase', 'Step'],
      result = Object.values(data.reduce((r,o) => {
        const key = keys.map(k => o[k]).join('_');
        r[key] = r[key] || keys.reduce((ob, k) =>  ({...ob, [k]: o[k]}), {Task: [], Value: 0});
        r[key].Task.push(o.Task);
        r[key].Value += +o.Value;
        return r;
      }, {}))
      .map(o => ({...o, Task: o.Task.join(',')}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comment: Thanks Hassan for your help.
If I want  "group by" parameters to be dynamic, ie i want to group by Phase/Step or Phase/Task based on certain conditions, how can i achieve that
Comment: You can follow @NinaScholz approach by creating array of `groups` and then creating keys out of it.
Comment: The syntax "??" in that approach is not working.
Do I need to include any other library.
It says Support for the experimental syntax 'logicalAssignment' isn't currently enabled
Comment: See the edit above. It contains logic to group key based on dynamic keys.
Answer: You could take the wanted keys for grouping in an array and build a compound key and take an object as hash table. For common keys add Task and Value values.
At the end take only the values from the object.

const
    data = [{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }],
    groups = ['Phase', 'Step'],
    result = Object.values(data.reduce((r, o) => {
        const key = groups.map(k => o[k]).join('|');
        r[key] ??= { ...o, Task: '', Value: 0 };
        r[key].Task += (r[key].Task && ', ') + o.Task;
        r[key].Value += +o.Value
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comment: you could replace the line with an logical OR insta a nullish assingment operator: `r[key] = r[key] || { ...o, Task: '', Value: 0 };`


How to cache minipanels

Question: I use minipanels in specific regions of pages (such as the main menu region) and they generally conain content that stays the same. How can I cache these minipanels?
Is the block caching system independent from the minipanels? I am not sure about that, since minipanels also show in the blocks configuration admin page.
Answer: You can cache mini panels from mini panels UI settings.
Go to the mini panel content edition page.
You have then 2 choices. Above in global mini panel display settings or per panel content piece : in its wheel settings at the bottom...

How to cache minipanels


create File supporting UTF-8

Question:
Possible Duplicate:
How to write a UTF-8 file with Java?

I want to create a csv file using java and write into it which supporting UTF-8.
How can I do this.?
Comment: see http://stackoverflow.com/questions/1001540/how-to-write-a-utf-8-file-with-java
Answer: new OutputStreamWriter(new FileOutputStream("path/to/file"), Charset.forName("UTF-8"))

Answer: Writer myWriter= new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("filename"), "UTF-8"));
try {
    myWriter.write(stringdata);
} catch(Exception e){
e.printStacktrace();
}

create File supporting UTF-8


Take 2 fields in a content type with php

Question: I have a content type with the following fields:
Name, Language, Date, Photo, Text
associated with the following names for internal use:
title, language, field_date, field_photo, body
I created instances. One of these is called "Mondovi." I would like to see only the fields field_data and body of this instance. I want to use php to put them within the content or within a block. What to do?
Comment: This doesn't really make a lot of sense.  You could probably re-write it to prevent it being closed.
Comment: know how to do? If you do not understand what I do, what is not clear?
Comment: The language and structure of the question makes it far too ambiguous.
Comment: @Chapabu I tried
Answer: Let assume that you are using Drupal 7
You need to know nid of node "Mondovi".
Then you can use following code:
<code>$node = node_view(node_load(NID_OF_NODE));

// print value of body field without field label
print render($node['body'][0]);

// or print body value with field label and all div wrappers
print render($node['body']);

// print value of field_data without field label
// if field can have multiple values - use cycle to dipslay all of them
print render($node['field_data'][0]);
</code>
Comment: Hello,
Can I enter these commands php in a template where I can also make html / css? in this case, which would be more suitable for the file do it, and how to proceed right? If I put these commands into blocks, then I need a way to group them ...
Comment: The best way is to create MODULE which provide custom block - read here how to do this http://drupal.stackexchange.com/a/5587/7313


What is the order of $\mathbb{Z}[\sqrt{-5}] /(2)$

Question: I've been trying to figure this out. The hint is that it isomorphic to some group that is not a field. I keep on getting that  $\mathbb{Z}[\sqrt{-5}] /(2)$ is isomorphic to $\mathbb{Z_2}$
Answer: Hint: no two of $0,1,\sqrt{-5},1+\sqrt{-5}$ are congruent modulo 2.
Answer: You may obtain an explicit description of $\mathbb{Z}[\sqrt{-5}]/(2)$ by looking at
$\mathbb{Z}[\sqrt{-5}]/(2) \cong \mathbb{Z}[X]/(2,X^2+5) \cong \mathbb{F}_2[X]/(X^2+1)$.
Also, the quotient ring may be realised as the following matrix ring:
$\mathbb{Z}[\sqrt{-5}]/(2) \cong \left\{ \begin{pmatrix}a&b \\ b&a \end{pmatrix} ~|~ a,b \in \mathbb{F}_2 \right\}$.
Comment: It's the [dual numbers](http://math.stackexchange.com/a/17151/242) mod 2 since the ring $\cong \Bbb Z_2[\epsilon]/(\epsilon^2),\,\ \epsilon = 1-\sqrt{5}.\ \ $


Why is my own app incompatible with my phone?

Question: I have made an app, and tested it fully on my phone. When I uploaded it to the market, it says it is incompatible with my phone - why is this, and is there any way to manually include my device?
Answer: It turns out that because I had set my app to use the protection (App-Private data folder), it wouldn't be installed to rooted phones. My phone is rooted.


Recommendations for beginner chord practice

Question: I am a beginner (learning with acoustic guitar). Started learning  major chords now and this is the sequence I am planning on practicing it; A, A-A#, A-B....  A#, A#-A, A#-B.... i.e I also want to practice changing the chords right now. I already am having finger pain, but now when I play chords it is even more.
When I change the chords without removing the contact between the fingers and the strings, The pain gets unbearable but when I do take my fingers off the strings between changing chords the pain is less but I do more mistakes and it takes longer for me to relocate the fingers.
In which method should I keep practicing? and what is the ideal chord-practicing time for beginner. I tried 1 hr one day and I couldn't lift my hand the next.
Comment: What is the actual reason for changes like these ? Are they exercises, or a particular song you want to learn.Most songs will not have changes such as these, so other chord changes will be more beneficial.
Comment: Perhaps the most common changes occur between a chord and one either a fourth  or a fifth away from it. As in A - D and A - E. There won't be many songs without these changes. To achieve this, you need to stay on the same fret, but change shape (for barre chords), say, from an E to an A shape.This is only the beginning, but a far more useful one generally than what you're practising.Of course, in the end, you'll need to be able to change any chord to any other, but one day at a time for now!
Comment: Just read that you are playing A# but not using barre chords. So you must be using a shape like Bob broadleys answer? Anyway, you will find that changing to chords of a completely different shape will use different muscles and give your hand a rest.
Comment: I notice you want to play A-A#-B etc. Are you planning to use the same shape and move it up and down the neck?
Comment: yes I want to use the same shape
Comment: @Tim indeed, the only type of music where you find a lot of half-step changes between major chords is certain riffs in punk music. A more general case would be certain progressions in phrygian mode (as in flamenco) for example Am-G-F-E. RPS, you should focus on changes which are a fourth (5 semitones/frets) or a whole step (2 frets) apart. Read about the cycle of fifths and which chords belong to which key (and practise some real songs from a beginner's book, which will have typical and easy progressions!) This answer of mine may help: http://music.stackexchange.com/a/15944/9630
Comment: @Tim, for practicing, I want to be thorough with the chords and most importantly change them as quick as possible. not for any particular song.
Comment: Where are your fingers hurting? If it's the skin on the tips, that's ok. But if you're having joint or muscle pain, STOP! You should start with simple songs in a key like A major (chords D,A,E) or G major (chords C,G,D) Hurting your joints will not help and could cause permanent damage. There's plenty of songs you can play without barre chords. Move onto barre chords slowly when your body is ready.  Remember it's not about how hard you press, it's about pressing consistently on the strings you need. It took me a couple of months to get barre chords, using maybe one or two in a song at first.
Answer: Practice Time:
There is no ideal length of time for practising, especially for practising any one technique. However, an hour does seem like quite a long time for a beginner to be playing chords. It is quite normal for the ends of your fingers to become a little sore while playing, as you play more your fingers will become stronger and the skin on your finger tips will become tougher. However, if you are getting a lot of pain, particularly if it is in your wrist, arm or shoulder I would definitely play a little less.
Whether you are getting a lot of pain or just a little soreness, I would still take regular breaks while practising. This doesn't have to be long (not even a real break from your practice), but just half a minute or so between exercises to give your fingers a rest. This can also help to make your practice more relaxed and help you to sustain concentration.
Generally, it is better to practise for a shorter amount of time very regularly, than for a long time only now and then. For instance, 30mins every day is better than an hour three times a week.
Technique:
You are right that you don't want to move your fingers away from the strings while changing between chords. You keep them close, so that the chord change can be quicker and more accurate. There are two ways to achieve this:

one is to keep any notes that are common to two chords in position while changing (for instance, keeping finger 2 on fret 2 string 4 when changing from Em to C);
the second is to allow fingers to move along the string if the same finger is used on different frets in two chords (for instance, moving finger 1 along string 3 when changing from an E chord to a D chord. I call this technique, using a guide.

If you are planning to play chromatic chord change exercises (eg. A - A# - B etc.) you will probably want to use the same shape for each chord, so you would use the second technique, allowing each finger to move along the string it is on. However, you do not need to keep each finger fully pressed down to use this technique. Instead, you should lift enough so that the string is no longer pressed against the frets, but so that your finger is still touching the string. This makes a lot of difference. It allows you to keep the accuracy and speed of chord change, by keeping your fingers on the strings as "guides", but gives your fingers and wrist a little rest from pressing hard in between every chord change.
Use Easier Chords:
All chords on the guitar can be played with a wide variety of shapes, some easier to play than others. You can build up to playing more difficult chords by starting with simpler ones. For instance, start by playing major chord shapes only using three strings, before moving on to shapes with four, five and six strings. Below are some suggestions for how to play the chords A - A# - B, starting with easier three-string shapes:

As you can see each progression of chord changes uses the same shape, moving it up one fret at a time. (Sorry the chord boxes are a bit untidy - I scribbled them in a hurry!) The first shape will help you to move onto the fourth shape. Also, you could try the first shape with fingers 1, 2 & 3, if you find it difficult to press down two strings with finger 1. The third shape could be played with just one finger across the three strings.
Answer: Adding to Bob's always great answers, if you need to change up or down a fret - I can't think if many songs that it happens in - it's probably time to learn barre chords. This will be a tremendous leap for you, both in effort and in usefulness. Once you have achieved this status, your playing will soar.
Bob says 30 mins, I'd advocate even less, certainly not the hour you felt was necessary. 10/15 mins is plenty at this stage, with a break of an hour or two before the next session. If it hurts, it's God's way of saying give yourself (and your hand) a break - you've deserved it. With all guitar playing, be aware that it's not necessary to press really hard on strings - unless your guitar has a less than good action, in which case, get it sorted or change to a better guitar.
By the way, A# is far more commonly called Bb -by most people apart from guitarists ! I'd love to know why!
Comment: As has been said many times here - have a few lessons at least. A good teacher will be able to verify the guitar as good, or not, and give you pointers that are well nigh impossible to give via a site such as this.
Comment: Thank you for more advice. I thought an hr was needed coz I kept stopping and shaking my fingers for few secs many times due to the pain and didn't felt like I practiced continuously and _effectively_. And also I like _have_ to press hard against string else the sound doesn't _sound_ right, especially when my fingers are near the fret lines. May be since i am not used to play guitar that my fingers are lacking enough strength
Answer: If I don't know what you mean by "beginner" but if you're beginning with the chords, i don't think A# or B is a good choice, since it's quite hard to do on the six strings at the same time. I believe you should start with simple chords like
A C D E G - Am Dm Em
Then you begin the barred chords with
Fm A#m - F (with Am Fm and F you can do almost all chords by transposing it on different frets).
The hard thing with A# is that 1)you must make a double bared and 2)if you want to hear the six strings, the 3-finger must be very precise, not to touch the high-E string and not to mute it.I think you must try to do it after the other chords, and start with the 3 higher strings of the chords, and progressively getting lower strings from D to low-E, then playing this chord on different frets
The time you give yourself of course increases your abilities, but its not linear (less than the number of times per week !). So, giving yourself a lot of time is good, unless it gets you bored, which would be very bad ;)
Hope it's been useful, farewell !
Comment: A# was sooo hard ;( , It felt like I pulled a nerve in the outer edge of my left wrist! I will try to practice again with others' tips, if pain persists I will change the order like you suggested. Thank you loads.
Answer: Practicing changes between nearby chords isn't going to do that much for your musical development as a beginner, in my opinion.
Try learning a relatively easy key first. Most of the chords in C major are fairly easy, and they will enable you to play quite a variety of songs relatively quickly. I play them in order (C Dm Em F G Am Bdim) when I am first learning them, but that is not necessary.
At this point it is good to try to play music with what you have learned. Use them in songs, or learn songs that use them. Learning in this manner is going to be more rewarding and more instructive than trying to learn chords chromatically.
Once you feel reasonably comfortable with what you have learned, either learn some variations of those chords or move on to a new key.
Don't do only finger and chord exercises. You will get bored and quit. Learning chord progressions and songs is a better way to keep motivated and it helps you to get used to the way the chords come up in normal situations.
Encyclopedic knowledge of every chord/chord-shape is neither necessary nor sufficient to ensure that you can play or compose successfully.
As for the pain:
Depending on the type of pain you are experiencing, you need may need to scale back your practice a bit.
If you mean your fingertips (or skin) hurt because you don't have calluses, then I don't think there is much harm if blisters don't bother you. Eventually this will stop. You might have a technician look at your guitar to see if it is set up properly. If your strings are too high above the fretboard, it makes the guitar hard to play because you have to push harder on the strings. A qualified person can verify if this is the case and modify the saddle for you if it needs to be done.
Lift your fingers off the strings completely if it hurts during changes. It shouldn't affect your speed in the long-term.
If you have muscle ache like someone who did too much exercise at the gym, then I don't think that is so dangerous either, but it is an indication that you are overdoing it a bit.
However if you experience sharp pain, then your body is screaming at you "Stop doing that, now!" You can cause serious damage to your hand if you try to ignore that.
Answer: Really sorry to hear changing chords causes pain - I'm thinking it probably shouldn't be like that otherwise no-one would play guitar! As you couldn't lift your hand, I assume you mean aching in the hand/wrist rather than the pain in the pads of the fingers? If it's the pads, that'll go as they toughen up with practice. Everyone gets that at first and it does go away.
So assuming you mean general hand-ache:
Others have made great suggestions re how to go about changing chords, but I wonder whether your guitar is causing you trouble? might be worth checking it out ..
The thickness of the strings and the distance from the strings to the frets (=the "Action") are prime factors in how hard it is to play a chord convincingly.
The strings rest on the nut (at the head end) and the bridge (on the body of the guitar) - both play a part in the Action (distance) so if you're playing an A shord and the action around that area is high, it's going to require more strength to fret the strings.
It should be something in the reqion of a millimetre or thereabouts, because the strings don't rattle about much that end so it can afford to be less distance. It;s a curious thing that some quite nice guitars have this set badly so that chords like F and Bb (A#) are really hard to play, but chords in the middle of the neck are relatively easy.
At the top end of the neck (ie highest fret) it's usially a bit more than the nut end to allow for the string flapping about in the middle, but still shouldn't be more than a couple of millimetres.
It;s a bit hard to describe in distances because it really depends on how it "feels" but basically it shouldn't feel like you're asking the string to bend much just by fretting a string.
Note that tastes vary so these measurements are just my personal estimates based on a "nice rweasonable guitar that I woud like to play", but are hopefully something to give you guidance if you look at yous and see it's way out.
If the nut is set too high, you can normally reduce it by taking the strings off (just loosen them & pull them out of the groove in th nut) and carefully sanding the grooves deeper with a folded bit of sandpaper./ Use VERY smooth paper so that you don't go too fast and reduce too much. altertnatively take it to a guitar technician - it shouldn't cost much and I bet they could do it there and then.
Regards the thickness of the strings : If it's hurting a lot, maybe you could try lighter strings ? It makes them a bit sharper so they'll cut into your pads more, but as I said they'll toughen up and that on;t be a problem after a few weeks.
Perhaps you could try this for a while as you get used to changing chords, then put meatier ones on once your'e more used to it.
Answer: I would recommend that you intersperse some single note passages within your chord practice so that your hand doesn't cramp up, as well as to reinforce how lightly the string may be pressed. For starters, I I would simply recommend the nearly chromatic scale in the position where you are playing -- that is, four frets (one per finger) ascending from the bass strings to the trebles and back again. This will build dexterity.
After your music theory develops and you begin to play chords from a common key, then switch your single note exercises to arpeggios or scales from the current key. I think that you will enjoy that development.
The muscle memory takes time to establish, but eventually the chord shapes and positions will become virtually second-nature. Be patient and pick up your guitar daily, if possible. Above all, enjoy yourself!
Answer: I too am a beginner, so I am quite aware what you are going thru. But here is what I found:
Practice chords no more than 15 min at a time. I found that practicing for 15 min 2 or 3 times a day is long enough.
I also found that when I feel pain in my fingers, it is because I am pressing on the strings too hard. When it hurts, ease up on the pressure.


Colorbox inline style="display:none" doesn't disappear

Question: I am using colorbox module.
I have an inline modal that works o.k, this is the code:
view content

    <input name="name" type="name" />
    <input name="phone" type="phone" />
    <input name="email" type="email" />

This code is an a view header.
When I click the link the modal pops but it is empty.
I've noticed that the style="display: none;" in the div does not disappear.
What can cause this?
Any help will be great.
Comment: is there any javascript that attached that attribute? or hardcoded in the tpl?
Comment: no... not as much as i know... this is a new drupal installation with some modules
Answer: O.k... I changed the code to this and it works...
Link to click

        <input name="name" type="name" />
        <input name="phone" type="phone" />
        <input name="email" type="email" />

Comment: The other way would be .view-header #paste-data-to-lp { display: none; } . You just need to narrow down where you hide it. It's generally recommended that you do styling with an external css file so your styles don't have to be configured in the UI.


Access inline SVG's transformed group bounding box (x and y position, width and height)?

Question: Is there an "easy" DOM way to get a group's transformed position (center or origin) and bounding box (width, height)?
<g> as a logical container tag does not have geometric attributes aside from transform, which its children use.

let o = document.getElementById("o");
let g = document.getElementById("g");

o.textContent += "rect  x = " + r.x.baseVal.value + "\n";
o.textContent += "group x = " + g.x.baseVal.value + "\n";  // TypeError: g.x is undefined
svg{background-color:#f3f3f3}
<svg viewBox="0 0 200 200" width="200">
<g id="g" transform="translate(100,100)" >
  <rect id="r" width="100" height="100" ></rect>
</g>
</svg>

So it probably is required to iterate all children and calculate the sum of their bounding boxes (including transforms)?

Edit:
The following returns the group's bounding box without the transform:

let o = document.getElementById("o");
let g = document.getElementById("g");

o.textContent += "getBBox().x = " + r.getBBox().x + "\n";
o.textContent += "getBBox().y = " + r.getBBox().y + "\n";
o.textContent += "getBBox().width = " + r.getBBox().width + "\n";
o.textContent += "getBBox().height = " + r.getBBox().height + "\n";
svg{background-color:#f3f3f3}
<svg viewBox="0 0 200 200" width="200">
<g id="g" transform="translate(100,100)" >
  <rect id="r" width="100" height="100" ></rect>
</g>
</svg>

Comment: call getBBox. That works on a  and also on individual leaf elements.
Comment: create a parent  element and get that element's bounding box.
Comment: @RobertLongson Thanks, now the result just needs to be transformed - do you happen know of a method for that, too?
Answer: https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox

The SVGGraphicsElement.getBBox() allows us to determine the
  coordinates of the smallest rectangle in which the object fits. The
  coordinates returned are with respect to the current svg space, i.e.
  after the application of all geometry attributes on all the elements
  contained in the target element.

But also:

The returned value is a SVGRect object, which defines the bounding
  box. This value is irrespective of any transformation attribute
  applied to it or the parent elements.


Taking Log to find MAXIMIZE summation of variables

Question: I have been reading IEEE papers on communication and in several papers the authors formed objective function like:
$\text{Maximize }    \sum_k \log r_k $
to maximize the total rate of the system of $k$ users. Here $r_k$ is the rate of the $k$'th user. Now I cant understand how taking logarithm is relevant with maximizing. This is a common case in 'Entropy Maximization'. Is there any general mathematical explanation of this? Any explanation is highly appreciated.
Answer: Maximizing a sum of logs over a convex set is called achieving proportional fairness. This is a standard goal in communication networks.  Here, $r_k$ is the communication rate achieved by user $k$.  Each user wants to maximize its own rate.  However, there are shared resources.  Let $\Lambda$ be the (typically convex) set of all possible rate vectors $(r_1, r_2, \ldots, r_K)$ that the system can support.  We want to find a Pareto optimal point.  Maximizing a sum of increasing and concave utility functions is used because concave functions have a diminishing returns property, which says that we would prefer to make allocations relatively even (pushing up those who have lower rate).
The log function is analyzed in particular in:
Frank Kelly, "Charging and Rate Control for Elastic Traffic," European Transactions on Telecommunications, vol. 8, no. 1 pp. 33-37, Jan.-Feb. 1997.
If $\Lambda$ is a convex set, it can be shown that finding a vector $r^*=(r_1^*, \ldots, r_K^*)$ that maximizes $\sum_{k=1}^K \log(r_k)$ subject to $(r_1, \ldots, r_K) \in \Lambda$ means that:
$$ \sum_{k=1}^K\frac{r_k-r_k^*}{r_k^*} \leq 0 $$
for all vectors $(r_1, \ldots, r_K) \in \Lambda$.  This can be interpreted as the "proportionally fair" criterion:  Consider changing from the $r^*$ vector to some other vector $r \in \Lambda$. You might be able to increase rates of particular users by deviating from  $r^*$, but the overall proportional change is never positive, where this change weights users with currently low rates $r_k^*$ more heavily, which is a fairness feature.

Example 1: A simple example is when the set $\Lambda$ is the set of all nonnegative rates that sum to less than or equal to 1.  Then one solution to maximizing the linear function $\sum_k {r_k}$ over $r \in \Lambda$ is $(1, 0, 0, ..., 0)$, which is clearly unfair since it gives one user everything.  Howevever, maximizing the strictly concave function $\sum_k \log(r_k)$ over the same set $\Lambda$ gives the (much more fair) solution $r^*=(1/K, 1/K, ..., 1/K)$.
Example 2:  Suppose $\Lambda$ is the set of all $(r_1, ..., r_K) \geq 0$ such that $r_1/2 + \sum_{k=2}^K r_k \leq 1$.  Maximizing the linear utility function $\sum_k r_k$ over $\Lambda$ gives the (unfair, and unique)  solution $(2, 0, 0, ..., 0)$.  Yet, maximizing the $\sum_k \log(r_k)$ over the same set gives the (more fair, in fact, "proportionally fair") solution: $(\frac{2}{K},  \frac{1-1/K}{K-1}, ..., \frac{1-1/K}{K-1})$.
Comment: You could define a recursion that starts with a weight vector $w[1]=(w_1[1], ..., w_K[1])$, solves for $r^*(w[1])$ as the maximizer of $\sum_{k=1}^K w_k[1]\log(r_k)$, then iteratively defines $w[n+1]$ such that $w_k[n+1] = \frac{r_k^*(w[n])}{\sum_{i=1}^K r^*_i(w[n])}$. I don't know why you would want to do that, at every step it seems to give more weight to users that already have high rate (which seems the opposite of fair).  But in example 1, if we start with uniform weights, we always stay at uniform weights.  In example 2, I think we converge to the (unfair) vector $(2,0,0,...,0)$.
Comment: Excellent explanation sir! I have already read the paper that u mentioned but could not understand the whole of it. but your examples makes it easier for anyone. thanks a lot. @Michael.
Comment: After seeing the constraint in example 2, one thing came to my mind. If a system starts with distribution equation rates: $r* = (1/k, \cdots, 1/k)$. The system uses a weight $w_k$ for each user, where $w_k = r_k/ \sum_k r_k$, and then say after every slot the system wants to maximize the rate of those user whose weight is higher. How can the constraint should be set to allow this? Or changing the objective function as $Maximize  \sum_k w_k \log r_k$ is sufficient to achieve that? Please answer. thanks a lot.
Comment: I do not understand your question.  What is the $r_k$ value in your $w_k$ weight?  If you have weights $w=(w_1, ..., w_K)$ then maximizing $\sum_k w_k \log(r_k)$ gives a vector $r^*(w)$ (which depends on $w$).


what is SPI Check while uploading iOS?

Question: while uploading the app from xcode 13.x it stuck to

"Performing SPI Check.."

any idea what is this about?, added a pic for reference.
Comment: I've been facing this "Performing SPI check…" stage the last two times I uploaded to App Store Connect and I don't know what it is. It takes a very long time to finish.
Comment: same here but it got solved when I re-initiated the uploaded process
Comment: First validate the build, then upload it. First time me also faced the same issue....
Comment: @Naresh you mean if I validate the build, then SPI check time would decrement?
Answer: Service Provider Interface most likely,
and I'd be guessing they are checking for usage of private APIs
https://en.wikipedia.org/wiki/Service_provider_interface
Answer: I also faced the same problem, but it worked after retrying the upload process.
For anyone, if the issue persists try restarting the Mac or try more suggestions from this Thread
Answer: Maybe System Programming Interface where it checks to see if you're calling any private APIs?

what is SPI Check while uploading iOS?


Finding a perpendicular vector from a line to a point

Question: Let's say I have an arbitrary linear line described by $y=mx+b$. I also have a point $P(x_1,y_1)$ that is not on that line. I suppose $P$ can be anywhere relative to the line. How can I find the vector $v$ the stretches from the point to the line (and is perpendicular to it)?
Here's what I tried: I figured that the difference in the $x$ and $y$ components ($\delta y$ and $\delta x$) basically describe a vector twice as large as $v$ but in the same direction. So I tried finding $\delta x$ and $\delta y$ by the following:
$\delta y=y_1-(m\cdot x_1 +b)$
$\delta x = x_1-(y_1/m - b/m)$
The vector V is then $[\delta x/2, \delta y/2]$. I divide by two because I figure the vector described by $[\delta x, \delta y]$ goes all the way to the top left corner of the imaginary rectangle that is completed by $\delta x$ and $\delta y$.
Am I correct? If not, why? Regardless if I am, is there an alternative or smarter way to accomplish this? I would appreciate any input here.
Answer: First I will write the line $l$, defined by $y=mx+b$, as a parametric vector equation,
$$
l = \left\{\vec{u}_0 + \lambda \vec{u}_1, \lambda \in \mathbb{R}\right\}, \tag{1}
$$
where $\vec{u}_0$ and $\vec{u}_1$ are equal to,
$$
\vec{u}_0 = \begin{pmatrix} 0 \\ b \end{pmatrix}, \tag{2}
$$
$$
\vec{u}_1 = \begin{pmatrix} 1 \\ m \end{pmatrix}. \tag{3}
$$
This notation will be useful when projecting an arbitrary point $P$ onto the line. Any point on $l$ can be seen as a scaled version of $\vec{u}_1$ with its origin at $\vec{u}_0$. The point $P$ can be seen as a vector with its origin at $\vec{0}$. Both origins have to be the same in order to be able to project $P$ onto the line. This can be done by adding $\vec{u}_0$ to its origin and subtracting $\vec{u}_0$ from $P$, which is visualized in the following figure:

The projection of $P$ into $l$, denoted with $P'$ with its origin at $\vec{0}$, can be found with,
$$
P' = \frac{(P - \vec{u}_0) \cdot \vec{u}_1}{\vec{u}_1 \cdot \vec{u}_1} \vec{u}_1 + \vec{u}_0. \tag{4}
$$
When writing $P$ as $(x_p,y_p)$ and using equation $(1)$ and $(2)$ for $\vec{u}_0$ and $\vec{u}_1$, then $P'$ can be simplified to,
$$
P' = \frac{(x_p + m (y_p - b)}{1 + m^2} \begin{pmatrix} 1 \\ m \end{pmatrix} + \begin{pmatrix} 0 \\ b \end{pmatrix}. \tag{5}
$$
The vector $\vec{v}$, with its origin at $P'$ and point to $P$, can be found with,
$$
\vec{v} = P - P'. \tag{6}
$$
Comment: I just want to tell you how much I love this answer. Really appreciate the figure too. I think I'll be using this idea in the future.
Comment: @JohnAlperto Thanks, I tried to explain it as visually as possible, such that one might understand better some of the underlying principles involved and be able to apply them to other similar problems.
Answer: Let $(x_2, y_2)$ be the foot of perpendicular drawn from the given point  $P(x_1, y_1)$ to the line: $y=mx+b$ then the line joining $(x_1, y_1)$ & $(x_2, y_2)$ is perpendicular to the given line hence we have the following condition
$$\text{slope of line joining}\ (x_1, y_1) \ \text{&}\ \ (x_2, y_2)=\frac{-1}{\text{slope of line:}\ y=mx+b}$$
$$\frac{y_2-y_1}{x_2-x_1}=\frac{-1}{m}\tag 1$$
Since, the foot of perpendicular $(x_2, y_2)$ is lying on the line: $y=mx+b$ hence, by satisfying the equation we have $$y_2=mx_2+b\tag 2$$ Now, solving (1) & (2), we can find out the coordinates $(x_2, y_2)$ as follows $$x_2=\frac{x_1+m(y_1-b)}{1+m^2},\ \  y_2=\frac{mx_1+m^2y_1+b}{1+m^2}$$
Hence, the vector $v$ from $P(x_1, y_1)$ to $(x_2, y_2)$ perpendicular to the line is determined as follows  $$\overrightarrow v=i(x_2-x_1)+j(y_2-y_1)$$
Comment: Just to be clear, is your answer essentially the same as mine except that you don't divide by 2?
Comment: Yes, this method is straight forward.
Comment: OK, one more question, can you explain how equation 1 works again?
Comment: The product of slopes/gradients  of the perpendicular lines is $-1$
Comment: OK great, thanks for your help.
Answer: Let the line $L$ be
$$ax+by+c = 0 \tag{1}$$
Let P be
$$ P = (x_1, y_1) \tag{2}$$
Now, to make calculations easier, shift the coordinate system by the vector given by the position $P$, so that $P$ is the origin of the new coordinate system and the new equation for $L$ is
$$ a(x+x_1) + b(y+y_1) + c = 0 \tag{3}$$
If we let a the constant $s$ be the constant at the end of this equation, $$s = ax_1 + by_1+ c$$ The equation for $(3)$ becomes much shorter,
$$ax + by + s = 0 \tag{4}$$
To calculate the vector that we need, which is from the line to $P$, we need to write the equation for the perpendicular line to the line $L$ and through the point $P$, which in the new coordinate system is given by $$ bx - ay = 0 \tag{5}$$
After a few manipulations we get $ bx = ay $ and $$x = \frac{a}{b} y$$ Now the intersection of $L$ and its perpendicular yields the other point of the vector. Substituting this into $(4)$ yields
$a\frac{a}{b}y + by + s = 0$ then $(a^2 +b^2)y = -bs$, and finally
$$y = \frac{-bs}{a^2 + b^2}$$
And similarly $x$ can be shown to be
$$x = \frac{-as}{a^2 + b^2}$$
But since the vector begins at $(x,y)$ and goes to $P$, it's $$\begin{pmatrix} -x \\ -y \end{pmatrix}$$ So the vector may be written as
$$\begin{pmatrix} a\\ b \end{pmatrix} \times \frac{ax_1 + by_1 + c}{a^2+b^2}$$
If the line is given as $y = mx +b$, we need only to rewrite it as $mx + b - y = 0$ and the new value is
$$\begin{pmatrix} m\\ -1 \end{pmatrix} \times \frac{mx_1 + b -y_1}{m^2+1^2}$$.


Programmatically set fulfillment webhook for DialogFlow

Question: The DialogFlow documentation explains how to configure the Fulfillment webhook address using the web UI.
Is there a way to set it programmatically, calling any of the DialogFlow APIs?
Answer: The answer is a no if you are trying to programmatically set the webhook address. What you can do is put a static url from the web UI (which you can't change programmatically) & then using params access/change the service you want from the cloud functions.
Comment: This sucks. Any change since the last post?
Comment: No its the same.


Reattach or create a named screen session? (or persistent screen sessions)

Question: Basically I have a remote screen session, which I wish to automatically reattach to.. Currently I'm doing this by with the following command (as an iTerm bookmark, or an alias)
ssh host -t screen -x thesessionname

This works fine, but if the session dies for whatever reason, I'd like it to be recreated when I next connect. The -R flag for screen is almost perfect:
ssh host -t screen -R -S thesessionname

..but if the session is already attached, a second session gets made (as -R simple looks for the first detached session, if none are found it creates a new one)
Is there a way to make the -R flag look for attached sessions also, and only create a new one if thesessionname doesn't exist?
If this is not easily doable, how could I automatically recreate the screen session when it dies? Perhaps a script run via cron that looks for the named session, creating it should it not exist?
Answer: Tell screen to be a bit more persistent about trying:
-D -R
    Attach here and now. In detail this means: If a session is run-
    ning,  then  reattach.  If necessary detach and logout remotely
    first.  If it was not running create it and  notify  the  user.
    This is the author's favorite.

So combine the two and you should have your solution ("-DR" is equivalent to "-D -R"):
screen -DR <yoursession>

Additionally and useful to know, you can view running sessions with:
screen -ls

Comment: Perfect, `screen -x -R -S main` is what I ended up using (works the same without the forced-detach), thanks!
Comment: Sometimes you want to use `sceen -r `, will give an error when it's already attached (instead of creating a new session).
Answer: A few good options.  First, my favorite:
screen -x -R

That will attach to the first screen session available (sharing if another connection is connected), and if there are no screen sessions at all, start a new one.
screen -d -RR

Docs for that say "Reattach  a  session  and if necessary detach or create it. Use  the first session if more than one session is available."  Basically, the double-R makes it look for the first session to attach to.
screen -D -RR

"Attach here and now.  Whatever that means, just do it."  Will detach and remotely logout any other attached sessions and attach to the first session it can.  Basically, does whatever it needs to do to attach to an existing session, and creates a new one if there's nothing there.
The very first (-x -R) is the least likely to cause problems (won't detach your other connection) but just plain always attaches to something if there's anything to attach to and creates something if there's nothing to attach to.
Comment: These are all nice/handy options, but none of them answer the original question, which was to (re)connect to a session _by name_.
Answer: I use
screen -dRRS sessname

I don't want my entire login on the other shell dropped, like -D does, and I definitely don't want the multi-attach mode of -x.


prove $(a^3+1)(b^3+1)(c^3+1)\ge 8$

Question: let $a,b,c\ge 0$ and such $a+b+c=3$ show that
$$(a^3+1)(b^3+1)(c^3+1)\ge 8$$
My research:It seem use Holder inequality,so
$$(a^3+1)(b^3+1)(c^3+1)\ge (abc+1)^3$$
Use AM-GM
$$abc\le\dfrac{(a+b+c)^3}{27}=1$$
what? then I think  this method is wrong
Comment: @A---B assuming you meant $c=1$, those integers don't satisfy $a+b+c =3$
Comment: @Hari Shankar $\left(\ln(x^3+1)\right)''=\frac{3x(2-x^3)}{(x^3+1)^3}$ and Jensen does not help here. By the way, we can use the Vasc's LCF Theorem.
Comment: since $a+b+c=3$, and why download it?
Comment: Jensen's Inequality would be useful here
Comment: @MichaelRozenberg This wouldnt be the first time you have caught me misusing the inequality :). Anyway, its an honour to be corrected by you!
Comment: abc <= 1 means (abc+1)^3 <= 8 <= blahblah is not in any way a contradiction..
Answer: Let $f(x,y,z) = (x^3 +1)(y^3 +1)(z^3 +1)$ subject to the constraint $g(x,y,z) = x + y + z - 3 =0$ and $ x,y,z \ge 0$.
Then using lagrange multipliers we have

$f_x = 3x^2(y^3 +1)(z^3 +1)= g_x= \lambda$
$f_y = 3y^2(x^3 +1)(z^3 +1)= g_y = \lambda$
$f_z = 3z^2(x^3 +1)(y^3 +1)=g_z = \lambda$
$g(x,y,z) = x + y + z - 3 =0$

From the first three equations we see $x^2(y^3 +1) = y^2(x^3 +1) = z^2(y^3 +1)$. So then $x =z$, since $x, z \ge 0$. Then clearly $x=y=z$, so plugging into our formula for $g$, we see $x=y=z=1$, so $(1,1,1)$ is a critical point.
Now, $f(1,1,1) = 8$. To see this is a minimum, we see $(0,0,3)$ lies on our curve, and $f(0,0,3) = 28 \gt f(1,1,1) = 8.$
We conclude that $(a^3 +1)(b^3 +1)(c^3 +1) \ge 8$.
Comment: I didn't downvote you, but do you know it OP knows something about Lagrange multipliers?
Comment: The LM is okay but OP wants to see AM-GM, Cauchy-Schwarz, or Schur or Muirhead inequalities used in the proof. OP seems interested in non-derivative answers.
Comment: Given he knows about Holder's inequality, I'm fairly sure he knows Lagrange multipliers. If not, this is just but one solution.
Comment: It's one way to do it. Maybe someone else can find another one!
Answer: $\sum\limits_{cyc}\left(\ln(a^3+1)-\ln2\right)=\sum\limits_{cyc}\left(\ln(a^3+1)-\ln2-\frac{3}{2}(a-1)\right)$.
Let $f(x)=\ln(x^3+1)-\ln2-\frac{3}{2}(x-1)$.
Easy to see that $\min\limits_{[0,2]}f=0$.
Indeed, $f'(x)=\frac{3x^2}{x^3+1}-\frac{3}{2}=\frac{3(1-x)(x^2-x-1)}{2(x^3+1)}$ and since $x_{max}=\frac{1+\sqrt5}{2}$,
it remains to check that $f(2)>0$, which is true.
Thus, for $\{a,b,c\}\subset[0,2]$ our inequality is proven.
Let $a>2$.
Hence, $\prod\limits_{cyc}(a^3+1)\geq(8+1)\cdot1\cdot1>8$.
Done!
Comment: If you let $a>2$, then there's the stronger fact: $\prod\limits_{cyc}\left(a^3+1\right)\ge \left(a^3+1\right)\cdot 1\cdot 1$ $>(8+1)\cdot1\cdot1=9>8$.
Comment: @user236182 59 and we get $\sum\limits_{cyc}(a^3+1)>8$ again.
Answer: WLOG we assume that $(b-1)(c-1)\ge 0$.
By Carlson inequality we have
\begin{aligned}
{[(a^3+1)(b^3+1)(c^3+1)]}^{\frac{1}{3}}= & \;\;[(a^3+1)(1+b^3)(1+c^3)]^{\frac{1}{3}} \\
\ge & \;\;a+bc\\
= & \;\;3-b-c+bc\\
= & \;\;2+(b-1)(c-1)\\
\ge & \;\;2.
\end{aligned}
Done.
Comment: could you give a reference to the Carlson inequality you used here? My impression about Carlson inequality seems different.
Comment: @Yimin Here by Carlson inequality I mean $(x_1+y_1)(x_2+y_2)(x_3+y_3)\ge [(x_1 x_2 x_3)^{\frac{1}{3}}+(y_1 y_2 y_3)^{\frac{1}{3}}]^3$ (Just a special case of Hölder's inequality)
Answer: BY Jensen inequality with  $\phi\left(t\right)=\ln(t^3+1)$
$$\phi\left(\frac13\sum_{i=1}^{3}x_i\right)\le \frac13\sum_{i=1}^{3}\phi\left(x_i\right) $$
since $a+b+c= 3$ we get
$$\ln(2)=\phi\left(1\right)\le \frac13\left(\ln(a^3+1)+\ln(b^3+1)+\ln(c^3+1)\right) $$
hence $$\ln8= 3\ln(2)\le \ln \left((a^3+1)(b^3+1)(c^3+1)\right)$$
that is $$(a^3+1)(b^3+1)(c^3+1)\ge 8$$

prove $(a^3+1)(b^3+1)(c^3+1)\ge 8$