text:
Q: Use IFS() to return a range I'm writing a Google Sheets named function, GETTABLEOFCELL(), that takes in a cell reference, and returns the Named Range that cell exists in.
Since I could not find a native function to determine if a cell is within the specified range, I've defined a helper function called ISCELLINRANGE(range, cell).  I've confirmed that this helper function works for cells and ranges within the same sheet--good enough for my case.
ISCELLINRANGE(range, cell)
=AND(
  ROW(cell) >= ROW(range),
  ROW(cell) < ROW(range) + ROWS(range),
  COLUMN(cell) >= COLUMN(range),
  COLUMN(cell) < COLUMN(range) + COLUMNS(range)
)

GETTABLEOFCELL(tableCell)
=ARRAYFORMULA(
  IFS(
    ISCELLINRANGE(DeathWaveUW, tableCell), {DeathWaveUW},
    ISCELLINRANGE(BlackHoleUW, tableCell), {BlackHoleUW},
    // ...
  )
)

///

=ISCELLINRANGE(DeathWaveUW, D6) // => TRUE
=COLUMN(GETTABLEOFCELL(D6)) // => #VALUE!

=ARRAYFORMULA(
  IFS(
    ISCELLINRANGE(DeathWaveUW, D6), DeathWaveUW
  )
) // => #N/A

As seen above, to debug GETTABLEOFCELL(), I simply copied a snippet of the formula into a cell with hard-coded values.  It returns #N/A saying there is no match in the IFS() list, which I am guessing (read: hoping) is the root issue in GETTABLEOFCELL().  I've used both DeathWaveUW and {DeathWaveUW} syntaxes for the second argument of IFS; both return #N/A.
Any idea what I am doing wrong?

A: Issue:
IFS returns

*

*#N/A, when none of the conditions is satisfied

*#VALUE, when there are mismatched ranges

Solution:
For

*

*#N/A, Add a default value to IFS

*#VALUE, Fix the range size

Sample:

*

*#N/A
Add a default value:
GETTABLEOFCELL(tableCell)
=ARRAYFORMULA(
  IFS(
    ISCELLINRANGE(DeathWaveUW, tableCell), {DeathWaveUW},
    ISCELLINRANGE(BlackHoleUW, tableCell), {BlackHoleUW},
    TRUE, "No range found"
  )
)

This assumes All *UWs are of single range. If not, TRUE and "No range found" should be  modified to a array(MAKEARRAY is a option).

*

*#VALUE
If DeathWaveUW and BlackHoleUW and all other UWs were two dimensional and of the same size, you can change the aggregating function AND to a non-aggregating function like * to maintain the array size:
ISCELLINRANGE(range, cell)
=
  (ROW(cell) >= ROW(range))*
  (ROW(cell) < ROW(range) + ROWS(range))*
  (COLUMN(cell) >= COLUMN(range))*
  (COLUMN(cell) < COLUMN(range) + COLUMNS(range))

Alternatively, reduce the array size of named range to 1 by passing it as a string and use INDIRECT
GETTABLEOFCELL(tableCell)
=ARRAYFORMULA(
 INDIRECT(
  IFS(
    ISCELLINRANGE(DeathWaveUW, tableCell), "DeathWaveUW",
    ISCELLINRANGE(BlackHoleUW, tableCell), "BlackHoleUW",
    TRUE, "No range found"
  )
 )
)

Related:

*

*ArrayFormula and "AND" Formula in Google Sheets

*Mismatch Range error on using IFs in sheets


text:
Q: Can't get lx-select to display data I have the following select:
<lx-select ng-model="selects.selectedPerson" placeholder="Recommended by" choices="people" floating-label>
    <lx-select-selected>{{ $selected.name + ' ' + $selected.age }}</lx-select-selected>

    <lx-select-choices>{{ $choice.email }}</lx-select-choices>
</lx-select>

and the following $scope variables:
$scope.people = [
    { name: 'Adam', email: 'adam@email.com', age: 10 },
    { name: 'Amalie', email: 'amalie@email.com', age: 12 }
    ];

But when I run this code there are no results in this dropdown.  I can click the dropdown and the ripple effects occurs but no dropdown appears and no choices are ever selected.
What am I missing?

A: I just read that LumX has a known issue when using Bootstrap in addition to the bootstrap that comes with LumX.  I removed the reference to the nonLumX one and it took off.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error using eps ..... Class must be 'single' or 'double' I'm facing a problem with my code which is the error (using eps ..... Class must be 'single' or 'double'). which due to the following code line
beta=sqrt  (  (0.5*nthroot((Tt + (sqrt(-Delta/27))),3)) + ...
     (0.5*nthroot((Tt - (sqrt(-Delta/27))),3)) -(1/3*T)  );

A: The function nthroot makes a call to the function eps in its code, passing it the class of a variable which should have the same class as your first input argument to nthroot. As the documentation for nthroot specifies, it only supports single and double precision inputs, so your first argument to the function likely isn't one of those (my guess is it's probably an integer type, so you will have to convert to single or double).


text:
Q: NTP time synchronization in offline machines I have a couple of offline nodes in a cluster. I want their time to be synchronized, so I configured one of the nodes to be the NTP server.
This is the configuration file of my NTP server:
# node's ip:192.168.17.11
driftfile /etc/ntp.drift
server    192.168.17.11
fudge    192.168.17.11 stratum 1
restrict 192.168.17.0 mask 255.255.255.0 nomodify notrap
restrict -4 default kod notrap nomodify nopeer noquery
The problem is that the other machines can not synchronize their time with this machine.
Is this configuration file correct for acting as NTP server?
Thank you,
Ali

A: Using 127.0.0.1 as the server IP you are not allowing other compututers in the LAN to communicate with the NTP server.
Try changing 127.0.0.1 by the LAN IP of the server in the configuration file.


text:
Q: Warnings when building a .NET application using Google API I've an application that uses Google Drive API with .NET 4.0. When I build the application I get three warnings:

Warning 3 Unable to find dependency 'GOOGLE.APIS' (Signature='(null)'
  Version='1.8.1.31687') of assembly 'Google.Apis.Drive.v2.dll'
  D:\Documents\Visual Studio 2013\Projects\FFP Extended
  1.0\FFPXInstaller\FFPXInstaller.vdproj
Warning 2 Unable to find dependency 'GOOGLE.APIS.CORE'
  (Signature='(null)' Version='1.8.1.31685') of assembly
  'Google.Apis.Drive.v2.dll' D:\Documents\Visual Studio
  2013\Projects\FFP Extended 1.0\FFPXInstaller\FFPXInstaller.vdproj
Warning 1 Unable to find dependency 'ZLIB.PORTABLE'
  (Signature='(null)' Version='1.9.1.9000') of assembly
  'Google.Apis.dll' D:\Documents\Visual Studio 2013\Projects\FFP
  Extended 1.0\FFPXInstaller\FFPXInstaller.vdproj

The installed application seems to work fine, but, obviously, I'd rather not have any warning when it's compiled. Has anyone seen anything similar? If so, have you solved the problem?

A: The installer project FFPXInstaller.vdproj has some references to the assemblies mentioned in the warnings. Probably these files are from a prerequisite that reside in another folder then specified in the project, or don't exist at all.
Check the project references to see what goes wrong. Check if the assemblies with a warning sign actually exist in the path specified and that their versions match. If not, download them. and place them in the right folder.


text:
Q: Why does Sequelize think my models are not associated? I am trying to make a Sequelize query but it keeps telling me that my models are not associated. Yet I do declare an association... I guess I simply don't understand associations as well as I thought...
I made a repo which you can clone to see the problem for yourself: https://github.com/WaltzApp/sequelize-troubleshooting
I think the reason I am having this problem is that Sequelize doesn't support composite foreign keys, so I have to use a custom on clause in my join, but it's not working as expected since I can't specify the same join method in the associations themselves. That would explain why I sometimes get perfectly functional SQL printed out by Sequelize, but the query still fails (presumably because although the database query succeeds, converting the results to Sequelize entiteis fails).
A previous version of this reproduction effort is copied below as well:
Relevant Models
usersRoles:
module.exports = (sequelize, DataTypes) => {
  const usersRoles = sequelize.define('usersRoles',
    {
      key: {
        type: DataTypes.UUID,
        primary: true,
      },
      userUid: {
        type: DataTypes.UUID,
        allowNull: false,
      },
      roleUid: {
        type: DataTypes.UUID,
        allowNull: false,
      },
      oemUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      propertyManagerUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      tenantUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      [MORE FIELDS IRRELEVANT TO MY PROBLEM]
    },
    {
      tableName: 'usersRoles',
      indexes: [
        {
          name: 'userRoleOem',
          fields: ['userUid', 'roleUid', 'oemUid'],
          unique: true,
          where: {
            oemUid: { $ne: null },
            propertyManagerUid: null,
            tenantUid: null,
          },
        },
        {
          name: 'userRolePropertyManager',
          fields: ['userUid', 'roleUid', 'propertyManagerUid'],
          unique: true,
          where: {
            oemUid: null,
            propertyManagerUid: { $ne: null },
            tenantUid: null,
          },
        },
        {
          name: 'userRoleTenant',
          fields: ['userUid', 'roleUid', 'tenantUid'],
          unique: true,
          where: {
            oemUid: null,
            propertyManagerUid: null,
            tenantUid: { $ne: null },
          },
        },
        {
          name: 'compositePK',
          fields: ['userUid', 'roleUid', 'oemUid', 'propertyManagerUid', 'tenantUid'],
          unique: true,
        },
      ],
      freezeTableName: true,
      timestamps: false,
    });

  usersRoles.removeAttribute('id');

  usersRoles.associate = (models) => {
    models.usersRoles.belongsTo(models.oems, { foreignKey: 'oemUid' });
    models.usersRoles.belongsTo(models.propertyManagers, { foreignKey: 'propertyManagerUid' });
    models.usersRoles.belongsTo(models.tenants, { foreignKey: 'tenantUid' });
    models.usersRoles.belongsTo(models.users, { foreignKey: 'userUid' });
    models.usersRoles.belongsTo(models.roles, { foreignKey: 'roleUid' });
    models.usersRoles.belongsTo(models.invitations, { as: 'invitation', foreignKey: 'compositePK' });
  };

  return usersRoles;
};

invitations:
module.exports = (sequelize, DataTypes) => {
  const invitations = sequelize.define('invitations',
    {
      uid: {
        type: DataTypes.UUID,
        primaryKey: true,
      },
      guestUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      mappingGroupUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      invitedByUid: {
        type: DataTypes.UUID,
        allowNull: false,
      },
      adminUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      propertyManagerUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      tenantUid: {
        type: DataTypes.UUID,
        allowNull: true,
      },
      [MORE FIELDS IRRELEVANT TO MY PROBLEM]
    }, {
      tableName: 'invitations',
      freezeTableName: true,
      timestamps: false,
    });

  invitations.associate = (models) => {
    models.invitations.belongsTo(models.propertyManagers, { foreignKey: 'propertyManagerUid' });
    models.invitations.belongsTo(models.tenants, { foreignKey: 'tenantUid' });
    models.invitations.belongsTo(models.mappingGroups, { foreignKey: 'mappingGroupUid' });
    models.invitations.belongsTo(models.users, { as: 'guest', foreignKey: 'guestUid' });
    models.invitations.belongsTo(models.users, { as: 'invitedBy', foreignKey: 'invitedByUid' });
    models.invitations.belongsTo(models.users, { as: 'admin', foreignKey: 'adminUid' });
    models.invitations.hasMany(models.usersRoles, { as: 'invitation', foreignKey: 'compositePK' });
  };

  return invitations;
};

Notice above that I associate the invitations and usersRoles models with the line models.invitations.hasMany(models.usersRoles, { foreignKey: 'compositePK' }).
The Query
const path = require('path');
const glob = require('glob');
const Promise = require('bluebird');

const Sequelize = require('sequelize');
const configs = require('./test/_helpers/getConfigs');

const models = {};

const performQuery = (db) => {
  const { usersRoles, invitations } = db; // eslint-disable-line max-len

  const sql = {
    include: {
      model: invitations,
      as: 'invitation',
      on: {
        user: Sequelize.where(
          Sequelize.col('usersRoles.userUid'),
          '=',
          Sequelize.col('invitation.guestUid')),
        propertyManager: Sequelize.where(
          Sequelize.col('usersRoles.propertyManagerUid'),
          '=',
          Sequelize.col('invitation.propertyManagerUid')),
        tenant: Sequelize.where(
          Sequelize.col('usersRoles.tenantUid'),
          '=',
          Sequelize.col('invitation.tenantUid')),
      },
    },
  };
  return usersRoles.findAll(sql);
};

const sequelize = new Sequelize(
  configs.get('DB_NAME'),
  configs.get('DB_USER'),
  configs.get('DB_PSSWD'),
  {
    dialect: configs.get('DB_TYPE'),
    host: configs.get('DB_HOST'),
    port: configs.get('DB_PORT'),
  });

const modelsPath = path.join(__dirname, 'sequelize/models');
const globOpts = {
  cwd: modelsPath,
  ignore: '**/index.js',
  realPath: false,
  nosort: true,
  nodir: true,
};

glob('**/*.js', globOpts, (err, files) => {
  Promise.map(files, (file) => {
    const model = sequelize.import(path.join(modelsPath, file));
    models[model.name] = model;
  })
    .then(() => {
      Object.keys(models).forEach((modelName) => {
        if (models[modelName].associate) {
          models[modelName].associate(models);
        }
      });
      return performQuery(models);
    })
    .then((res) => {
      console.log('SUCCESS', res);
    }, (reason) => {
      console.error('FAILED', reason);
    });
});

The Output
FAILED { SequelizeEagerLoadingError: invitations is not associated to usersRoles!
    at Function._getIncludedAssociation (.../node_modules/sequelize/lib/model.js:573:13)
    at Function._validateIncludedElement (.../node_modules/sequelize/lib/model.js:489:53)
    at options.include.options.include.map.include (.../node_modules/sequelize/lib/model.js:385:37)
    at Array.map (native)
    at Function._validateIncludedElements (.../node_modules/sequelize/lib/model.js:381:39)
    at Promise.try.then.then (.../node_modules/sequelize/lib/model.js:1525:14)
    at tryCatcher (.../node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (.../node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (.../node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (.../node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (.../node_modules/bluebird/js/release/promise.js:693:18)
    at Async._drainQueue (.../node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (.../node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (.../node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:637:20)
    at tryOnImmediate (timers.js:610:5)
    at processImmediate [as _immediateCallback] (timers.js:582:5) name: 'SequelizeEagerLoadingError' }

Further attempt
I tried adding the following line to the invitations model:
models.usersRoles.belongsTo(models.invitations);

In this case, Sequelize prints some SQL which, when executed, works exactly as intended, but apparently it doesn't execute it properly because the query still doesn't work, instead saying SequelizeDatabaseError: relation "usersRoles" does not exist.

Executing (default): SELECT "usersRoles"."key", "usersRoles"."userUid",
  "usersRoles"."roleUid", "usersRoles"."oemUid",
  "usersRoles"."propertyManagerUid", "usersRoles"."doorSchedule",
  "usersRoles"."cardId", "usersRoles"."notifyBy",
  "usersRoles"."contactEmail", "usersRoles"."tenantUid",
  "usersRoles"."createdAt", "usersRoles"."compositePK",
  "usersRoles"."invitationUid", "invitation"."uid" AS "invitation.uid",
  "invitation"."status" AS "invitation.status", "invitation"."guestUid"
  AS "invitation.guestUid", "invitation"."firstName" AS
  "invitation.firstName", "invitation"."lastName" AS
  "invitation.lastName", "invitation"."email" AS "invitation.email",
  "invitation"."mobile" AS "invitation.mobile",
  "invitation"."mappingGroupUid" AS "invitation.mappingGroupUid",
  "invitation"."doorSchedule" AS "invitation.doorSchedule",
  "invitation"."invitedByUid" AS "invitation.invitedByUid",
  "invitation"."adminUid" AS "invitation.adminUid",
  "invitation"."acceptedAt" AS "invitation.acceptedAt",
  "invitation"."rejectedAt" AS "invitation.rejectedAt",
  "invitation"."propertyManagerUid" AS "invitation.propertyManagerUid",
  "invitation"."tenantUid" AS "invitation.tenantUid",
  "invitation"."contactEmail" AS "invitation.contactEmail",
  "invitation"."notifyBy" AS "invitation.notifyBy",
  "invitation"."createdAt" AS "invitation.createdAt",
  "invitation"."updatedAt" AS "invitation.updatedAt" FROM "usersRoles"
  AS "usersRoles" LEFT OUTER JOIN "invitations" AS "invitation" ON
  "usersRoles"."userUid"="invitation"."guestUid" AND
  "usersRoles"."propertyManagerUid"="invitation"."propertyManagerUid"
  AND "usersRoles"."tenantUid"="invitation"."tenantUid"; Query failure {
  SequelizeDatabaseError: relation "usersRoles" does not exist

A: You are never calling the Model.associate() method so the models aren't being associated with each other. The trick is that the associations may require models that have not yet been defined, so the associates have to come last. After you models are loaded loop through them and call model.associate(models) to create the associations.
The userRole definition also does not include an association to invitations. In Sequelize a relationship must be defined from the side you want to query from, or both if you plan to query the relationship from both objects. Since the invitations has many userRoles, I assume that userRoles belongs to an invitations. You reference the table as invitation in your query, so you probably want to alias the association with the as attribute.
userRoles
models.usersRoles.belongsTo(models.invitations, {
  as: 'invitation',
  foreignKey: 'compositePK',
});


text:
Q: Need a fool proof way to maintain and update a web application without messing it up I'm working on a simple social networking application and would be ready to launch it in soon. However I would like a way to properly maintain it as such that we would be making updates and adding new features to the application from time to time. I need some pointers on how to do it right as right now I have my application subversions using tortoise svn on a local server and every time I wish to upload it I do an export and upload the exported files to our remote server using a simple ftp.
Is there a better way to do this - I mean I don't want to make an upload and end up finding out that I accidentally overwrote a critical file that wasnt meant to be overwritten or so - I mean whats the proper way to do this.

A: I am used to having an ordinary working copy checked out on the web server. If a file does not exist in the repository, it should not be on the web. This way you can easily move the entire web around and create additional versions (like beta version on a different domain) without worrying about copying all the necessary files. And you can easily add new features without breaking the release version – simply work on the features in a separate branch, test the branch on a different URL and when you are ready, merge the branch back to trunk and update the trunk copy.
Of course there are some drawbacks to having the ordinary working copy checked out on the server, for example there are probably some files you do not want to be served over the web. This might and might not be an issue – I am working with Catalyst, so this does not bother me, as each request goes through the controller stack anyway.

A: You should create a pre-production mirror of your live system and deploy to that with a script. You can then check in that environment your changes haven't broken any functionality before deploying the code from pre-production to the actual production environment with another script.
Using source control to manage you development, pre-production and production environments is essential. SubVersion is a good choice and if you don't fancy the command line use TortoiseSVN.


text:
Q: Xcode simulator: "Unable to boot the simulator" macOS: 10.15.4 (19E287)
Xcode:  11.5 beta (11N605c)
Simulator:
Version 11.5 (921.9)
SimulatorKit 581.9.1
CoreSimulator 704.12.1
Error:

Log of /Users/rusakovic/Library/Logs/CoreSimulator/CoreSimulator.log
May  5 22:03:08 Maxs-MBP CoreSimulatorService[690] <Warning>: Device DF41FCC8-DA93-47CA-AD47-4EA67FB4D560 encountered in creation state at launch.  The device will be re-created.
May  5 22:03:08 Maxs-MBP CoreSimulatorService[690] <Notice>: Could not locate default .GlobalPreferences.plist for iOS 13.5 (13.5 - 17F5054f) - com.apple.CoreSimulator.SimRuntime.iOS-13-5
May  5 22:03:19 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.PowerManagement.control: launch_sim_register_endpoint: 0xfffffecc
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.SystemConfiguration.configd_host: launch_sim_register_endpoint: 0xfffffecc
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.audio.coreaudiod: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.SystemConfiguration.PPPController: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.audio.audiohald: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.coreservices.lsuseractivity.simulatorsupport: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.FSEvents: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.SystemConfiguration.configd: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator.Carousel: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator.SketchBoard: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator.SpringBoard: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator.SBRendererService: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.IOSurface.Remote: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator.HeadBoard: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service IndigoHIDRegistrationPort: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator.backboardd: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.metal.simulator.PineBoard: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.CoreSimulator.SimFramebufferServer: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Could not register service com.apple.CoreSimulator.host.bootstrap_port: launch_sim_register_endpoint: 0x44e
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error Domain=NSPOSIXErrorDomain Code=60 "Operation timed out" UserInfo={NSLocalizedDescription=Unable to boot the Simulator., NSLocalizedFailureReason=launchd failed to respond.}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error Domain=NSPOSIXErrorDomain Code=60 "Operation timed out" UserInfo={NSLocalizedDescription=Unable to boot the Simulator., NSLocalizedFailureReason=launchd failed to respond.}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error Domain=NSPOSIXErrorDomain Code=60 "Operation timed out" UserInfo={NSLocalizedDescription=Unable to boot the Simulator., NSLocalizedFailureReason=launchd failed to respond.}
May  5 22:03:27 Maxs-MBP com.apple.iphonesimulator[1433] <Error>: Error Domain=NSPOSIXErrorDomain Code=60 "Operation timed out" UserInfo={NSLocalizedFailureReason=launchd failed to respond., NSLocalizedDescription=Unable to boot the Simulator.}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=165 "Unable to lookup in current state: Shutdown" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutdown}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error looking up host support port: Error Domain=com.apple.CoreSimulator.SimError Code=165 "Unable to lookup in current state: Shutdown" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutdown}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=165 "Unable to lookup in current state: Shutdown" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutdown}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=165 "Unable to lookup in current state: Shutdown" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutdown}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error looking up host support port: Error Domain=com.apple.CoreSimulator.SimError Code=165 "Unable to lookup in current state: Shutdown" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutdown}
May  5 22:03:27 Maxs-MBP CoreSimulatorService[690] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=165 "Unable to lookup in current state: Shutdown" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutdown}

What I tried:
1.
rm -rf /Volumes/.../private/tmp
mkdir /Volumes/.../private/tmp
chmod 1777 /Volumes/.../private/tmp
chown root:wheel /Volumes/.../private/tmp

*Removing all devices in Xcode.

*Xcode reinstalling
/Applications/Xcode.app
/Library/Preferences/com.apple.dt.Xcode.plist
~/Library/Preferences/com.apple.dt.Xcode.plist
~/Library/Caches/com.apple.dt.Xcode
~/Library/Application Support/Xcode
~/Library/Developer/Xcode
~/Library/Developer/CoreSimulator

*Erase all from here
xcrun simctl erase all
But it's not working. Who could help to fix it?
Thank you in advance!


text:
Q: Overriding the login jsp in Liferay 7 In Liferay 7, I would like to override the login jsp.
As a first test, I've tried successfully to override the bottom-ext.jsp through the following link
https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/overriding-core-jsps
After that and because the login.jsp is not a core jsp in Liferay 7 but a module jsp, I've tried the following link :
https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/overriding-a-modules-jsps
But unfortunately after trying deploying* and starting, nothing has changed in my login view whereas I've added some custom html in the login.jsp file.
Does anyone has followed the previous tutorial successfully ?
For my failed test, I have :

*

*First retrieved the example project

https://github.com/liferay/liferay-blade-samples/tree/master/liferay-workspace/modules/blade.hook.jsp

*Next modified the login.jsp with custom html between lines 18 and 20

changed

Hello World

<c:choose>

*The Liferay Module Project seems not be deployed* because nothing is written in the Eclipse console during deployment. Usually, with my other project modules, I have the following message :

16:31:49,741 INFO  [pool-8-thread-2][BundleStartStopLogger:35] STARTED project.module_name_1.0.0 [864]
But not in this case...

A: hooks always remain in resolved state in liferay 7,
Also when u deploy that hook, nothing seems to be coming on the log, seems to indicate that your login portlet version is different.
Check your version in gogo shell & Replace it in this line in bnd.bnd
Fragment-Host: com.liferay.login.web;bundle-version="1.0.0"

When u deploy this, a message should come like  stopped & started login.web,
This is how JSP Fragments hook works.
The latest Liferay IDE 3.1.0 (December Release) provides option to create JSP fragment hook, try that if you are facing issues via BLADE CLI.


text:
Q: Bringing the (square) brackets to the same height Consider the .tex extract from below:
\begin{equation*}
A=U\Lambda U^T=\left[\begin{array}{ccc}
&   &  \\
u_1 & \cdots  & u_n \\
&  &
\end{array}\right]\left[\begin{array}{ccc}
 \lambda_1 &  &  \\
 & \ddots  &  \\
&  & \lambda_n
\end{array}\right]\left[\begin{array}{ccc}
& u_1^T  &  \\
& \vdots  &  \\
& u_n^T &
\end{array}\right],
\end{equation*}

As you may notice, the surrounding square brackets are not of the same height. How could one achieve the above expression with the same bracket height? (the expression within should be intact)

A: You can use some extra space by \\[3pt] for first and second lines.
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation*}
A=U\Lambda U^T=\left[\begin{array}{ccc}
&   &  \\[3pt]
u_1 & \cdots   & u_n \\[3pt]
&  &
\end{array}\right]\left[\begin{array}{ccc}
 \lambda_1 &  &  \\
 & \ddots  &  \\
&  & \lambda_n
\end{array}\right]\left[\begin{array}{ccc}

& u_1^T  &  \\
& \vdots  &  \\
& u_n^T &

\end{array}\right],
\end{equation*}
\end{document}


text:
Q: Олимпиадная задача. Выборы
На выборах в Государственную думу в избирательные бюллетени внесено N
  партий. Электронный сканер для считывания информации с бюллетеней
  передает информацию о каждом бюллетене в следующем формате: если в
  соответствующей клетке бюллетеня стоит пометка, то сканер передает +
  (плюс), в противном случае он передает - (минус). Таким образом, он
  передает последовательность из N символов - плюсов и минусов.
Бюллетень считается действительным, если пометка есть ровно в одной
  клетке. Недействительные бюллетени в подсчете результатов выборов не
  участвуют.
Партия проходит в Государственную Думу, только если она набирает не
  менее 7% от общего числа действительных бюллетеней.
Требуется вывести номера (в порядке их перечисления в бюллетене) всех
  партий, которые проходят в Государственную Думу.
Входные данные В первой строке входных данных содержатся два числа, разделенные пробелом: N - количество партий и M - количество
  бюллетеней. Оба числа натуральные, N <= 200, M <= 100 000.
В следующих M строках записана информация, полученная из бюллетеней.
  Каждая строка - последовательность из N символов + или - (без
  пробелов).
Гарантируется, что есть хотя бы один действительный бюллетень.
Выходные данные Выведите через пробел номера партий, прошедших в Думу, в порядке возрастания. Если ни одна из партий не проходит в
  Думу,  выводить ничего не нужно.

Мое решение выглядит так:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class main1 {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String str1 = reader.readLine();
        StringTokenizer stk1 = new StringTokenizer(str1," ");
        String []ar1 = new String[stk1.countTokens()];
        for(int i = 0; i<ar1.length; i++)
        {
            ar1[i] = stk1.nextToken();
        }
        //Выше - разбиение строки на массив
        int N = Integer.parseInt(ar1[0]); //Количество партий
        int M = Integer.parseInt(ar1[1]); //Количество бюллетеней
        int K = 0; //Количество действительных бюллетеней
        int[] result = new int[N]; //Количество голосов к партиям (0-я ячейка - первая партия, 1-я ячейка - вторая и т.д.)
        String[] P = new String[M]; //Бюллетени
        for (int a = 0; a < M; a++){
            P[a] = reader.readLine();
        }

        //Тут очистятся ячейки с недействительными бюллетенями, подсчитается количество действительных и распределятся голоса по партиям(result)
        for (int a = 0; a < P.length; a++){
            int i = 0;
            String parts[] = P[a].split("");
            for (int b = 0; b < parts.length; b++){
                if (parts[b].equals("+")) i++;
            }
            if (i != 1){
                continue;
            }else{
                K++;
                String parts1[] = P[a].split("");
                for (int b = 0; b < result.length; b++){
                    if (parts1[b].equals("+")) result[b] = result[b]+1;
                }
            }
        }

        //Проверяется условие (не меньше 7% от общего числа действительных бюллетеней) и выводится на экран через пробел
        for (int a = 0; a < result.length; a++){
            if (result[a] != 0){
                if ((result[a]*100)/K > 6) System.out.print(a+1+" ");
            }
        }
    }
}

Не прошу решить задачу. Укажите, пожалуйста, в чем моя ошибка. Мой вариант проходит только 1 тест из 23. Какие данные использует тестирующая система при проверке решения - неизвестно.

A: Тесты для олимпиадных задач учитывают время выполнения и количество используемой памяти, поэтому даже правильное решение может не пройти все тесты если не является оптимальным.
В вашем решении вы храните все исходные данные, хотя задача имеет решение не требующее такого объема памяти. Из всего набора исходных данных достаточно хранить только информацию о количестве бюллетеней и партий, а также текущем введенном бюллетене.
Upd:
Для начала исправим очевидное, не влияющее на ход решения.
Ваш вариант анализа строки описания бюллетеня использует памяти в трое больше чем необходимо (на самом деле еще немного больше, но это уже мелочи). Исправить это можно отказавшись от использования split("") который возвращает массив одно-символьных строк и вспомнить, что строка сама по себе массив и к ее элементам можно обращаться по индексу. Пример исправленного фрагмента (все переменные из исходного фрагмента ТС, оригинальные строки, требующие исправления, закоментированы):
int i = 0;
//String parts[] = P[a].split("");
//for (int b = 0; b < parts.length; b++)
for (int b = 0; b < P[a].length; b++)
{
    //if (parts[b].equals("+")) i++;
    if (P[a][b]=='+') i++;
}
if (i != 1)
{
    continue;//Переходим к обработке следующей строки
}
else
{
    K++;
    //String parts1[] = P[a].split("");
    for (int b = 0; b < result.length; b++)
    {
        //if (parts1[b].equals("+")) result[b] = result[b]+1;
        if (P[a][b]=='+') result[b] = result[b]+1;
    }
}

В принципе, одного этого изменения будет достаточно для уменьшения суммарной используемой памяти в 3 раза, что поможет пройти несколько больше тестов, но не все.
Следующим шагом необходимо избавиться от записи всех бюллетеней в массив строк и обрабатывать их по мере поступления. Заложенная в, предложенном ТС, коде идея алгоритма, позволяет внести соответствующие изменения достаточно безболезненно.


text:
Q: How to increase the timer before drive spins-down? I use Ubuntu 12 beta on a Lenovo Z575. I noticed that the disk spins down a few seconds after the last operation. When I am working, e.g. in the vim and write quite often, it spins-up and -down frequently. This causes vim to freeze for a second.
I used hdparm but it didn't change anything:
hdparm -S 24 /dev/sda # 2 minutes standby time

and I see (and hear) that the disk is idle or working:
hdparm -C /dev/sda
drive state is: standby
# or...
drive state is: active/idle

I have laptop-mode-tools already installed.

A: Maybe your computer works in laptop mode. To change the behaviour of laptop mode in Ubuntu you should change parameters in file /etc/laptop-mode/laptop-mode.conf . These parameters among others could affect you:
#
# Idle timeout values. (hdparm -S)
# Default is 2 hours on AC (NOLM_HD_IDLE_TIMEOUT_SECONDS=7200) and 20 seconds
# for battery and for AC with laptop mode on.
LM_AC_HD_IDLE_TIMEOUT_SECONDS=20
LM_BATT_HD_IDLE_TIMEOUT_SECONDS=20
NOLM_HD_IDLE_TIMEOUT_SECONDS=7200

#
# Power management for HD (hdparm -B values)
#
BATT_HD_POWERMGMT=1
LM_AC_HD_POWERMGMT=254
NOLM_AC_HD_POWERMGMT=254

Also in Debian distributions there could be some parameters in the file /etc/default/laptop-mode (but my Ubuntu 12.04 does not have this file).
There are some parameters that controls idle timeout that (here a citation):
AC_HD/BATT_HD
The idle timeout that should be set on your hard drive when laptop mode
is active (BATT_HD) and when it is not active (AC_HD). The defaults are
20 seconds (value 4) for BATT_HD  and 2 hours (value 244) for AC_HD. The
possible values are those listed in the manual page for "hdparm" for the
"-S" option.

There is additionally a kernel laptop mode. Computer that works in kernel laptop mode will be spinning disk up slower but it should not change the spinning down behaviour.
To check kernel laptop mode try:
cat /proc/sys/vm/laptop_mode
If the value is 1 or more it means the computer works in laptop mode. To disable laptop mode set it to 0.
A cite from https://www.kernel.org/doc/Documentation/laptops/laptop-mode.txt :
"The
result of this is that after a disk has spun down, it will not be spun up
anymore to write dirty blocks, because those blocks had already been written
immediately after the most recent read operation."
Additional information about the kernel laptop mode could be found at site given above.

A: Try hdparm -B 254 /dev/sda
My drive seems to ignore -S commands but listens to -B commands.


text:
Q: CanCan Ability in rails active_admin is can't Comments I use CanCan Ability in active_admin.I want to comment in page show.But I use CanCan is can't Add comments in show page.
This is error message:
You are not authorized to perform this action.

A: Configure the ActiveAdmin::Comment at ability.rb:
can [:read, :create], ActiveAdmin::Comment

I found the answer from this seemingly unrelated page https://github.com/ryanb/cancan/issues/597


text:
Q: Receiver stops when force close Hello I've made an app with a receiver to listen to incoming calls ,
My problem is that when i close (swipe off from list of apps) the receiver doesn't work anymore.
first thing i tried is the receiver itself defined in the android manifest like so:
<receiver
            android:name=".demo.CallReceiver"
            android:exported="true"
            android:enabled="true">
            <intent-filter android:priority="999">
                <action android:name="android.intent.action.PHONE_STATE"/>
            </intent-filter>
            <intent-filter android:priority="999">
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />

            </intent-filter>
        </receiver>

This works only when the app is open or in the background .
I looked online and saw this - https://stackoverflow.com/a/46889335/7079340
so i made a Service of my own like so (in the manifest):
<service android:name=".Service.CallService" android:enabled="true"
    android:exported="false"> <intent-filter>
    <action android:name="com.package.name.IRemoteConnection" />
</intent-filter>
</service>

and the class :
public class CallService extends Service {
    private static BroadcastReceiver m_Receiver;

    @Override
    public IBinder onBind(Intent arg0)
    {
        Log.e("SERVICELOG","bind");

        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("SERVICELOG","start command");

        return START_STICKY;
    }

    @Override
    public void onCreate()
    {
        Log.e("SERVICELOG","create");

        Receiver();
    }

    @Override
    public void onDestroy()
    {
        Log.e("SERVICELOG","destroy");
        try{
            unregisterReceiver(m_Receiver);}catch (Exception e){
            Log.e("SERVICELOG"," "+e.getMessage());

        }

    }

    private void Receiver()
    {
        m_Receiver = new CallReceiver();
    }
}

Started it in the oncreate of my Splashscreen and it prints the logs and it works !
Any way to make this work without a service I'm afraid of battery issues and so on ? Thanks !

A: When you close your app, it goes directly to onDestroy method. In your service code, you implemented this method. So, in your method you did stop your service programmatically. In short, you must remove it.

A: Android has had many changes from Marshmallow and above about apps that implicitly listener for broadcast in their manifest. The reasoning for this is because several apps would register for broadcast and a new process would be spun up for all the registered app's broadcast receiver to run in (very expensive) thus causing battery drain. What made this worse, was that users have no control over this behavior because the broadcast receiver couldn't be unregistered. To fix this, the engineering team behind Android, only allows for a select few broadcast to be implicitly registered. One is the Device Boot broadcast intent. By stopping apps from implicitly registering Broadcast's, apps have to be manually launched by the user to listen for intents they'd like to be notified of. This prevent several unnecessary apps from waking up to attempt to handle intent.
As for your concern, about "battery issues" I would recommend to you to use the preferred pattern of explicitly registering a BroadcastReciever in your Service and just performance tune to get your code to be as performant as possible. Services are definitely not free, but they aren't automatically heavy objects just by having one started and running; plus they do exist for this exact purpose. Just remember to not do unnecessary work in your service and you should be off to the right start.


text:
Q: Reformating the URL's generated by the routing system Hi I have been trying to solve a problem for quite a while that it is related to routing and links with no luck.
I have an application that stores a number of books. Each book has links that displays it's details. In order to get the details I am using the ID for each book in my link. This is the code for the link:
@Html.ActionLink(book.Name, "Details", new { bookId = book.Id , book = book.BookUrl })

When the user clicks one of the links this is the controller that is being called and I am not allowed to modify it:
 public ActionResult Details (int bookId){..}

And this is how my link will be displayed:
http://localhost:51208/Home/Details/C-sharp-5.0-in-a-Nutshell-The-Definitive-Reference/BookId-2

What I would like is someway to stop displaying the controler action and BookId.So my link would look something like this:
http://localhost:51208/C-sharp-5.0-in-a-Nutshell-The-Definitive-Reference

From what I can tell so far there is no way to do this using the standard functionality of routing so I figured I have to extend it's functionality somehow.
I have been reading about this in PRO ASP.NET MVC 4 and from what I have read I have to create a class and inherit from RouteBase.
This will result in having to implement two methods one is RouteData GetRouteData(HttpContextBase httpContext) and the other VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
So far I only understand that GetVirtualPath is responsible for generating the links so I figure this is where I would have to create the implementation to get the functionality I desire.
If this is the case can someone give me an idea on how I should implement this method?
If this is not the route to take then how can I achieve what I want?

A: You can put an extra route in your RouteConfig.cs as below:
    routes.MapRoute(
        "Book Details", // Route name
        "{ bookName }", // URL with parameters
             new { controller = "BookController",
                   action = "Details",
                   name = UrlParameter.Optional
                 } // Parameter defaults
        );

Change your Details method accordingly, but its parameter must be bookName.
Note :
Put this route at the bottom of all routes you have defined for avoiding ambiguity.

A: You could do this by implementing your own version of RouteBase.  You would need to implement both GetRouteData and GetVirtualPath.
Your implementation of GetRouteData would need to check your database of books to see if the URL contains the name of a book in your database, and then return the correct route data e.g.
public class BookRoute : RouteBase
{
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var url = httpContext.Request.AppRelativeCurrentExecutionFilePath;
        url = url.Replace(@"~/", "");

        var book = getBookWithTheNameThatMatchesTheUrl(url);

        if (book != null)
        {
            var rd = new RouteData(this, new MvcRouteHandler());
            rd.Values.Add("controller", "Home");
            rd.Values.Add("action", "Details");
            rd.Values.Add("bookId", book.Id);
            return rd;
        }

        return null;
    }

and your implementation of GetVirtualPath would need to do the opposite - find the name of the book with the given ID, and return the appropriate URL.
e.g.
public override VirtualPathData GetVirtualPath(RequestContext requestContext,
                                               RouteValueDictionary values)
{
    if ((string)values["action"] == "Details" &&
        (string)values["controller"] == "Home")
    {
        var bookId = (int)values["bookId"];
        var bookName = LookUpTheBookNameForTheBookWithThisId(bookId);
        return new VirtualPathData(this, bookName);
    }

    return null;
}

Lastly, add routes.Add(new BookRoute()); where you are registering the routes to enable this new route to be checked.
Given that the method getBookWithTheNameThatMatchesTheUrl() would hit the database for every page, you'd want to be caching the look-ups.


text:
Q: Unable to load namespaced class in PHP 5.3.27 I have an issue where I seem to be unable to load a namespace that I have created. I have read a bit about namespaces on SO, but I can't see what I am missing in this case.
This is my calling code:
<?php

use \CRMPicco\User\AlertReminder;
$alert_reminder = new AlertReminder($userObj);

?>

This is my namespaced code:
<?php
namespace CRMPicco\User;

class AlertReminder
{

}

This is my error:

Fatal error: Class 'CRMPicco\User\AlertReminder' not found in
  /var/www/vhosts/dev/web/login.inc.php on line 324

Line 324 is the new AlertReminder line.

A: This was due to some classname cleansing in my custom autoloader, which prevented the class from loading.
I refactored the class into another package and it now works as expected.


text:
Q: Verifying that a string starts with a number (easy) OR exactly 3 letters? I'm trying to make a RegEx expression to verify that a field starts with either the number 3 - the easy part - or starts with three letters, then continues to be numbers
My expression so far is
^((3)[\d])|([a-zA-Z]{3}[\d])$
The expression stops you from doing anything BELOW 3, but it still lets you go over...
I've done some searching and can't find a topic that relates to the issue of having an exact amount of characters
And I'm having trouble with limiting it to exactly 3 letter characters. Unfortunately what I'm working with, it HAS to be RegEx and not another language.

A: ^(?:3|[a-zA-Z]{3})\d+$

verifies, that your string starts with either 3 or 3 letters and then is only followed by numbers (at least one) until the end of the string
See https://regex101.com/r/tD2nK4/3 for some positive and negative examples

A: This regex should do exactly what you want:
^((3)[\d])|([a-zA-Z]{3}[^a-zA-Z])

Please note that this regex can only cope with the ASCII alphabet.


text:
Q: Nanosecond plots using highstockJS I'm trying to plot oscilloscope time traces using highcharts/highstock. The problem is highstock only takes the xAxis as date values. I can't figure out how to force it to only use seconds (because then I could just change the label to nanoseconds).
Highcharts on the other hand can plot anything really but doesnt have the advanced data grouping features that I need to plot these long (and sometimes concatenated - i.e. SUPER long) time traces.
I could go server side with it but I don't think anything beats highcharts in terms of usability and flexibility.
Anyone have any advice?

A: Have you consider to modify labels, by formatter ?
http://api.highcharts.com/highstock#xAxis.labels.formatter
http://api.highcharts.com/highstock#highcharts.dateFormat()


text:
Q: Plotting 3 columns of rasters and saving into pdf with base R Sorry this example is not entirely reproducible (I do not provide exact input data), but hopefully the example will be clear.
In short, I would like to save three maps in a wide pdf format, so All three maps can be shown with a desired extent + there is an overarching title above (but I don't want it to take up half of the page).
I am really struggling with setting it up properly:
pdf("plots1.pdf",width = 30/2.54,height = 20/2.54)
par(mfrow = c(2,3))
layout(matrix(c(1,1,1,2,3,4), 2, 3, byrow = TRUE))
plot.new()
text(0.5,0.5,"Africa, Params_1",cex=2,font=2)
# plot.new()
# plot.new()
plot(r2_list[[1]], xlim = Region[[g]][1:2], ylim = Region[[g]][3:4],
     breaks=cuts, col = plasma(21), main = variable[1],legend=FALSE)
plot(wrld_simpl,add=TRUE)
plot(r2_list[[2]], xlim = Region[[g]][1:2], ylim = Region[[g]][3:4],
     breaks=cuts, col = plasma(21), main = variable[2],legend=FALSE)
lines(wrld_simpl)
plot(r2_list[[3]], xlim = Region[[g]][1:2], ylim = Region[[g]][3:4],
     breaks=cuts, col = plasma(21), main = variable[3])
lines(wrld_simpl)

dev.off()

I would also like to try to print 6 plots, again - with overarching titles but I fail miserably.
Help will be much appreciated.

A: Add heights= to your layout call.
layout(matrix(c(1,1,1, 2,3,4), byrow=TRUE, nr=2), heights = c(1, 8))
opar <- par(mar=c(0,0,0,0))
plot.new()
text(0.5,0.5,"Africa, Params_1",cex=2,font=2)
par(opar)
plot(1:20)
plot(3:99)
plot(1:2)

(Blue boundaries below added externally, for reference only.)
Without heights
If I remove the heights= from the code above, I see this:

With heights

(You will want to play with the actual values based on your canvas size, etc.)


text:
Q: Refreshing a date subroutine in an HTA application Could anyone tell me how I could use document.write to output the date and time from a subroutine, and also have it refresh every minute from when the application is executed? Here is the code I have so far.
Sub Window_OnLoad
Daterefresher
iTimerID = window.setInterval("DateRefresher", 100)
End Sub

Sub ExitProgram
    window.close()
End Sub
Sub DateRefresher()
DateInfo = DateInfo & Now & VbCrLf
DateInfo = DateInfo & Date & VbCrLf
DateInfo = DateInfo & Time & vbCrLf
End Sub

After that id like to call it in a div and have it update the time every minute.
I am very sorry ,I am new to VBS, and not an expert with HTML either. Please excuse my poor attempt here.
Thanks.

A: Try this code :

<title>Auto Refresh</title>
<HTA:APPLICATION
ID="objAutoRefresh"
APPLICATIONNAME="Auto Refresh"
SCROLL="auto"
SINGLEINSTANCE="yes"
>


text:
Q: Populate 1 dataframe based on values in another I am trying to append values into a new pandas dataframe (df_t2) by looping over df. Assign does not seem to work. Is there any other way to achieve this?
values = {'No': ['123','456'],
        'data1': [22000,25000]}

df = pd.DataFrame(values, columns = ['No', 'data1'])

Code to loop over dataframe (df) and copy it to df_t2:
for index, row in df.iterrows():
   df_t2["No"] = row['No']
   df_t2[str(row['point1']) = row['data1']

A: Try reading here:
https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html
import pandas as pd
values = {'No1': ['123','4562'], 'data1': [22000,21000] }

df_1 = pd.DataFrame(values , columns = ['No1', 'data1'])

values = {'No2': ['1231','456'], 'data2': [24000,25000] }
df_2 = pd.DataFrame(values , columns = ['No2', 'data2'])

all_values = np.concatenate([df_1.values,df_2.values])
new_df_2 = pd.DataFrame(all_values, columns = df_2.columns)


text:
Q: Coherence distributed cache expiry per Namedcache How can we set eviction policy/expiry per cache entry for any specific cache(NamedCache). For example, I may have two cache's configured, however want to set eviction policy based on time only for one of the cache.
As per the below config file, I require to set eviction only for "TEST2CACHE" cache for say, expiry after 1 day. How to do that?
Any pointers would be helpful. Thanks.
Here, is a sample of my coherence config xml file-

    <cache-mapping>
        <cache-name>TEST1CACHE</cache-name>
        <scheme-name>MyDistributedCache</scheme-name>
    </cache-mapping>

    <!-- Application Configuration Cache -->
    <cache-mapping>
        <cache-name>TEST2CACHE</cache-name>
        <scheme-name>MyDistributedCache</scheme-name>
    </cache-mapping>

</caching-scheme-mapping>

<caching-schemes>
    <distributed-scheme>
        <scheme-name>MyDistributedCache</scheme-name>
        <service-name>MyDistributedCache</service-name>
        <lease-granularity>member</lease-granularity>
        <backing-map-scheme>
            <read-write-backing-map-scheme>
                <internal-cache-scheme>
                    <local-scheme>
                        <unit-calculator>BINARY</unit-calculator>
                    </local-scheme>
                </internal-cache-scheme>
                <cachestore-scheme>
                    <class-scheme>
                        <class-name>spring-bean:myCacheStore</class-name>
                        <init-params>
                            <init-param>
                                <param-name>setEntityName</param-name>
                                <param-value>{cache-name}</param-value>
                            </init-param>
                        </init-params>
                    </class-scheme>
                </cachestore-scheme>
            </read-write-backing-map-scheme>
        </backing-map-scheme>
        <autostart>true</autostart>
    </distributed-scheme>
</caching-schemes>

A: You are using the same 'MyDistributedCache' schema for both caches, so if you'll add eviction policy it will affect both of them:
example:
<local-scheme>
  <unit-calculator>BINARY</unit-calculator>
  <expiry-delay>10d</expiry-delay>
  <flush-delay>1d</flush-delay>
</local-scheme>

I'll bet you don't want to create two almost identical schemes, so the solution could be to use Scheme Inheritance
Link to Coherence Documentation
at least you would be able to reuse parts of the cache.
Another option worth to check is to use expiration in the API, but I'm not sure if Coherence will actually clean the cache.
NamedCache.put(Object oKey,
           Object oValue,
           long cMillis)

see JavaDoc
I suggest to use different cache schemes.


text:
Q: Understanding Javascript getElementById to find asp.net control in a sharepoint form This is for my Sharepoint edit form:
I need to be able use the asp.net TextBox in my javascript:
<asp:TextBox runat="server" id="ff17{''}" text="{@Container_x0020_Qty}" __designer:bind="{ddwrt:DataBind('u',concat('ff17',''),'Text','TextChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Container_x0020_Qty')}" />

I'm trying to read it in my javascript as such:
var CCID = document.getElementById("ff17");

This doesn't work...
However if I copy what the page renders as the form's Id:
var CCID = document.getElementById("ctl00_m_g_64200ded_b593_468b_bca5_0ea023581b8a_ff17");

This works!
Is there a way I can get this to work without having to always figure out the ct portion?

A: I'm not sure how this will translate to sharepoint, but for normal asp.net pages I typically put a script like this in the head to get client ids:
<head runat="server">
    <script type="text/javascript" language="javascript">
        //ClientIDs for controls in naming containers that we'll want to use from javascript
        var Controls = {
            'ff17':<%="'" + ff17.ClientID%>',
                'othercontrol':<%="'" + othercontrol.ClientID%>'};
    </script>
</head>

The reason I factor it out like this is to avoid needing to re-render the id everywhere I might want to use it, and because I can reference this from included script files without having to pass them through the asp.net processor.  The Controls object is to avoid naming collisions (only one name to worry about).
The downside is the ugly string concatenation for the initial quote, because the simpler '<%=o.clientid%>' syntax doesn't work here.  Also, this doesn't work as well with master pages, where the head is in the master page but the controls you care about are in a detail page.  But you could certainly do this elsewhere in your page instead.

A: I'm not sure how sharepoint and bindings works. But in ASP.net you would do something like this.
var CCID = document.getElementById('<%= ff17.ClientID %>');

I'm not sure this will work, but it might point you in the right direction.


text:
Q: Download very large files (8GB+) - combining WCF and WebClient? I have quite some trouble creating a WCF service that supports downloads of very large files. I have read a lot of guides on how to set transferMode attribute to Streamed, increase all messageSize and bufferSize attributes to Int32.MaxValue, and still I have no luck. (I am also returning the stream as the message body via the MessageBodyMember attribute, and metadata is sent via the headers using the MessageHeader attributes).
If I set all these attributes, I can download smaller files fine, but when I try to download 1-2GB files I simply get a 400 bad request error which makes it rather hard to debug...
My service should ideally support file sizes of at least 8GB. Is this even doable with WCF? The various messageSize attributes of the web.config file seem to be limited to Int32.MaxValue which equals a maximum file size of 2GB.
From my studies I have found that it seems I will have to use WebClient.DownloadFile instead.
Files should only be available for download to users who have the required rights. With WCF my download method could take a token-parameter that the server could check and return the stream only if the user had rights to download the requested file. This does not seem straight forward using the WebClient approach. If anyone has some guidelines on how to do this (via the WebClient), I would very much appreciate it.
Ideally my WCF service should administer and provide user tokens and somehow bind to every individual file what tokens are currently legal (tokens should be usable only once). Download should then happen via the WebClient.
Thanks in advance for any clues.

A: You can do this in WCF.  Many moons ago I built a service that did this (we didn't have a web server as part of our configuration).  We used WCF streaming:
http://msdn.microsoft.com/en-us/library/ms733742.aspx

The strategy to deal with large payloads is streaming. While messages,
  especially those expressed in XML, are commonly thought of as being
  relatively compact data packages, a message might be multiple
  gigabytes in size and resemble a continuous data stream more than a
  data package. When data is transferred in streaming mode instead of
  buffered mode, the sender makes the contents of the message body
  available to the recipient in the form of a stream and the message
  infrastructure continuously forwards the data from sender to receiver
  as it becomes available.


text:
Q: Is it possible to forward or redirect from a servlet filter after the response has been committed? The logic is that the filter gets hit, the condition is not true, so it goes through the filter chain. After the response is committed, the filter gets hit, and the condition is now true (a request attribute was set). It goes in to execute the forward, but the page never forwards. I know this has something to do with the response being committed because I tested different logic where it forwards before it hits the chain for the first time, and it does forward successfully.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest)request;

    if (some condition equals true) {
        httpServletRequest.getRequestDispatcher("/home.jsp").forward(request, response);
        return;
    } else {
        chain.doFilter(request, response);
    }
}

Example from my deployment descriptor:
<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.filters.MyFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

A: You can achieve what you want by using a custom HttpServletResponse. You pass this wrapped HttpServletResponse down the filter chain. You can provide a local OutputStream that stores all the write requests, local variables to store the status code and headers. Once you are back in your filter you can then decide to perform the redirect or copy back the results from the local variables from the wrapper into the original ServletResponse (i.e. set the status code and header and copy the results from the local output stream into the servlet response's output stream).
Edit:
Refer to the Programming Customized Requests and Responses section for a code example which uses a CharResponseWrapper. The example uses a custom Writer, but it can be easily extended to an OutputStream. Based on how your Servlet is used, you need to override one or both of getWriter() and getOutputStream() to delay committing anything onto the original response. In addition, you will need to override isCommitted() to return false, so that the forward can be executed at any time down the filter chain. You will also need to override resetBuffer() to initialize a new OutputStream/Writer to store the new content (including headers) after the redirect/forward.

A: The "committed" status of an HttpServletResponse is really a way of saying whether the response headers have been written to the underlying socket.  A "committed" response has had (at least) the first line written.  Since the first line of the response contains the status code, it follows that you cannot change the status code of a committed response ... and that means it is too late to change the status to 3xx to do a redirect.  Similarly, you cannot do a local forward because you've already started sending the response.


text:
Q: verbose_name_plural unexpected in a model? I've been doing some models of a future app, and, after adding verbose_name and verbose_name_plural to every entry on a working model, for making it 'beautiful', I've found that at validate time, Django doesn't like that, so it says:
  File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 4, in <module>
    class Concursante(models.Model):
  File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 7, in Concursante
    nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50)
TypeError: __init__() got an unexpected keyword argument 'verbose_name_plural'

My model begins like this:
# -*- encoding: utf-8 -*-
from django.db import models

class Concursante(models.Model):
    nombre = models.CharField(verbose_name='Nombre', max_length=30)
    apellidos = models.CharField(verbose_name='Apellidos', max_length=50)
    nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50)

Why 'he' didn't expects a plural verbose name there? Cannot live together with verbose_name?
FYI, this are my software versions:

*

*Ubuntu 8.04

*Python 2.5.2

*Django "1" "0" "final"

*Django ubuntu package version "1.0-1ubuntu1"

A: There is no verbose_name_plural.  It does not make sense to have both singular and plural for one field.  They are mutually exclusive.  In Django, they share the same name: verbose_name.
If your data represents multiple items (e.g. in a one-to-many relationship) use a plural form in verbose_name.  Otherwise, if your data represents a single item, use a singular form.
Verbose name fields in the Django documentation provides some examples.

A: Unfortunately, verbose_name_plural is not an option on the field. It's a meta option for the model itself. A field has no plural name since, unless it's a many-to-many relationship (in which case Django will use the plural for the model pointed to by the relationship), there's only one entity in that field.
Here's the doc section: http://docs.djangoproject.com/en/dev/topics/db/models/#id3


text:
Q: Evaluating the Nullity of Linear Transformation $T^2$ If $T$ is a Linear Transformation from $\mathbb{R^5} \to \mathbb{R^{5}}$ such that
$T^2 = 0$ if $x,y,z \in \mathbb{R}$ such that $x^2 + y^2 + z^2 =1$ then show that
$T(x,y,z,0,0) = (0,0,0,0,0)$
Since $T^2 =0$   ;  $\text{Rank T} \le \text{Nullity T}$ Now using Rank Nullity theorem I get
Rank T $\le  5/2$ at this point I am stuck  I don't know how can I use the condition $x^2 + y^2 + z^2 =1 $ to prove the given result.
Can anyone please help me here ?
Thank you.


text:
Q: What is the purpose of 'to be' in this sentence and is it grammatically incorrect if it is omitted?
It (Parasite) is the first-ever South Korean film to be nominated for an Oscar.

A student of mine asked me why there is 'to be' in this sentence.
What is the purpose of 'to be' in this sentence and is it grammatically incorrect if it is omitted?
So:

It is the first-ever South Korean film nominated for an Oscar.

A: There is a familiar pattern: the first [noun] to [verb phrase].  The verb phrase could be run in the Boston Marathon or it could be be nominated for an Oscar.  You can indeed omit to be without changing the meaning, but then the phrase no longer fits the pattern, and for that reason I think the sentence takes on a more literary register.

A: This is an adjectival verb phrase formed in the passive voice.  In this case, the verb in the adjectival phrase (to be) is not declined, but is kept to indictate that the subject is the target of the action.

A:
It (Parasite) is the first-ever South Korean film to be nominated for
  an Oscar.

"To be nominated for an Oscar" is an infinitival relative clause. This use (labeled as non-modal in CGEL) is rather special in that it usually requires words like : first, second, next, last .. It receives past interpretation - ..that was nominated/ to have been nominated.


text:
Q: Data migration MS SQL - MySQL in C# I've got a database files here. It's a MS SQL database (I think 2005). I need to do a migration to MySQL. But my problem is to read the data from this database. I'm not experienced in migration, so sorry if my question is not very ambitious. I think I'd like to write a short program in C# to read data and then copy to another database system. Am I correct ? Or does anybody know any freeware tool to do it ? Thank you for your help.

A: MySQL Workbench has ability to migrate between MS SQL Server and MySQL.
You probably have backup of database in zip file. First of all, restore it to Sql Server, because Workbench must connect to live database.
MySQL Workbench could be downloaded from here:
http://www.mysql.com/products/workbench/migrate/


text:
Q: Unproven inequality in textbook I was reading through the solution to a problem in a probability textbook and the author applied the following inequality without proving it: $$(1-\mathbb{P}(\text{Bin}(k,1/2)>s))^{t-1} \leq 2^{-|\Omega|(t\mathbb{P}(\text{Bin}(k,1/2)>s))}.$$
$\text{Bin}$ is the binomial distribution, and $s,t,k$ are natural numbers s.t. $t,k>0$, $0 < s < k$.
So the inequality above is equivalent to proving the following inequality,
$$(t-1)\log_2(1-\mathbb{P}(\text{Bin}(k,1/2)>s))\geq -|\Omega|(t\mathbb{P}(\text{Bin}(k,1/2)>s)).$$
I am not really sure how to proceed here. Any help would be appreciated.


text:
Q: How to use broadcast DATE_CHANGED? (android)          <receiver android:name="com.BillManager.DateChanged">
             <intent-filter>
                 <action android:name="android.intent.action.DATE_CHANGED"/>
                 </intent-filter>
         </receiver>

in class...
 if (action.equals(Intent.ACTION_DATE_CHANGED))
    {
          Log.d("DateChanged","DateChanged");
    }

Hello,
 I am devloping an Android app and I use this broadcast to announce when the user changes the date manually.
 For some reason I get the broadcast at 12:00 without changing the date manually.
 Does anyone have an explanation why is it?


text:
Q: Integrated (wp) blog not expanding it's 100% height container Intro:
I have a page designed simply with html and css, mostly just div's with css to mold the div boxes.
I want to integrate only the blog posts of a wordpress blog site into this page.  Everything in the design is to be the same except for one (large) div that contains the "imported" posts.  I do not want this div to contain it's own scrollbar, as if it's a window to the wp site.  I want the whole site to expand vertically, determined by the height of the wp blog posts, whatever they may be.
I have used the method provided here: http://moshublog.com/2005/07/05/integrate/2/
to incorporate the blog, this has worked.
Problem:
The div containing this the blog posts ("the loop") does not expand vertically.  It simply cuts the blog post(s) off as if they are not detected.  The height is set to 100% on the div containing it and any div's parent to that one.
Question:
How can the div containing the wp blog posts expand vertically based on the height of those blog posts?
What I've tried:
- - - Overflow:hidden;  I have floating elements on the page.  I have tried every possibility with overflow:hidden;, which was suggested in any other questions I could find.  This did not change anything.
- - - Making body and html height=100%.  This did not change anything.
- - - Changing the height of the div containing it and any of the parent div's to a fixed height.  This changed the height. If it was larger, then more of the blog posts were seen.  The posts are there, just cut off.
Here is the code:

            <?php if (have_posts()) : ?>
            <?php while (have_posts()) : the_post(); ?>
            <div class="post" id="post-<?php the_ID(); ?>">

            <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php
            the_title_attribute(); ?>">
            <?php the_title(); ?>

            Posted in <?php the_category(', ') ?> on <?php the_time('F jS, Y') ?>  by <?php the_author() ?> –
            <?php comments_popup_link('Be the first to comment', '1 Comment', '% Comments'); ?>
            <?php edit_post_link('Edit', ' | ', ''); ?>

            <?php the_content('read more »') ?>

            <?php if(is_single()) {?>
<?php the_tags('Tags: ', ', ', '
'); ?>
<?php } ?>

            <?php endwhile; ?>

            <?php next_posts_link('« Older Entries') ?>

            <?php previous_posts_link('Newer Entries »') ?>

            <?php else : ?>
            <?php include (TEMPLATEPATH . "/searchform.php"); ?>
            <?php endif; ?>

Everything below "wp blog code goes here" to "?php endif; ?" is from the wp blog site, and is "the loop".
Thank you.

A: Don't set the height of the divs, doing so will limit them to the height you set them, having said that, if you set the height to 100%, the div will fill 100% of the area of its container, not 100% of its contents, so for the outermost div this will be 100% of the window.


text:
Q: reverse video rotating sometimes IOS I'm using this library  Reverse-AVAsset-Efficient (https://github.com/whydna/Reverse-AVAsset-Efficient) to rotate videos.
It works perfectly. But If the video is recorded in phone and if I try to reverse it, I am getting the video in landscape [Orientation --> Left].
I want all videos in portrait (Same orientation as source file).
I am trying to explain is I am getting video rotated that I don't want. Please provide me solution.
Still you are not understanding try to reverse recorded video with this library. I've also attached images


text:
Q: R: renaming column names of dataframe with X and not V I have this simple code which creates a dataframe:
n = 5
p = 20
x=matrix(rnorm(n*p), nrow=n, ncol=p)
df=as.data.frame(x)

and I get this result of the data frame:
          V1         V2         V3         V4          V5          V6         V7         V8          V9        V10        V11         V12        V13        V14
1  1.8006821  0.2159150  0.2475421 -0.9591421 -0.05854140 -0.27782478 -0.5720555 -1.2093522 -1.34788746 -0.8452290 -1.5755013 -0.63180230  0.7267592  0.3079042
2 -1.2331962  0.3851325  0.7456002  0.6644699  0.43867770  0.52313129 -0.3429952  1.1231887 -0.78820594 -0.4749721 -1.1753511  0.44071083  0.5779413 -0.1477964
3 -1.3504110 -0.3694895  0.3419928  0.5078171 -0.88020980 -0.71862641  0.9641083 -2.7750092 -0.24178360 -0.1351366 -0.1801874 -0.08418993  0.7812341 -1.0273796
4 -0.3446066 -0.8032128 -0.7736583 -0.6863910  0.92667421 -0.06884001  0.5956594 -0.7848495 -0.09455081  0.3616341  0.3650726 -0.20903196 -0.8109611  0.2280463
5 -0.2685629 -0.8994275 -0.4956517 -1.0406881  0.01477389 -0.43855661 -0.5896001  0.1434798 -1.57407092  0.2337882  1.1170875  1.84402283  0.3901575  0.3403759
         V15        V16        V17         V18         V19         V20
1 -0.1450630 -0.7464377  1.3052135  0.29509627  0.09459443 -0.64872578
2 -0.5690047 -0.6694732 -0.1550677  0.15692547 -0.11672445 -0.07493947
3  0.3114352  1.4360456 -1.2353439  0.09812837 -0.66051299  1.00596707
4 -1.9778373 -0.6626688 -0.1474813 -0.41951635  0.80435969  0.40983722
5  0.1074216 -0.9764558  0.1439187 -0.51275394  0.44831639  1.18295229

Is there any way to rename automatically the column names of the data frame? Instead of using V1, V2,...V20 to be X1,X2...X20

A: Using sub() on the colnames should do
colnames(df) <- sub("V", "X", colnames(df))

df[, 1:5]

#           X1         X2         X3         X4         X5
# 1 -1.3082368  0.1279402 -0.5617098 -0.5270066 -0.1255816
# 2  0.6039559  0.4957135 -0.6753756 -0.3299313  1.6700390
# 3 -1.9705086  0.3714967 -0.8691308 -0.9567827  0.2744300
# 4 -0.7793934 -0.7170730  1.0079133  0.4428833 -0.4107202
# 5 -0.7248188  0.6195181  1.6373108  0.2425697 -2.7285534

As alistaire brought up piping, here's one way you could implement this in a pipe:
library(pipeR)

n = 5
p = 20
df <- matrix(rnorm(n*p), nrow=n, ncol=p) %>>%
  as.data.frame %>>%
  "colnames<-"(sub("V", "X", colnames(.))) %>>%
  (? str(.))

A: Would this work?
names(df) <- stringr::str_replace(names(df), 'V', 'X')
Or are you looking for some way to do it within the as.data.frame call?

A: purrr::set_names can take an anonymous function to apply to the names:
set.seed(47)
n = 5
p = 5
x = matrix(rnorm(n * p), nrow = n, ncol = p)
df = as.data.frame(x)

purrr::set_names(df, ~sub('V', 'X', .x))
#>           X1          X2          X3          X4         X5
#> 1  1.9946963 -1.08573747 -0.92245624  0.67077922 -1.5661621
#> 2  0.7111425 -0.98548216  0.03960243 -0.08107805  0.2491482
#> 3  0.1854053  0.01513086  0.49382018  1.26424109 -0.3404160
#> 4 -0.2817650 -0.25204590 -1.82822917 -0.70338819  0.4171908
#> 5  0.1087755 -1.46575030  0.09147291 -0.04057817 -0.3264668

It's particularly handy mid-pipeline.


text:
Q: Python code to sum a series incrementally Great site, and I really appreciate all the answers and tips I get from here. I'm trying to calculate the sum of a series INCREMENTALLY of fractions, but cant seem to get the loop-in-a-function right. I have been able to write the program to calculate the total sum, and to calculate the individual fractions in the series, but I need it to display the running sum at each step in the string. the series is 1/2, 2/3, 3/4, 4/5, ...., 20/21. so that it displays:
0.5000
1.1667
...
16.4023
17.3546
This is what I have so far:
def frac(n, d):
    a = n / d
    return a

def main():
    count = 1
    while count <= 20:
        num = count
        den = count +1
        ans = frac(num, den)
        print(num, "    ", format(ans, ".4f"))
        count += 1
main()

But it only gives me this:
1      0.5000
2      0.6667
3      0.7500
4      0.8000
5      0.8333
6      0.8571
7      0.8750
8      0.8889
9      0.9000
10     0.9091
11     0.9167
12     0.9231
13     0.9286
14     0.9333
15     0.9375
16     0.9412
17     0.9444
18     0.9474
19     0.9500
20     0.9524

A: I don't know python at all, but it seems the step you have missed is to factor in the previous answer in each iteration. So you could do:
def main():
    count = 1
    ans = 0
    while count <= 20:
        num = count
        den = count +1
        ans = ans + frac(num, den) #add previous ans here
        print(num, "    ", format(ans, ".4f"))
        count += 1

A: You can also use itertools.accumulate to generate these values:
from itertools import accumulate
for i, ans in enumerate(accumulate(n/(n+1) for n in range(1, 21)), start=1):
    print(str(i).ljust(4), format(ans, '.4f'))

Output:
1    0.5000
2    1.1667
3    1.9167
4    2.7167
5    3.5500
6    4.4071
7    5.2821
8    6.1710
9    7.0710
10   7.9801
11   8.8968
12   9.8199
13   10.7484
14   11.6818
15   12.6193
16   13.5604
17   14.5049
18   15.4523
19   16.4023
20   17.3546

A: As many pointed out already, you missed out the accumulation of partial sums in your loop. Now, geeking out a little bit, and using list comprehensions, the same can be achieved like this:
fractions = [ float(x)/(x+1) for x in range(1,21) ]
cumulatives = [sum(fractions[0:i+1]) for i,j in enumerate(fractions)]

for i,item in enumerate(cumulatives):
    print '{} {:.4f}'.format(i+1, item)

This is in python 2.7. Python 3.x itertools has function accumulate.
See it in action here: https://eval.in/658781
1 0.5000
2 1.1667
3 1.9167
4 2.7167
5 3.5500
6 4.4071
7 5.2821
8 6.1710
9 7.0710
10 7.9801
11 8.8968
12 9.8199
13 10.7484
14 11.6818
15 12.6193
16 13.5604
17 14.5049
18 15.4523
19 16.4023
20 17.3546

A: From what I can see you're not keeping track of your total sum anywhere, so just add a total variable before your loop and add to that (I also avoid while loops when a for loop will do the trick):
def frac(n, d):
    a = n / d
    return a

def main():
    total = 0
    for num in range(1, 21):
        ans = frac(num, num+1)
        total += ans
        print(num, "    ", format(ans, ".4f"), 'total=', format(total, ".4f"))
main()

Output looks like this:
1      0.5000 total= 0.5000
2      0.6667 total= 1.1667
3      0.7500 total= 1.9167
4      0.8000 total= 2.7167
5      0.8333 total= 3.5500
6      0.8571 total= 4.4071
7      0.8750 total= 5.2821
8      0.8889 total= 6.1710
9      0.9000 total= 7.0710
10      0.9091 total= 7.9801
11      0.9167 total= 8.8968
12      0.9231 total= 9.8199
13      0.9286 total= 10.7484
14      0.9333 total= 11.6818
15      0.9375 total= 12.6193
16      0.9412 total= 13.5604
17      0.9444 total= 14.5049
18      0.9474 total= 15.4523
19      0.9500 total= 16.4023
20      0.9524 total= 17.3546


text:
Q: Regular Expression to get a string between parentheses and inside the string literal in Javascript let s =  "Cannot add or update a child row: a foreign key constraint fails (`testdb`.`products`, CONSTRAINT `products_ibfk_3` FOREIGN KEY (`category_id`) REFERENCES `product_categories` (`id`))"

here I need to extract the FOREIGN key inside the literal with parenthesis ex. extracted = "category_id". I don't know how to do with
regexp.
Anyone, can you help me?
Thank in advance for your great community support.

A:

let s =  "Cannot add or update a child row: a foreign key constraint fails (`testdb`.`products`, CONSTRAINT `products_ibfk_3` FOREIGN KEY (`category_id`) REFERENCES `product_categories` (`id`))";

let match = /FOREIGN KEY \(`([\w]*)`\)/.exec(s);
let extracted = match[1];
console.log(extracted);

Edit:
The pattern(/FOREIGN KEY (([\w]*))/) does extract "FOREIGN KEY (category_id)" and "category_id" from string. Please refer to this url.


text:
Q: Test Coverage fails on before insert / before update Apex trigger I have this very simple before insert / update trigger on Opportunity that auto-selects the Price Book based on a dropdown value containing Sales Office (State) location info.
Here's my Trigger:
trigger SelectPriceBook on Opportunity ( before insert, before update ) {

    for( Opportunity opp : Trigger.new ) {
        // Change Price Book
        // New York
        if( opp.Campus__c == 'NYC' )
          opp.Pricebook2Id = PB_NYC; // contains a Pricebook's ID

        // Atlanta
        if( opp.Campus__c == 'ATL' )
          opp.Pricebook2Id = PB_ATL; // contains another Pricebook's ID
    }
}

Here's my Test Class:
@isTest (SeeAllData = true)
public class SelectPriceBookTestClass {

    static testMethod void validateSelectPriceBook() {

        // Pricebook IDs
        ID PB_NYC =  'xxxx';
        ID PB_ATL =  'xxxx';

        // New Opp
        Opportunity opp = new Opportunity();
        opp.Name = 'Test Opp';
        opp.Office__c = 'NYC';
        opp.StageName = 'Quote';

        // Insert
        insert opp;

        // Retrive inserted opportunity
        opp = [SELECT Pricebook2id FROM Opportunity WHERE Id =:opp.Id];
        System.debug( 'Retrieved Pricebook Id: ' + opp.Pricebook2Id );

        // Change Campus
        opp.Office__c = 'ATL';
        // Update Opportunity
        update opp;

        // Retrive updated opportunity
        opp = [SELECT Pricebook2id FROM Opportunity WHERE Id =:opp.Id];
        System.debug( 'Retrieved Updated Pricebook Id: ' + opp.Pricebook2Id );

        // Test
        System.assertEquals( PB_ATL, opp.Pricebook2Id );

    }
}

The test runs report 0% test coverage.
Also, on similar lines I have another before insert trigger that sets the Owner of an Event same as the Owner of the parent Lead.  Here's the code:
trigger AutoCampusTourOwner on Event( before insert ) {

    for( Event evt : Trigger.new ) {
        // Abort if other kind of Event
        if( evt.Subject != 'Visit' )
            return;

        // Set Owner Id
        Lead parentLead = [SELECT OwnerId FROM Lead WHERE Id = :evt.WhoId];
        evt.OwnerId = parentLead.OwnerId;

    }
}

This, too, is causing 0% coverage - my guess is that it's got something to do with the for loops in both. I know I'm seriously flouting DML rules by invoking SOQL query inside a for loop, but for my purposes it should be fine as these Events are created manually and only one at a time - so there are no scopes of governor limits kicking in due to bulk inserts.
The code in both cases work 100%. Please suggest a fix for the test cases.

A: Have you tried trigger.old ?? My thinking is, when you update the office in your test class from NYC to ATL, the value 'NYC' will be in trigger.old, and that's what you want to check in your trigger.
I could be wrong since i'm new to apex too, but try it and let me know what happens.

A: For the first trigger don't do anything rather just create opportunity and execute like this.
Test class for SelectPriceBook
@isTest
    private class TriggerTestClass {

        static testmethod void selectPriceTest(){
            Opportunity opps = new Opportunity(
                Name= 'Test Opps',
                CloseDate = System.today().addDays(30),
                StageName = 'Prospecting',
                ForecastCategoryName = 'Pipeline',
                Office__c = 'NYC');
                insert opps;

                Opportunity opps2 = new Opportunity(
                Name= 'Test Opps 2',
                CloseDate = System.today().addDays(28),
                StageName = 'Prospecting',
                ForecastCategoryName = 'Pipeline',
                Office__c = 'ATL');
                insert opps2;
        }

    }

It will give you good test coverage and I don't know what are you trying to do in AutoCampusTourOwner!

A: i have test class for these
trigger ClientEmailTrigger on inflooens__Client_Email__c (after insert, after update, before insert, before update) {
ApexTriggerSettings__c setting = ApexTriggerSettings__c.getValues('Inflooens Trigger Settings');

if(setting != NULL && setting.ClientEmailTrigger__c == TRUE){

    AuditTrailController objAdt = new AuditTrailController();

    if(Trigger.isAfter){
        if(Trigger.isUpdate){
            System.debug('In Update Client Email Record');
            objAdt.insertAuditRecord(Trigger.newMap, 'inflooens__Client_Email__c', Trigger.new.get(0).Id, Trigger.oldMap);
        }

        if(Trigger.isInsert){
            objAdt.insertAuditRecord(Trigger.newMap, 'inflooens__Client_Email__c', null , null);
        }
    }
}

}


text:
Q: SAML IDP Login Form not prompted after local logout I am using spring saml sample application (by @vladimir schafer) to test my single sign on with an IDP. I am using IDP initiated single sign on. When I start the sign on process for the first time, I am able to get IDP login page and is successfully logged into the application. However, when I local logout and login again, it doesn't prompt me the IDP login form. It logs me in directly.
Am I missing something here? Or is this how the saml application supposed to work?
I want to local logout and when user logs in again, it should prompt the IDP login for.
I have edited securityContext.xml to include <security:logout logout-url="/j_logout" logout-success-url="/logout.jsp"/>, no luck.
My form action is /saml/logout?local=true
How can I achieve this?

A:
Am I missing something here? Or is this how the saml application
  supposed to work?

Yes, that's how the SAML supposed to work.

I want to local log out and when user logs in again, it should prompt
  the IDP login for.

No, you can't do it. If you want IDP prompt the login page, use global log out. For more details, local log out only invalidates your application session, not IDP session or other application sessions. Therefore, when to redirecting to IDP login page, it already has session information about who you are so you don't need to log in again.
Hope it helps,


text:
Q: Spring Boot logs not visible in minikube I've set up a simple Spring Boot application without any custom logging, so everything gets logged to the console.
This works fine when running it from my IDE.
The second thing is, that I wrapped this application, as a jar in a docker image. This image / container will simply run the jar with java -jar - and yet again, when running this Docker container locally, I can see all the Spring Boot logs in the docker container logs.
But for some reason, when I load this image in minikube, and when I start the deployment, service, and pod - the Spring Boot logs are missing in the pod / container logs.
Eg when I run
kubectl logs pod-name --all-containers

I see the container logs, but they do not contain Spring Boot logs.
I run the jar file within the Dockerfile like so:
CMD java $JAVA_ARGS -jar $TARGET_JAR_FILE

Any ideas what could be wrong? How do I get Spring Boot logs to be visible on minikube pod / container?

A: "With some troubleshooting, I see that the pod displays the container logs," - what exactly do you mean here? To see container logs in minikube/ kubernetes you always have to run kubectl logs pod-name, If the pod is formed from more than one container, you must also specify the name of the container you want to inspect: kubectl logs pod-name container-name or just set the --all-containers flag to include log lines produced by any of the containers in the Pod. Please specify which commands you have used.


text:
Q: why is my PipedOutputStream deadlocking? I am trying to implement a threaded circular buffer with PipedInputStream & PipedOutputStream but it is locking everytime when I get to mHead.write in the Decoder runnable. I thought there was no chance for deadlocks when using separate threads.
    private class DecoderTask implements Runnable{

    @Override
    public void run() {
        while(!mStop){
            try {
                    Log.d(TAG,"trying to write");
        mHead.write(decode( 0, 1000));
            mHead.flush();
            Log.d(TAG,"Decoded");
            } catch (DecoderException e) {
                Log.e(TAG,e.toString());
            } catch (IOException e) {
                Log.e(TAG,e.toString());
            }
        }
    }

}
private class WriteTask implements Runnable{

    @Override
    public void run() {
        while(!mStop){
            try {
                                 Log.d(TAG,"trying to read");
                 int read = mTail.read(mByteSlave, 0, mByteSlave.length);
                 mAudioTrack.flush();
                                 mAudioTrack.write(mByteSlave,0,read);
                                 Log.d(TAG,"read");
            } catch (IOException e) {
                Log.e(TAG,e.toString());
            }
        }
    }

}

//in some function
mTail = new PipedInputStream();
mHead = new PipedOutputStream(mTail);
mByteSlave = new byte[BUF];
mT1 = new Thread(new DecoderTask(), "Reader");
mT2 = new Thread(new WriteTask(), "Writer");
mT1.start();
mT2.start();
return;

edit:  here is the full source for my service http://pastie.org/1179792
logcat prints out :
trying to read
trying to write

A: I have experienced the same problem and resolved it by overriding the default PIPE_SIZE in the PipedInputStream(int) constructor. The method PipedOutputStream.write(byte[], int, int) blocks until all the bytes are written to the output stream. This might be a problem with the default PIPE_SIZE.
After all, size does matter ;-)

A: The program doesn't block, it's just very very slow and inefficient. It uses 100% CPU. The problem is if (mTail.available() >= mByteSlave.length) - this will return false in most cases, and so you get a busy loop in this thread. If you can get rid of this, do it. Then this problem is solved. If you can't, it gets more complicated...
There is another problem: PipedInputStream.read returns an int. You need to use:
int len = mTail.read(mByteSlave, 0, mByteSlave.length);
mAudioTrack.write(mByteSlave, 0, len);

Other than that, I couldn't find anything wrong in this code. My complete test case looks like this:
import java.io.*;
public class Test2 {
    PipedOutputStream mHead;
    PipedInputStream mTail;
    byte[] mByteSlave = new byte[1024];
    boolean mStop;
    public static void main(String... ar) throws Exception {
        new Test2().run();
    }
    void run() throws Exception {
        mTail = new PipedInputStream();
        mHead = new PipedOutputStream(mTail);
        Thread mT1 = new Thread(new DecoderTask(), "Reader");
        Thread mT2 = new Thread(new WriteTask(), "Writer");
        mT1.start();
        mT2.start();
    }
    class DecoderTask implements Runnable {
        public void run() {
            while (!mStop) {
                try {
                    mHead.write(new byte[3000]);
                    mHead.flush();
                    System.out.println("decoded 3000");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class WriteTask implements Runnable {
        public void run() {
            while (!mStop) {
                try {
                    int len = mTail.read(mByteSlave, 0, mByteSlave.length);
                    if (len < 0) break; // EOF
                    // mAudioTrack.write(mByteSlave, 0, len);
                    // mAudioTrack.flush();
                    System.out.println("written " + len);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

A: Just get rid of the test involving available(). The read will block anyway, and you have nothing better to do when there is no data.


text:
Q: My application runs fine on Android 10 but crashes on all other Android versions. In the emulator AND on the real device I am using Android studio. Even the simplest of apps that I make fail to run on Android versions below 10 (Android Q). I have two virtual devices. One virtual device that has API 29 runs everything nicely. The other one with API 26 (Android 8.0). My apps also fail to run on my LG G6 that runs Android 8.0. I don't possess an Android Q device to test the app outside the emulator on that version. When I open Logcat after the app crash on Android 8.0 virt. device I get a ridiculous amount of errors tracing back to some Java files like View, ViewGroup, ImageView, BitmapDrawable, etc. At this point, the app I'm trying to run is a mere image with a black background and a text field.
xml errors kotlin
I did choose API 15 as the minimum API, which is like freakin' Android 4.0.3 or something... The app should be able to at least run on versions above that.

A: Probably the image you're showing is too big, and resizing it will fix your problem. Which size is it (physical size, not filesize) and in which folder is it?
The issue can be the same as Android Studio Canvas: drawing too large bitmap


text:
Q: How to track how many users are using Apple Watch is there a way to track how many iOS-users do have (and use) an Apple Watch as well? Is it tracked via Google Analytics automatically or what do I have to do to achieve that?

A: I believe this Stack Overflow question answer yours.

The best you an do is set a BOOL to true in shared NSUserDefaults the first time the Watch app is run and then check for that value in your iOS app. All indications on the dev forums and publicly have been that there isn't a way to programatically know if a Watch has been paired.


text:
Q: Excel VBA that looks at a form field for text and line breaks and then text I'm working with legacy code here and I'm not sure how much I could or should change, but I have code that looks for something like "SIC CODE 4000"
However the data html database I pull it from (we use a copy and paste) has updated their code to have:
"SiC CODE
4000"
Currently the code is:
Const strSic = "SIC Code "

However I now need it to add line breaks.
I tried modifying the code to say:
Const strSic = "SIC Code" & Chr(10) & Chr(10) & Chr(10)

But I get a compile error saying "Constant expression required"
I tried using "SIC Code \n\n\n" but maybe I'm not thinking the right character for line break.
Any suggestions?

A: The code for a new line is vbNewLine:
Const strSic = "SIC Code" & vbNewLine & vbNewLine & vbNewLine

Update:
To be a bit more detailed see the VBA constants:

*

*vbNewLine = Chr(13)+Chr(10) on Windows and Chr(13) on Mac

*vbCr = Chr(13)

*vbLf = Chr(10)
So if you only need Chr(10) you should use vbLf (like Excel Hero's answer).

A: Try this:
Const strSic = "SIC Code" & vbLf & vbLf & vbLf

A: Yes vbNewLine is the correct code : )


text:
Q: My code to change the current directory in C++ keeps giving me the Segmentation Fault: 11 error Here is the code:
#include <iostream>
#include "unistd.h"
using namespace std;

int main(){

char *directory = NULL;

cout << "Enter the directory you want to enter: ";

//taking input
cin >> directory;

//changing the directory
chdir(directory);

return 0;
}

My compiler says that the error occurs at line 7 (char *directory = NULL;)
Any help with this would be appreciated.

A: It's got nothing to do with chdir(), rather the problem is that you are telling cin to write data via a NULL pointer.
The proper solution is to use a std::string to hold the path-string instead:
#include <string>
#include <iostream>
#include <unistd.h>

int main()
{
   std::string directory;

   std::cout << "Enter the directory you want to enter: " << std::endl;

   //taking input
   std::cin >> directory;

   //changing the directory
   chdir(directory.c_str());

   return 0;
}

A: use <> for file in compiler library
#include <iostream>
#include <unistd.h>  //
using namespace std;

int main()
{
   string directory;

   cout << "Enter the directory you want to enter: " << endl;

   //taking input
   cin >> directory;

   //changing the directory
   chdir(&directory[0]);

   return 0;
}


text:
Q: SMTP: \r\n\r (without second \n) as double newline I have SMTP parser that works mostly fine. There is a problem when receiving traffic from third party software that sends double newlines as "\r\n\r" (without the second "\n"). Currently such connections are terminated as non-compliant SMTP. Can somebody explain what exactly RFC says about such "funny" double newlines? Can I asume that software that sends data like that is doing something really wrong?

A: RFC2821. Section 2.3.7:

SMTP commands and, unless altered
  by a service extension, message
  data, are transmitted in "lines".
  Lines consist of zero or more data
  characters terminated by the sequence
  ASCII character "CR" (hex value    0D)
  followed immediately by ASCII
  character "LF" (hex value 0A).

http://www.ietf.org/rfc/rfc2821.txt
--Dave

A: Various operating systems have various representations for Newline characters. Check the instructions here on newline characters.. By the way its a common practice among programmers to use both the \n and \r together to prevent any conflicts on the system. You need to check which newline character is supported by your system. If its \r then you are getting both the required characters. But if its \n, then the error lies with the sender.


text:
Q: Characterization of the space of integrable functions stable under multiplication Let $Ω = (Ω,Σ_Ω,μ)$ be a measure space and let $L(Ω)$ be the space of integrable functions on $Ω$.
For $f ∈ L(Ω)$, set $L_f(Ω) = \{φ ∈ L(Ω);~f·φ ∈ L(Ω)\}$.
Has the space of all integrable functions stable under multiplication by integrable functions
$$\bigcap_{f ∈ L(Ω)} L_f(Ω)$$
a nice characterization when $Ω$ is an Euclidean space $ℝ^n$ equipped with the Lebesgue measure, say in terms of continuity? Are there characterizations for more general $Ω$?

A: Assuming $\mu(\Omega)<\infty$, this intersection is $L^\infty(\Omega)$, the set of bounded measurable functions.
It is clear that $L^\infty(\Omega)\subset L_f(\Omega)$ for any $f\in L(\Omega)$.
The other direction is trickier.
Let us denote the intersection by $I$.
If $f\in I$, then $f\in L_f(\Omega)$ and so $f^2\in L(\Omega)$.
But $f\in I\subset L_{f^2}(\Omega)$, so $f^3\in L(\Omega)$.
Carrying on like this, we have that $f^k\in L(\Omega)$ (or $f\in L^k(\Omega)$) for any $k\in\mathbb N$.
This implies that $f\in\bigcap_{p\in\mathbb N} L^p(\Omega)=L^\infty(\Omega)$.
Even if $\Omega$ has infinite measure, the argument above shows that $L(\Omega)\cap L^\infty(\Omega)\subset I\subset\bigcap_{p\in\mathbb N} L^p(\Omega)$.