text:
Q: How to divide the interval equally into 13 parts with Hive sql I have this problem when I need to  do some statistics. Given a HIVE table which contains two columns, min_price and max_price. Now I have to divide the interval that made up by min_price and max_price into 13 parts (or some other number).
How can I do it?
I've seen some answers using connect by in oracle but unfortunately not supported in Hive.
I'm very grateful if you can help me solve the problem.
Table that I got:(let's assume it only contains 2  rows.)
min_price    max_price
2834           3256
3054           3845

Results that I want to achieve:(13 rows for each row above, so 26 rows)
min_price    max_price
2834            2866
2866            2898
       ......
3223            3256     (13 rows)
3054            3114
       ......
3784            3845     (13 rows)

*Only retain Integer part for upper and lower bounds of each part.

A: You optimize this logic further. I just provided the idea and demonstrated that it works. See this demo:
set hivevar:parts_num=13; --define the number of parts required

with your_data as (--use your table instead of this
select stack(2,
2834,3256,
3054,3845
) as (min_price,max_price))

--query starts here
select min_price_calculated as min_price, max_price_calculated as max_price
from
(
select min_price, max_price, i, min_price+cast((i)*(max_price-min_price)/${parts_num} as int) as min_price_calculated, min_price+cast((i+1)*(max_price-min_price)/${parts_num} as int) as max_price_calculated
  from your_data d --use your table instead
     lateral view posexplode(split(space(${parts_num}),' ')) s as i,x
)s where s.max_price_calculated<=s.max_price

Result:
OK

min_price       max_price
2834    2866
2866    2898
2898    2931
2931    2963
2963    2996
2996    3028
3028    3061
3061    3093
3093    3126
3126    3158
3158    3191
3191    3223
3223    3256
3054    3114
3114    3175
3175    3236
3236    3297
3297    3358
3358    3419
3419    3479
3479    3540
3540    3601
3601    3662
3662    3723
3723    3784
3784    3845
Time taken: 0.449 seconds, Fetched: 26 row(s)


text:
Q: Validador Unique Yii2 para los pocos que utilizan este framework, estoy con un problema. No hay forma de que funcione correctamente el validador unique, al utilizarlo funciona y me tira el msj de error pero también lo valida al hacer un update, cosa que no debería y no me deja actualizar. He revisado en internet lo referido a scenarios y tampoco me funciona. Cree un scenario 'create' y sigue haciendo lo mismo o directamente no valida nada. Alguien sabe como resolverlo?
public function actionCreate()
    {
        $model = new Marcas();
        $model->scenario = 'create'; // única linea que agregue aca
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $datos = [
                'accion' => 'create',
            ];
            if ($model->save()) {
                echo Json::encode($datos);
            }
        } else {
            return $this->render('create', [
                'model' => $model
            ]);
        }
    }

public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())  && $model->validate()) {
            if ($model->save()) {
                Yii::$app->getSession()->setFlash('success',[
                    'message' => Html::encode('El registro se actualizo correctamente'),
                ]);
            }else{
                Yii::$app->getSession()->setFlash('error',[
                    'message' => Html::encode('El registro no se pudo actualizar'),
                ]);
            }
            return $this->redirect('index');
        } else {
            return $this->render('update', ['model' => $model]);
        }
    }

 public function actionValidation() {
        $model = new Temporadas;
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = 'json';
            return ActiveForm::validate($model);
        }
    }

y esto esta en el modelo
public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios['create'] = ['codigo','nombre', 'cuit'];
    return $scenarios;
}

public function rules()
{
    return [
        [['codigo','nombre'],'required'],
        ['codigo','unique','on' => 'create'],
        [['codigo'], 'string', 'max' => 2],
        [['nombre', 'color_marca'], 'string', 'max' => 50],
        [['cuit'], 'string', 'max' => 13],
    ];
}

Esta es la vista
<?php

use yii\helpers\Html;
use kartik\form\ActiveForm;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\widgets\Pjax;
use demogorgorn\ajax\AjaxSubmitButton;
use yii\web\View;

/* @var $this yii\web\View */
/* @var $model backend\models\Marcas */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php Pjax::begin(['id' => 'pjax-container']); ?>
    <?php $form = ActiveForm::begin(
        [
            'id' => $model->formName(),
            'enableClientValidation' => true,
            'enableAjaxValidation' => true,
            'validationUrl' => Url::toRoute('marcas/validation'),
            'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'd-none']],
            'errorSummaryCssClass' => 'alert alert-danger',
        ]
    ); ?>
    <?php echo $form->errorSummary($model); ?>

            <?= $form->field($model, 'codigo')->textInput(['maxlength' => true, 'autocomplete' => "off", 'autofocus' => true]) ?>

            <?= $form->field($model, 'nombre')->textInput(['maxlength' => true, 'autocomplete' => "off"]) ?>

            <?= $form->field($model, 'cuit')->textInput(['maxlength' => true, 'autocomplete' => "off"]) ?>

            <?php AjaxSubmitButton::begin([
                'label' => Yii::t('app', 'Guardar'),
                'useWithActiveForm' => $model->formName(),
                'ajaxOptions' => [
                    'type'=>'POST',
                    'url'=>$model->isNewRecord ? 'create' : Url::to(['update', 'id' => $model->codigo]),
                    'success' => new \yii\web\JsExpression('function(data){
                        data = JSON.parse(data);
                        if(data.accion=="create"){
                            toastr.success("Se registro correctamente")
                        }
                        $.pjax.reload({container:"#pjax-container"});
                    }')
                ],
                'options' => ['class' => 'btn btn-primary', 'type' => 'submit'],
                ]);
            AjaxSubmitButton::end(); ?>
            <?= Html::a(Yii::t('app', 'Cancelar'), ['cancelar'], ['class'=>'btn btn-danger']) ?>

    <?php ActiveForm::end(); ?>
    <?php Pjax::end(); ?>

Tambien he probado otras cosas que vi, pero nada funciona.
Esto lo estoy haciendo en un template avanzado no en el básico. No se que otro dato relevante puedo agregar porq la base de datos esta perfecta, a lo que yo voy es que el validador funciona correctamente, solo que quiero que no lo haga en el update, por eso cree ese scenario y no funciona. Ese es el unico codigo que agregue.

A: El problema está en actionValidation(), ya que si te das cuenta estás validando $model
public function actionValidation() {
    $model = new Temporadas; // -----> este es el model que estás validando
      //y que no tiene el scenario create

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = 'json';
        return ActiveForm::validate($model); // aquí lo validas
    }
}

Como habrás visto el model que validas no tiene el scenario create, por eso nunca te lo tomaba en cuenta.
puedes pasarlo como parametro el scenario de la siguiente forma
public function actionValidation($scenario) {
    $model = new Temporadas(['scenario' => $scenario]); // pasas el scenario
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = 'json';
        return ActiveForm::validate($model);
    }
}

En tu form tendrías que cambiar esto
<?php $form = ActiveForm::begin(
    [
        'id' => $model->formName(),
        'enableClientValidation' => true,
        'enableAjaxValidation' => true,
        'validationUrl' => Url::toRoute([
             'marcas/validation',
             'scenario' => $model->isNewRecord ? 'create' : 'default' // aquí es el cambio
         ]),
        'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'd-none']],
        'errorSummaryCssClass' => 'alert alert-danger',
    ]
); ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relaxing Flash security for local swf accessing local files Here's my situation - I have a 3D Engine written in C++ and DirectX. It uses Awesomium for GUI windows.
This allows me to use HTML and Javascript for the GUI, then render it within a 3D environment. Awesomium wraps the Chromium browser to render the HMTL. All working fine including SWF playback.
My problem comes when I try to communicate with the SWF movie with Javascript (Awesomium allows me to call Javascript from within my C++ application) and Actionscripts ExternalInterface. I get the dreaded security error. By adding various statements to the SWF file and adding the path to the SWF file to the flash player Global Security Settings list, it works.
Now I can't exactly expect my end users to all modify their flash player Global Security accordingly so I am hoping there is a workaround.
I have a local application, calling a local html file which loads a local swf file. My local application is communicating with this local SWF file, errr locally. No network transaction.
So why the sandboxing? Can I not tell the swf movie to trust a particular sender, my application? I am on flash 8/AS2 by the way.
Thanks for your help
Simon

A: I'm not sure these settings are applicable in your case, or if you already use them, but two things you can do to "relax" security for communication between ActionScript and JavaScript are:
In ActionScript: System.security.allowDomain("*")
In the <object> and/or <embed> tag for the swf in the HTML, set the allowScriptAccess parameter to "always".


text:
Q: How to inspect elements and click on Apple Script I'm pretty new with apple scripts, and I'm trying to change the focus mode in the system preferences via Apple Script (the shortcut way is not an option). And I found one script that enables the Don't Disturb mode. But it doesn't change the mode.
How can I inspect the window and click select the focus mode?
Here is the script:
        tell application "System Preferences"
            set current pane to pane "com.apple.preference.notifications"
        end tell

        delay 0.5

        tell application "System Events"
            tell application process "System Preferences"
                click radio button "Focus" of tab group 1 of window "Notifications & Focus"

                click checkbox 1 of group 1 of tab group 1 of window "Notifications & Focus"

                set theCheckbox to checkbox 1 of group 1 of tab group 1 of window "Notifications & Focus"
                tell theCheckbox
                    set theCheckboxStatus to value of theCheckbox as boolean
                    if theCheckboxStatus is true then
                        display notification "Do not disturb is on"
                    else
                        delay 0.2
                        display notification "Do not disturb is off"
                    end if
                end tell

            end tell
        end tell

And this is the window:


text:
Q: startSubscription never called in action I am trying to use meteor redux middlewares. Following the tutorials step by step, but have not managed to get it working so far. The problem seems to lie in startSubscription: I can never see the get() and subscribe() functions called, I slipped console calls inside that are empty both in the browser and in the server terminal.
// actions.js
import { Meteor } from 'meteor/meteor';
import { startSubscription } from 'meteor-redux-middlewares';
import FaucetRewards from '/imports/api/Rewards/Rewards.js';

export const HOME_REWARDS_SUBSCRIPTION_READY = 'HOME_REWARDS_SUBSCRIPTION_READY';
export const HOME_REWARDS_SUBSCRIPTION_CHANGED = 'HOME_REWARDS_SUBSCRIPTION_CHANGED';
export const HOME_REWARDS_SUB = 'rewards';

export const loadRewards = () =>{

  console.log("actions.loadRewards()"); // I can see this

  let sub = Meteor.subscribe(HOME_REWARDS_SUB); // I can see this in server console and in the sub variable below

  console.log(sub);

  console.log(FaucetRewards.find().fetch()); // Sub is not performed in time, so this is empty as expected

  return(
    startSubscription({
      key: HOME_REWARDS_SUB,
      get: () => {
        console.log("loadRewards.startSubscription.get()"); // I can never see this
        return (FaucetRewards.find().fetch())
      },
      subscribe: () => {
        console.log("loadRewards.startSubscription.subcribe()"); // I can never see this
        let subscription = Meteor.subscribe(HOME_REWARDS_SUB);
        return subscription;
      }
    })
  );

};

There might be some stupid thing I am overlooking. Can someone help me please?

A: I finally realized the problem.
First, I had a problem in my store.js file. Specifically, I had deleted by accident the lines related to createReactiveMiddlewares.

const {   sources,   subscriptions, } =
  createReactiveMiddlewares(Tracker);

Then, when implementing the actions.js, you have to be really careful about the naming of the actions AND also the Meteor.subscribe method, which has to be named according to the actions. Example bellow, if HOME_POSTS_SUB is equal to "home_randomName", it will not work, because the _SUBSCRIPTION_READY and _SUBSCRIPTION_CHANGED prefixes have to be coherent with the _SUB string value.

export const HOME_POSTS_SUBSCRIPTION_READY =
  'HOME_POSTS_SUBSCRIPTION_READY'; export const
  HOME_POSTS_SUBSCRIPTION_CHANGED = 'HOME_POSTS_SUBSCRIPTION_CHANGED';
  export const HOME_POSTS_SUB = 'home.posts'; // will work! //export
  const HOME_POSTS_SUB = 'home.randomName'; // spoiled!! //export const
  HOME_POSTS_SUB = 'posts'; // spoiled!!
export const loadHomePosts = () =>   startSubscription({
      key: HOME_POSTS_SUB,
      subscribe: () => Meteor.subscribe(HOME_POSTS_SUB),
      get: () => Posts.find().fetch(),
naming HOME_POSTS_... differently will give you a hell lot of troubles
  later. So, naming the actions correctly has an effect later when you
  use them in the reducer.js file:
export function home(state = initialState, action) {   switch
  (action.type) {
      case HOME_POSTS_SUBSCRIPTION_READY:
        return {
          ...state,
          ready: action.payload.ready,
          postsSubscriptionStopped: false,
        };
      case HOME_POSTS_SUBSCRIPTION_CHANGED:
        return {
          ...state,
          posts: action.payload,
        };
      case STOP_SUBSCRIPTION:
        return action.payload === HOME_POSTS_SUB
          ? { ...state, postsSubscriptionStopped: true }
          : state;
      default:
        return state;   } }


text:
Q: MYSQL SUM & GRAND TOTAL I am trying to get a GRAND TOTAL for the following mysql query. But am not having any luck, I am not so good at mysql yet.
SELECT SUM(ep_price)
FROM orders
WHERE date_shipped BETWEEN '2017-04-01' and '2017-04-30'
GROUP BY order_number

Query:
Result:

'152989', '93670.39999999998'
'157669', '159.5'
'165955', '45195'
'166054', '5030'
'166410', '29700'
'167023', '4530'
'167110', '9647.2'
'167152', '56620'
'167477', '46087.14'
'167483', '1690'
'167545', '3295'
'167563', '9144.550000000001'
'167566', '35036.67999999999'
'167736', '2015'
'167853', '1277.5'
'167971', '3695'
'167982', '5690.4'
'168063', '4316.4'
'168101', '3400'
'168330', '4686.9'
'168435', '725'
'168454', '4002.5'
'168455', '6372'
'168477', '1941'
'168590', '3625.5'
'168593', '18560.4'
'168704', '238'
'168706', '119'
'168870', '3340'
'168962', '2800'
'169019', '2050'
'169203', '1940'
'169207', '7500.51'
'169209', '3888.4'
'169212', '10006.5'
'169214', '5580'
'169230', '2742.5'
'169235', '33490.2'
'169371', '12400'
'169413', '671.6'
'169529', '2345'
'169642', '17480'
'169689', '1500'
'169731', '1602.9'
'169835', '567'
'169893', '535.2'
'169895', '431'
'170015', '143.2'
'170031', '431.8'
'170050', '233.7'
'170093', '3465'
'170157', '3070'
'170159', '6040'
'170176', '746.5'
'170260', '3195'
'170318', '4081.06'
'170323', '5400'
'170324', '2865'
'170418', '1815'
'170419', '3984'
'170451', '29775.2'
'170483', '184.7'
'170484', '996.4'
'170486', '1363.8'
'170549', '9975.75'
'170566', '5350'
'170599', '5978.5'
'170600', '5480.42'
'170603', '1309.95'
'170612', '9979.7'
'170619', '2194'
'170620', '32490'
'170661', '4075'
'170721', '1910'
'170735', '4950'
'170756', '19450'
'170758', '9250'
'170763', '285.8'
'170821', '1875'
'170849', '4950'
'170859', '3212.84'
'170865', '132.6'
'170991', '583.1'
'170992', '155.2'
'171108', '181.6'
'171111', '180.9'
'171113', '1481.1'
'171120', '332.8'
'171135', '3869.3199999999997'
'171200', '1175'
'171204', '288.1'
'171205', '261.5'
'171206', '256.6'
'171208', '221.6'
'171209', '815'
'171217', '14903.6'
'171262', '3910'
'171269', '545'
'171272', '273.1'
'171303', '976.25'
'171305', '3600'
'171309', '195.2'
'171310', '16959.13'
'171354', '1215'
'171382', '4500'
'171386', '86.9'
'171407', '511.5'
'171410', '2744.4'
'171412', '5634'
'171416', '5287.5'
'171417', '2063.3999999999996'
'171423', '150.2'
'171513', '4370.4'
'171566', '2747'
'171567', '134.7'
'171670', '2067'
'171676', '348.8'
'171677', '437.5'
'171717', '198'
'171728', '165.5'
'171767', '17430'
'171771', '865.8000000000001'
'171774', '3627.5'
'171831', '13987.5'
'171834', '142.4'
'171836', '1108.2'
'171837', '5199'
'171956', '254.9'
'171958', '1286.8'
'171962', '5586.4'
'171963', '4128.9'
'172067', '1690'
'172068', '5705'
'172069', '893.75'
'172074', '3795'
'172174', '1242'
'172214', '1411.2'
'172215', '568.8'
'172217', '1848.2'
'172219', '1985'
'172220', '22436'
'172244', '166.1'
'172245', '325.9'
'172246', '2395'
'172329', '1885.5'
'172333', '197.8'
'172338', '297.2'
'172341', '1126.5'
'172342', '138.3'
'172352', '388.3'
'172355', '160'
'172382', '244.2'
'172442', '3628.71'
'172448', '1050'
'172452', '213.2'
'172466', '292.6'
'172467', '180'
'172469', '407.1'
'172515', '965'
'172539', '3812.5'
'172602', '1649'
'172631', '514'
'172632', '552.8'
'172834', '250.7'
'172835', '360'
'172836', '0'
'172840', '0'
'172844', '815'
'172846', '2970'
'172902', '4635'
'172997', '143.9'
'172998', '174.7'
'173132', '210'
'173255', '290'
'173260', '565.9'
'173277', '115'
'173545', '672.1'
'173546', '225'
'173562', '215'
'173606', '445.6'
'173611', '228.4'
'173646', '238.61'
'173690', '755'
'173694', '15400'
'173706', '0'
'174028', '855'

So how can I add all of these order_numbers together in a grand total?
I will have multiple entries with the same order_number and ep_price but the distinction is the job_number. That's why I am using the GROUP BY order_number.
Thank you for your help.

A: Are you looking for ROLLUP?
SELECT SUM(ep_price)
FROM orders
WHERE date_shipped BETWEEN '2017-04-01' and '2017-04-30'
GROUP BY order_number WITH ROLLUP;

This will return on the last row the sum of all groups.


text:
Q: How to write software to read/write to USB device We have this USB device that we would like to communicate with. This specific device is listed in the Windows device manager as a 'USB Composite Device'. The details reveal that it has the following driver stack:

*

*\Driver\usbccgp

*\Driver\USBPcap

*\Driver\USBHUB3

I also took a look with UsbView. This reveals that it is a CDC device. It has 2 interfaces
The first:
    bInterfaceNumber:                  0x00
    bAlternateSetting:                 0x00
    bNumEndpoints:                     0x01
    bInterfaceClass:                   0x02  -> This is Communications (CDC Control) USB Device Interface Class
    bInterfaceSubClass:                0x02
    bInterfaceProtocol:                0xFF
    iInterface:                        0x05
         English (United States)  "RNDIS Communications Control"
      -> This is a Communications (CDC Control) USB Device Interface Class

The second:
    bInterfaceNumber:                  0x01
    bAlternateSetting:                 0x00
    bNumEndpoints:                     0x02
    bInterfaceClass:                   0x0A  -> This is a CDC Data USB Device Interface Class
    bInterfaceSubClass:                0x00
    bInterfaceProtocol:                0x00
    iInterface:                        0x06
         English (United States)  "RNDIS Ethernet Data"

It is not a virtual serial port though; that would be too easy.
My goal is to first find the device, then retrieve information about it, and then send data to it and read data back from it.
It took me some time and I have achieved the first two goals. The source code of UsbView was of great help. But now I have much trouble with the last part.
For example, I have looked at this page:
https://learn.microsoft.com/en-us/windows-hardware/drivers/usbcon/how-to-write-a-windows-desktop-app-that-communicates-with-a-usb-device
With this help I can now find the device and open it with the CreateFile function. But then it fails at the WinUsb_Initialize function. Probably because it is a composite device, right? But what else can i do?


text:
Q: Can I make this algorithm more efficient? This is a college homework.
I have to simulate 10 random dice rolls (between 1 - 6) and put them in a list, then create another list which will keep the amount of times each value was rolled. My output has to be like this:
   Your rolls: [6, 2, 3, 4, 5, 6, 3, 1, 5, 2]
   Number of rolls:
   1 -> 1
   2 -> 2
   3 -> 2
   4 -> 1
   5 -> 2
   6 -> 2

This is how my code turned out:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = []

print(f"Your rolls: {rolls}")
print("Number of rolls:")

rolls.sort()

for i in rolls:
    # Puts the amount of times each number (1-6) rolled inside roll_count
    roll_count.append(rolls.count(i))

    # Removes the duplicates so that the count doesn't register again
    while rolls.count(i) > 1:
        rolls.remove(i)

for n in range(1, 7):
    # Checks if the possible rolls (1-6) have been rolled, if not place the count as 0
    # in the sorted index inside roll_count
    if n not in rolls:
        roll_count.insert(n - 1, 0)

    print(f"{n} -> {roll_count[n - 1]}")

It works properly, but I wanted to know if I could make it more efficient or even simplify it.

A: The standard tool for this kind of task is a collections.Counter, from the standard library. It is purpose-built for precisely this task.
from collections import Counter
from random import randint

rolls = [randint(1, 6) for _ in range(10)]
roll_count = Counter(rolls)

print(f"Your rolls: {rolls}")
print("Number of rolls:")

for n in range(1, 7):
    print(f"{n} -> {roll_count[n]}")

Your rolls: [2, 5, 3, 3, 3, 2, 5, 5, 2, 6]
Number of rolls:
1 -> 0
2 -> 3
3 -> 3
4 -> 0
5 -> 3
6 -> 1

If for some reason you're not allowed to use collections.Counter(), your implementation is just about as good as it can be, with one exception - a dict is a better datastructure to use than a list for the roll count (indeed, collections.Counter is a subclass of dict). This enables you to use the setdefault() and get(key, default), which cuts out a few lines of code:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = {}

print(f"Your rolls: {rolls}")
print("Number of rolls:")

for i in rolls:
    roll_count.setdefault(i, 0)  # does nothing if element is already present
    roll_count[i] += 1

for n in range(1, 7):
    print(f"{n} -> {roll_count.get(n, 0)}")

A: from random import randint
rolls = []
roll_count = [0] * 6

for i in range(10):
    r = randint(1,6)
    rolls.append(r)
    roll_count[r-1] = roll_count[r-1] + 1

print(f"Your rolls: {rolls}")
print("Number of rolls:")

for n in range(1, 7):
    print(f"{n} -> {roll_count[n - 1]}")

Instead of looping once to form a rolls list and then loop once again to count each one, you can do this way to loop once and roll as well as count in the same loop.
And you don't need to sort as well or check if a count exists or not.

A: Since your range of values is so limited, there's no need to use any fancy collection to track them, and certainly no need to sort the input.  A simple list will do, initialized to all zeros.
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = [0] * 6

print(f"Your rolls: {rolls}")
print("Number of rolls:")

for i in rolls:
    # Puts the amount of times each number (1-6) rolled inside roll_count
    roll_count[i - 1] += 1

for n in range(1, 7):
    print(f"{n} -> {roll_count[n - 1]}")

Your rolls: [4, 1, 3, 3, 4, 3, 4, 5, 2, 2]
Number of rolls:
1 -> 1
2 -> 2
3 -> 3
4 -> 3
5 -> 1
6 -> 0


text:
Q: C++ Derived class array Reallocation Sorry for confusing the topic, this was the original question:

How to reallocate an array of pointers to base class, that actually
  point to different derived classes?

I shouldnt use dynamic cast, typeid or RTTI here if possible..
EDIT I just realized i could try saving the array elements and just setting the pointers in new array to old elements.. But then how to do operator= or Cctor?
Or:

How to reallocate this array 'the bad way', by actually copying the elements?

An example:
class Base {...}
class Derived1 : public Base {...}
class Derived2 : public Base {...}

int main()
{
  int arrayLength=0, arrayMaxLength=3;

  Base **array=new Base*[arrayMaxlength];
  array[0]=new Derived1();
  array[1]=new Derived2();

  //Reallocation starts...
  Base **tmp=new Base*[arrayMaxLength*=2];

  for(int i=0;i<arrayLength;i++)
    tmp[i]=new Base(*array[i]);      //<------ What to put here instead of Base?

  //The unimportant rest of Reallocation..
  for(int i=0;i<arrayLength;i++)
    delete array[i];
  delete [] array;
  array=tmp;
}

A: You should not need to do any casting (dynamic or otherwise): just reuse the pointers
Base **array=new Base*[arrayMaxlength];
array[0]=new Derived1();
array[1]=new Derived2();

//Reallocation starts...
Base **tmp=new Base*[arrayMaxLength*=2];

for(int i=0;i<arrayLength;i++)
  tmp[i]=array[i];

// ...

The objects are already allocated and have the proper type.  You can just copy the pointers themselves to the new array.
Note that you will have to be careful not to delete the (objects pointed to by the) pointers in the old array, as that would invalidate the ones in the new (the object pointed to by the stored pointers does not exist any more) -- just delete the original array iself.
If the management of pointers becomes burdensome, you can use some sort of shared pointer (the BOOST library offers a variety, for example)


text:
Q: is this looking stupid? inserting 2 form fields into mysql database safely hey so I have 2 input fields trying to get them to go into a database nicely been looking around trying to puzzle the thing together can someone nudge me in the right direction? :)
  <?php
    // Connect to server and select databse.
    mysql_connect("$subsc_hostname", "$subsc_username", "$subsc_password")or die("cannot connect");
    mysql_select_db("$subsc_database")or die("cannot select DB");

    // name and email from form fields
    $subsc_name=$_POST['sub_name'];
    $subsc_email=$_POST['sub_email'];

    // Atttempt to protect against MySQL injection
    $subsc_name = stripslashes($subsc_name);
    $subsc_email = stripslashes($subsc_email);
    $subsc_name = mysql_real_escape_string($subsc_name);
    $subsc_email = mysql_real_escape_string($subsc_email);
    $sql="SELECT * FROM subscribers WHERE subsc_name='$subsc_name' and subsc_email='$subsc_email'";
    $result=mysql_query($sql);

    // Mysql_num_row is counting table row
    $count=mysql_num_rows($result);

    // If result matched table row must be 1
    if($count==0){
    $sql="INSERT INTO subscribers(subsc_name, subsc_email)VALUES('$subsc_name', '$subsc_email')";
    }
    else {
    echo "Already Subscribed";
    }

    ?>

    <form method="post" action="">

        Full Name:
        <input class="form-control" type="text" name="sub_name" />

        Email:
        <input class="form-control" type="text" name="sub_email" />

                <input class="btn btn-success" type="submit" value="Subscribe" />

        </form>

A: Use prepared statements if you want to protect against sql injection. Also, don't use mysql, use mysqli or PDO.
For mysqli, see: http://php.net/manual/en/mysqli.prepare.php
For PDO, see: http://uk1.php.net/pdo.prepared-statements


text:
Q: Android Studio: Fixed footer that's locked to bottom I'm currently working on a layout in Android Studio but there's a problem that I need to fix..
I want to make my layout be locked to the bottom, just like Facebook which has a layout-bar at the bottom, no matter how much you scroll, it wont move.
Right now my code looks like this, but the "goButtonLayout" keeps going out of screen.. Anyone got an idea?
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:flatui="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
android:orientation="vertical"
android:nestedScrollingEnabled="true"
android:paddingBottom="20dp"
android:id="@+id/content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp"
    android:id="@+id/contentLayout">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:id="@+id/searchngo">

        <com.cengalabs.flatui.views.FlatEditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editBox"
            android:textColor="#fff"
            android:text="@+string/choose"
            flatui:fl_fontWeight="bold"
            flatui:fl_fieldStyle="0"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:longClickable="false"
            android:layout_marginBottom="2dp"
            android:layout_gravity="left"
            android:paddingRight="60dp"
            android:paddingLeft="12dp"
            android:paddingTop="12dp" />

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            flatui:fl_touchEffect="fl_ripple"
            android:text="@+string/addRow"
            android:id="@+id/newRow"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginLeft="16dp" />

    </LinearLayout>

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView3" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:paddingBottom="24dp">

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/search"
            android:id="@+id/test111"
            flatui:fl_touchEffect="fl_ripple"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginTop="16dp" />

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/search"
            android:id="@+id/test666"
            flatui:fl_touchEffect="fl_ripple"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginTop="16dp" />

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/search"
            android:id="@+id/test333"
            flatui:fl_touchEffect="fl_ripple"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginTop="16dp" />

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/search"
            android:id="@+id/test6532"
            flatui:fl_touchEffect="fl_ripple"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginTop="16dp" />

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/search"
            android:id="@+id/test6123"
            flatui:fl_touchEffect="fl_ripple"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginTop="16dp" />

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/search"
            android:id="@+id/test512"
            flatui:fl_touchEffect="fl_ripple"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginTop="16dp" />

        <com.cengalabs.flatui.views.FlatButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/search"
            android:id="@+id/test123123"
            flatui:fl_touchEffect="fl_ripple"
            flatui:fl_blockButtonEffectHeight="3dp"
            android:clickable="true"
            android:layout_marginTop="16dp" />

    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/goButtonLayout">

    <com.cengalabs.flatui.views.FlatButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/search"
        android:id="@+id/goButton"
        flatui:fl_touchEffect="fl_ripple"
        flatui:fl_blockButtonEffectHeight="3dp"
        android:clickable="true"/>

</LinearLayout>

A: Try like this better to use Relative Layout for this

A: Use a FrameLayout as your main layout.


text:
Q: Why am I getting the error "Cannot find source for binding with reference"? My WPF controls are not rendering as I expect. Specifically, when I assign a value to a dependency property of a user control, then that user control tries to use the value on one if its child controls, something goes wrong and the child control does not render as it should.
I've distilled the problem down to a simple example, presented below. I have created a RedBox user control, which displays its content inside a red border, and a BlueBox user control, which is supposed to display bound text in a TextBlock inside a RedBox. That last part fails. I suspect the trouble is on Line 35 of BlueBox.xaml, but that's just a guess.
RedBox.xaml
<UserControl
        x:Class="WpfApplication1.RedBox"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        mc:Ignorable="d">
    <ContentControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Border BorderBrush="Red" BorderThickness="4" Padding="4">
                <ContentPresenter Margin="3,0,0,0" Content="{TemplateBinding Content}" VerticalAlignment="Center" />
            </Border>
        </ControlTemplate>
    </ContentControl.Template>
</UserControl>

RedBox.xaml.cs
namespace WpfApplication1
{
    public partial class RedBox
    {
        public RedBox()
        {
            InitializeComponent();
        }
    }
}

BlueBox.xaml
<UserControl x:Class="WpfApplication1.BlueBox"
             x:Name="UserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:wpfApplication1="clr-namespace:WpfApplication1"
             mc:Ignorable="d">

    <Border BorderBrush="Blue" BorderThickness="4" Padding="4">

        <Grid>

            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Row="0" Grid.Column="0" Text="Show the BlueBox's Text property value:" />
            <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=UserControl, Path=Text}" />

            <TextBlock Grid.Row="1" Grid.Column="0" Text="Show static text within a RedBox:" />
            <wpfApplication1:RedBox Grid.Row="1" Grid.Column="1">
                <TextBlock Text="Static Text" />
            </wpfApplication1:RedBox>

            <TextBlock Grid.Row="2" Grid.Column="0" Text="Show the BlueBox's Text property value within a RedBox:" />
            <wpfApplication1:RedBox Grid.Row="2" Grid.Column="1">
                <TextBlock Text="{Binding ElementName=UserControl, Path=Text}" />
            </wpfApplication1:RedBox>

        </Grid>

    </Border>
</UserControl>

BlueBox.xaml.cs
using System.Windows;
using System.Windows.Input;

namespace WpfApplication1
{
    public partial class BlueBox
    {
        public BlueBox()
        {
            InitializeComponent();
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
            name: "Text",
            propertyType: typeof(string),
            ownerType: typeof(BlueBox),
            typeMetadata: new PropertyMetadata());
    }
}

MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfApplication1="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <wpfApplication1:BlueBox Text="Hi!" />
</Window>

If I could post a screenshot of the runtime MainWindow, you'd see that all dependency properties are wired-up correctly, but where there should be a red box with "Hi!" in it, there simply isn't one. The Output window gives me this error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=UserControl'. BindingExpression:Path=Text; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

In researching the error "Cannot find source for binding with reference" I've found that a frequent cause of the error is that people try to bind to something that isn't in the visual tree of the object they're binding to. But I don't think that's my problem here because the BlueBox is within the visual tree of its own TextBlock control, isn't it?
What, then, is going on?
Update:
I have discovered that if I replace line 35 of BlueBox.xaml with the following, it works:
            <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type wpfApplication1:BlueBox}}, Path=Text}" />

This solves my problem. I'm still baffled why the ElementName syntax didn't work, though. I'd appreciate any insight into that.

A: Your dependency property Text is type of String. But you registered its default value as PropertyMetadata() of an unspecific type. Either don't provide a type metadata, or give it a proper one, like: new PropertyMetadata("default value")
Change this part of your code:
public static readonly DependencyProperty TextProperty =
       DependencyProperty.Register(
             name: "Text",
             propertyType: typeof(string),
             ownerType: typeof(BlueBox),
             typeMetadata: new PropertyMetadata());

To this:
public static readonly DependencyProperty TextProperty =
       DependencyProperty.Register(
             name: "Text",
             propertyType: typeof(string),
             ownerType: typeof(BlueBox));

This might resolve your problem.


text:
Q: PHP: http_get undefined reference. Ubuntu Karmic Koala I am trying to use the http_get function. But I get a undefined reference error. I understands that this means the function can not be found. However I do no know how to fix this? Could somebody help?
Cheers

A: O.k so I sorted it out.
I used pecl:
user@user:~$ sudo pecl install pecl_http

Unfortunately this gave me an error which wanted me to install libcurl. Thus I installed it with:
user@user:~$ sudo aptitude install libcurl4-openssl-dev

After that I tried pecl again:
user@user:~$ sudo pecl install pecl_http

It work, but I had to add:
extension=http.so

in my php.ini file.
After all those steps it worked.
To me it seems that everybody knows that this is what you should do to fix it. It stumps me that nobody has actually documented it.

A: You can use the curl_ methods to do the same thing


text:
Q: Setting QTDIR based on generator in use I am trying to setup a CMake project which consists of multiple static libraries and one main executable which has dependencies on QT. I would like to be able to select either a MinGW or a MSVC build when I run the cmake build.
I recently learned that the QT specific parts of CMake will find the installed library binaries for QT automatically if QTDIR is set as an environment variable and if QTDIR/bin is in the PATH.
Now I am wondering how I can set this information dynamically depending on the compiler that I am using. Since I would need to point cmake to either one of C:\Qt\5.3\mingw482_32 or C:\Qt\5.3\msvc2013_64, or possibly others if I extend the list of targets in the future.
Note that I do not need to build both compiler targets at the same time, I would usually select on target in my IDE and build that one, but I would like to be able to switch between both targets.
The solution should be in such a way, that on Linux the CMake build will still find the libraries which are installed through the package manager automatically.
Can I easily achieve this with CMake?
As a side note, in the future I might also need to select the QT version on demand? So an extensible solution would be nice.


text:
Q: Arriving at a close approximation of the probability using code I was given a math question on probability. It goes like this:

There are 1000 lotteries and each has 1000 tickets. You decide to buy 1 ticket per lottery. What is the probability that you win at least one lottery?

I was able to do it mathematically on paper (arrived at 1 - (999/1000)^1000), but an idea of carrying out large iterations of the random experiment on my computer occurred to me. So, I typed some code — two versions of it to be exact, and both malfunction.
Code 1:
#include<iostream>
#include <stdlib.h>

using namespace std;

int main() {
    int p2 = 0;
    int p1 = 0;
    srand(time(NULL));
    for (int i = 0; i<100000; i++){
        for(int j = 0; j<1000; j++){
            int s = 0;
            int x = rand()%1000;
            int y = rand()%1000;
            if(x == y)
                s = 1;
            p1 += s;
        }
        if(p1>0)
            p2++;
    }
    cout<<"The final probability is = "<< (p2/100000);
    return 0;
}

Code 2:
#include<iostream>

#include <stdlib.h>

using namespace std;

int main() {
    int p2 = 0;
    int p1 = 0;
    for (int i = 0; i<100000; i++){
        for(int j = 0; j<1000; j++){
            int s = 0;
            srand(time(NULL));
            int x = rand()%1000;
            srand(time(NULL));
            int y = rand()%1000;
            if(x == y)
                s = 1;
            p1 += s;
        }
        if(p1>0)
            p2++;
    }
    cout<<"The final probability is = "<< (p2/100000);
    return 0;
}

Code 3 (refered to some advanced text, but I don't understand most of it):
#include<iostream>

#include <random>

using namespace std;

int main() {
    int p2 = 0;
    int p1 = 0;
    random_device rd;
    mt19937 gen(rd());
    for (int i = 0; i<100000; i++){
        for(int j = 0; j<1000; j++){
            uniform_int_distribution<> dis(1, 1000);
            int s = 0;
            int x = dis(gen);
            int y = dis(gen);
            if(x == y)
                s = 1;
            p1 += s;
        }
        if(p1>0)
            p2++;
    }
    cout<<"The final probability is = "<< (p2/100000);
    return 0;
}

Now, all of these codes output the same text:
The final probability is = 1
Process finished with exit code 0

It seems that the rand() function has been outputting the same value over all the 100000 iterations of the loop. I haven't been able to fix this.
I also tried using randomize() function instead of the srand() function, but it doesn't seem to work and gives weird errors like:
error: 'randomize' was not declared in this scope
randomize();
           ^

I think that randomize() has been discontinued in the later versions of C++.
I know that I am wrong on many levels. I would really appreciate if you could patiently explain me my mistakes and let me know some possible corrections.

A: Only seed the pseudorandom number generator by srand once at the beginning of your program. When you seed it over and over again you reset the pseudorandom number generator to the same initial state. time has a granularity measured in seconds, by default. Odds are you are getting all 1000 iterations - or most of them - within a single second.

A: See this answer to someone else's question for a general description of how pseudorandom number generators work.
This means that you should be creating one instance of a PRNG in your program and seeding it one time.  Don't do either of those tasks inside loops, or inside functions that get called multiple times, unless you really know what you're doing and are trying to do something sophisticated such as using correlation induction strategies such as common random numbers or antithetic variates to achieve "variance reduction".

A: You should reset your count (p1) at the beginning of the outer loop. Also, be aware of the final integer division p2/100000, any value of p2 < 100000 would result in 0.
Look at this modified version of your code:
#include <iostream>
#include <random>

int main()
{
    const int number_of_tests = 100000;
    const int lotteries = 1000;
    const int tickets_per_lottery = 1000;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> lottery(1, tickets_per_lottery);

    int winning_cases = 0;
    for (int i = 0; i < number_of_tests; ++i )
    {
        int wins = 0;                           // <- reset when each test start
        for(int j = 0; j < lotteries; ++j )
        {
            int my_ticket = lottery(gen);
            int winner = lottery(gen);
            if( my_ticket == winner )
                ++wins;
        }
        if ( wins > 0 )
            ++winning_cases;
    }
    // use the correct type to perform these calculations
    double expected = 1.0 - std::pow((lotteries - 1.0)/lotteries, lotteries);
    double probability = static_cast<double>(winning_cases) / number_of_tests;

    std::cout << "Expected: " << expected
              << "\nCalculated: " << probability << '\n';

    return 0;
}

A tipical run would output something like:

Expected: 0.632305
Calculated: 0.63125


text:
Q: Tablesorter Editable Widget change how to select a row I'm using TableSorter to display my table with the 'editable' widget - all working fine.
Does anyone know how I can change the 'single-click' (default, I think) which will select a cell,  to 'double-click'?

A: Content Editable is a browser rendering, and as such TableSorter has little control on how it functions.
That being said you could write your own.  Don't use the ContentEditable widget at all, just bind each tbody td to a double-click event, then wrap the content in a content editable div and focus it and bind an unfocus event to it.  Once unfocused, run your validation, commit the update, update ts rows and unwrap the cell.
This is not a common UI behaviour and as such I think it would be in the realm of per site rather then the scope of TableSorter, it would be hard to maintain with a small user base and take up lots of the authors time to do so for a small base.
Of course this is my personal option of it, I know the Author is very busy and I just can't see this being a very used widget.
EDIT: Mottie just came up with an other option, it's not the best since it'll run validate on each blur, but it might be a little quicker to implement.
    initialized: function (table) {
        $('tbody')
        .on('click', '[contenteditable]', function(){
            this.blur();
            return false;
        })
        .on('dblclick', '[contenteditable]', function(){
            this.focus();
        });
    }

http://jsfiddle.net/abkNM/4683/


text:
Q: HttpContext.Current null after async operation I'm having the same issue described in this question where I am losing HttpContext.Current after an async operation. The main difference between that question and mine, is that I've applied all of the possible solutions to resolve it - which all work on my PC but don't work when we deploy to the webserver, which has .NET 4.8 installed. Another thing to note is that when we apply the settings - we can see that the SynchronizationContext is of type AspNetSynchronizationContext (and not Legacy, so we seem to have what we want).
We checked IIS App Settings and made sure there were no manually added or negating settings (like <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" /> or something similar) and there weren't. We also tried <httpRuntime targetFramework="4.5" /> - which did not work.
Are there any other settings/configurations/possible .NET CLR explanations that would make this setting: <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> not pass the HttpContext.Current to a thread while performing async operations?
Also - if I have <httpRuntime targetFramework="4.5" /> - and I see a LegacyAspNetSynchronizationContext - what could be the root cause?
Example (locally) that works, but breaks on the webserver:
[HttpGet]
[Route("api/DelayTest")]
public async Task<int> Test()
{
    var ctx = System.Web.HttpContext.Current; // not null
    await Task.Delay(new TimeSpan(0, 0, 5));
    ctx = HttpContext.Current; //null here (which causes issues)

    return 0;
}

Note: We are targeting .NET 4.5:
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxQueryStringLength="6000" />


text:
Q: efficiency loss due to use of function pointer in place of if-block Suppose we have a Fortran function (for example a mathematical optimization algorithm) that takes as input, another Fortran function:
myOptimizer(func)

Now depending on the user's choice, the input function could be from a list of several different functions. This list of choices can be implemented via an if-block:
if (userChoice=='func1') then
    myOptimizer(func1)
elseif (userChoice=='func2') then
    myOptimizer(func2)
elseif (userChoice=='func3') then
    myOptimizer(func3)
end if

Alternatively, I could also define function pointers, and write this as,
if (userChoice=='func1') then
    func => func1
elseif (userChoice=='func2') then
    func => func2
elseif (userChoice=='func3') then
    func => func3
end if
myOptimizer(func)

Based on my tests with Intel Fortran Compiler 2017 with O2 flag, the second implementation happens to be slower by several factors (4-5 times slower than the if-block implementation). From the software development perspective, I would strongly prefer the second approach since it results in much more concise and cleaner code, at least in my problem where there is a fixed workflow, with different possible input functions to the workflow. However, performance also equally matters in the problem.
Is this loss of performance by indirect function calls, expected in all Fortran codes? or is it a compiler-dependent issue? Is there a solution to using indirect function calls without performance loss? How about other languages such as C/C++?

A: This is a pure guess based on how compilers generally work and what might explain the 4-5x perf difference.
In the first version, maybe the compiler is inlining myOptimizer() into each call site with func1, func2, and func3 inlined into the optimizer, so when it runs there's no actual function pointer or function call happening.
An indirect function-call isn't much more expensive than a regular function call on modern x86 hardware.  It's the lack of inlining that really hurts, especially for FP code.  Spilling / reloading all the floating-point registers around a function call is expensive, especially if the function is fairly small.
i.e. what's probably hurting you is that your 2nd version convinces the compiler not to undo the indirection.  This would be true in C / C++ as well.
Hand-holding your compiler into making fast asm probably means you have to write it the first way, unless there's a profile-guided optimization option you can use that might make the compiler realize this is a hot spot and it's worth trying harder with the source written the 2nd way.  (Sorry I don't use Fortran, and I only know a few of the options for Intel's C/C++ compiler from looking at its asm output vs. gcc and clang on http://gcc.godbolt.org/)

To see if my hypothesis is right, check the compiler-generated asm.  If the first version doesn't actually pass a function pointer to a stand-alone definition of myOptimizer, but the 2nd one does, that's probably all there is to it.
See How to remove "noise" from GCC/clang assembly output? for more about looking at compiler output.  Matt Godbolt's CppCon2017 talk: "What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid" is a good intro to reading compiler output and why you might want to.


text:
Q: Is there any way to detect if the browsers cache is cleared Is there any way to detect if the browsers cache is cleared , I want to check this on a javascript application and I am using session storage.
Example:
I am on page 1.
i do some operations, like edit a field ..etc
i clear the cache.
Can i get to know that cache is cleared , when i am still on page 1. i use session storage.
I understand , the storage event will let us identify any modification on the session storage when the current tab is closed and new tab is opened.
but i want to set a flag or throw an alert message whenever the cache of the current browser is cleared.
Please help!

A: I dont know straight way, but this may help:
if (!localStorage.length && !sessionStorage.length) {
    // No items in localStorage and in sessionStorage,
    // cache possibly cleared
    [your code here]
}


text:
Q: GCE startup script fails to run on Ubuntu 18.04 I am launching an instance on GCP using gcloud compute and specifying the URL of my script using the metadata param. The script fails to run, when I check the metadata, the script url is there. The logs have no mention of any errors.
When I sudo -i and copy the script down from the bucket and execute, it runs fine.
Instance is running Ubuntu 18.04. Any ideas?

A: I believe that the issue you are facing is related to a Google Known issue with the new Image Ubuntu 18.04.
In particular after the update of the image gsutil is not available during the startup, therefore you will be not able to download it and it will fail.
I advice you to check the public issue, and to star it to follow and receive the updates:

*

*https://issuetracker.google.com/78907347


text:
Q: Ruby on Rails: conditionally display a partial I'm not sure if I'm doing the best approach here, but I have a block of data that I want to show after a search is done and to not be there at all before.  First of all, there is nothing to show, and second the model it references is nil so it throws an exception.
I placed this block in a partial template and added it the appropriate spot in my layout.  Is there a way to cleanly render the partial conditionally?  Is there a better way to approach this problem?

A: One easy way is to use a helper method. Helpers tend to be a bit cleaner than putting logic directly in the view.
So, your view might be something like :
<%= render_stuff_conditionally %>

and your helper would have a method to control this:
def render_stuff_conditionally
  if @contional_check
    render :partial => 'stuff'
  end
end

where obviously things are named more appropriately

A: Ruby allows you to do nice things like this:
<%= render :partial => "foo/bar" if @conditions %>

To make this a bit easier to read and understand, it can be written as:
<%= render(:partial => "foo/bar") if @conditions %>

render is a function, and you pass it a hash that tells it which partial to render.  Ruby allows you to put things on one line (which often makes them more readable and concise, especially in views), so the if @conditions section is just a regular if statement.  It can also be done like:
<% if @conditions %>
  <%= render :partial => "foo/bar" %>
<% end %>

Edit:
Ruby also allows you to use the unless keyword in place of if.  This makes code even more readable, and stops you from having to do negative comparisons.
<%= render :partial => "foo/bar" if !@conditions %>
#becomes
<%= render :partial => "foo/bar" unless @conditions %>

A: Assuming I am following you right, you do this at the view level.
<% if !@my_search_data.nil? %>
<% render :partial => 'foo/bar' %>
<% end %>

Hope that helps.  If not, maybe post an example of your code.


text:
Q: Part of speech of 'nothing' Consider the below sentence.

Nothing is as painful as what he went through.

What part of speech does 'nothing' belong to? Traditionally, it is analysed as a pronoun, but I am not too convinced by this analysis: for instance, whereas 'nothing' can be followed by a modifier (as in Thus far he has suggested nothing helpful), pronouns are very limited in both the type and range of modifiers that they allow. The pronoun She in the sentence She was denied access cannot be modified by a pre-head modifier (Young she was denied access is not grammatical), nor can it be modified by a post-head modifier (apart from a relative clause, though She who committed the crime was denied access does sound very archaic).
Thoughts?

A:
Nothing is as painful as what he went through.

"Nothing" belongs solely to the word class (part of speech) determinative; more specifically it's a compound determinative.
It functions as determiner-head, with the syntactic fusion of the two functions marked by the morphological compounding of a determinative base "no" with a nominal one "thing".
It's true that "nothing" is tradionally analysed as a pronoun. It shares with pronouns the property that it always functions as head in NP structure, but it differs from a pronoun in that it can freely take post-head modifiers, as in "Nothing sensible will come of this".

A: Grammarians and lexicologists often differ on how they categorize words into "parts of speech", so you'll get different answers to this question. (In fact, you already have!) If you'd like to analyze "nothing" as a pronoun, then feel free to do so. Those who take that approach allow some indefinite pronouns (unlike most other pronouns) to be followed by modifiers (including adjectives). For example:

Something extraordinary is happening.
Do you have anybody special in mind?
Everyone interested should sign up immediately.

You may be interested in tchrist's recent discussion of this on EL&U.

A: Nothing is sacred.
Subject: nothing
Verb: is
Predicate: is sacred.
If nothing were not a noun there, there would be no sentence.
nothing there is a noun.
Nothing mattered to her.
nothing there is a noun.
If nothing were not a noun there, there would be no sentence.
Merriam Webster_nothing
The word nothing can be: a pronoun, noun, adverb and adjective.


text:
Q: Drupal: drupal_get_form specify file to search How to specify file to search for a function drupal_get_form?

A: If you mean a form used as page callback, the file parameter is where you can specify a filename:
/**
 * Implementation of hook_menu().
 */
function MODULENAME_menu(){
    return array(
        'my/form' => array(
            'page callback' => 'drupal_get_form',
            'page arguments' => array('MODULENAME_myform'),
            'file' => 'myform.inc',
            //
            // ...
            //
        ),
    );
}

In that example, the function "MODULENAME_myform" that returns the form structure that drupal_get_form uses to build the page "www.yoursite.com/my/form" is stored in the file "myform.inc".

A: use include_once , require_once or require for adding files where the form resides . drupal_get_form automatically takes care to include the form.
for example :
include_once drupal_get_path('module', 'modname') .'/file.php';


text:
Q: java.net.SocketException Error. What am I doing wrong? I created a SOA service with Socket Adapter on JDeveloper and I need to run/test it using Java. So I created a server class and a client class but I am getting an error
I did some research on how to create this service and test it and I came across some helpful material online but yet I'm getting an error and I dont know how to fix it. I am very new to making socket servers and stuff.
here is my server class
package client;

import java.net.ServerSocket;
import java.net.Socket;

public class Class1 {

      try {

        ServerSocket socket = new ServerSocket(12110);
    Socket s=socket.accept();

          System.out.println("Connected!");

      } catch (Exception e) {
        e.printStackTrace();
      }

    }
}

and here is my client class
package client;

import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.Socket;

public class Client{

    public static void main(String[] args) {

        try {
              Socket socket = new Socket("localhost", 12110);
              OutputStream os = socket.getOutputStream();
              os.write("FirstName,LastName\nWaslley,Souza\nJohn,Snow".getBytes());
              os.flush();
              socket.shutdownOutput();
              BufferedReader soc_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              String response = soc_in.readLine();
              System.out.println("Response: " + response);
              socket.close();

            } catch (Exception e) {
              e.printStackTrace();
            }

    }
}

here is the error I get:
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:210)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at client.Client.main(Client.java:23)

A: This happens because your server code exits after accepting a socket connection. Consequently, the JVM of this server will exit and (among others) close all socket connections it holds. This results in a SocketException on the client side.
To fix this, you should prevent the server's JVM from exiting, for instance by nesting the accept() call in a while loop:
public class Server {
  public static void main(String[] args) {
    try {
      ServerSocket socket = new ServerSocket(12110);
      while (true) {
        Socket s = socket.accept();
        System.out.println("Connected! to " + s);
      }
    } catch (final Exception e) {
      e.printStackTrace();
    }
  }
}

A: Server Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Class1 {

    //static ServerSocket variable
    private static ServerSocket server;
    //socket server port on which it will listen
    private static int port = 12110;

    public static void main(String args[]) throws IOException, ClassNotFoundException {
        //create the socket server object
        server = new ServerSocket(port);
        //keep listens indefinitely until receives 'exit' call or program terminates
        while (true) {
            System.out.println("Waiting for the client request");
            //creating socket and waiting for client connection
            Socket socket = server.accept();
            //read from socket to ObjectInputStream object
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            //convert ObjectInputStream object to String
            String message = (String) ois.readObject();
            System.out.println("Message Received: " + message);
            //create ObjectOutputStream object
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //write object to Socket
            oos.writeObject("Hi Client " + message);
            //close resources
            ois.close();
            oos.close();
            socket.close();
            //terminate the server if client sends exit request
            if (message.equalsIgnoreCase("exit")) {
                break;
            }
        }
        System.out.println("Shutting down Socket server!!");
        //close the ServerSocket object
        server.close();
    }

}

Client Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
        //get the localhost IP address, if server is running on some other IP, you need to use that
        InetAddress host = InetAddress.getLocalHost();
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        //establish socket connection to server
        socket = new Socket(host.getHostName(), 12110);
        //write to socket using ObjectOutputStream
        oos = new ObjectOutputStream(socket.getOutputStream());
        System.out.println("Sending request to Socket Server");

        oos.writeObject("SEND SOME DATA");
        //read the server response message
        ois = new ObjectInputStream(socket.getInputStream());
        String message = (String) ois.readObject();
        System.out.println("Message: " + message);
        //close resources
        ois.close();
        oos.close();
        Thread.sleep(100);

    }
}

do in this way.

A: yo @Mike sorry was not clear last time dig in this is the full server code
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class Serv1 {
    public static void main(String[] args) {
        new Serv1().start();
    }
    public void start(){
        String input = "";
            try(ServerSocket socket = new ServerSocket(12110)) {
                System.out.println("Connected!");
                while (true) {
                try(Socket server = socket.accept()){
                    BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
                    PrintStream echo = new PrintStream(server.getOutputStream());
                    while ((input = in.readLine()) != null && !input.equals(".")) {
                        System.out.println(input);
                        echo.println("Echoed: " + input);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

A: This should do it
        String input= "";
        Socket server=socket.accept();
        BufferedReader  in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
        PrintStream echo = new PrintStream(server.getOutputStream());
        while((input = in.readLine()) != null && !input.equals(".")) {
            System.out.println(input);
            echo.println("echo: "+input);
        }


text:
Q: Cite Custom Field in apacite I am trying to find a command that will allow me to cite any field in my document. For instance, I would like to reference ibcnn, specify the field title and print Local Binary Convolutional Neural Networks, or specify field month and print 2017.
@journal{ibcnn,
 title={{Local Binary Convolutional Neural Networks}},
 author={Felix Juefei-Xu and Vishnu Naresh Boddeti and Marios Savvides},
 booktitle={{IEEE} Computer Vision and Pattern Recognition ({CVPR})},
 month={July},
 year={2017}
}

I'm sure this can be achieved but for some reason I am not able to — even looking at the bibtex package I cannot find how to do that simply.


text:
Q: Removing NLog depencency in release mode I'm developing a small open source library which is also available on Nuget with no dependencies. Now I want to use NLog just for debugging purposes in "Debug Mode" but I don't want it to be a dependency when I release new versions on Nuget. What is the best way to do it if this is a reasonable approach at all.
thanks

A: You can use
Logger.ConditionalTrace("entering method {0}", methodname);

etc. Those will be removed in a non-debug build. . See NLog 4.0 release post. Then you can safely remove the dependency in your NuGet package.


text:
Q: Organizing a URL structure I'm trying to make a mashup using Php and Last.fm api. But I've got some questions:
1 - How can I organize the code? Because the webapp'll do different thing and each one has it own code (file.php) but I don't like to see it in the url Ex: www.example.com/core/similar.php or www.example.com/core/get.php but I'd like to always see "www.example.com".
2 - There are any guidelines to follow when programming a webapp?

A: *

*It depends on the server you're using, for example, in Apache you can use .htaccess file to map which .php file will serve which URL.

*The second question is too broad.

A: First of all, you can set up the webserver to rewrite the urls based on patterns. I do not know which webserver you're using, so look it up. Apache is popular, and if you have mod_rewrite, you do the rewriting in the .htaccess file.
On the other hand, you may as well define a index.php file, which can function as a routing script, showing the relevant content to the user.
In the simplest form, it may look like this:
<?php
    switch ($_GET['page']) {
        case  'get':
            require('core/get.php');
            break;
        case  'show':
            require('core/show.php');
            break;
        default:
            require('core/welcome.php');
    }

Though, normally this is handled in a much more structured way, such as the MVC pattern.


text:
Q: Split a Date/Time String into Tokens with Regex I am trying to break a date format string (and an input date string) into parts (tokens).
A date format can use any separating character between tokens, as long as the tokens are valid. The date/time will be parsed into the format and the non-alphanumeric characters will carry over into the output string. I would like to strip the tokens from both the date/time format string and the input date/time string.
I need to split a string on all sets of non-alphanumeric characters
For example, let's say my date format string is:
'dddd, MMMM D, YYYY h:mm A'

I would like to have an array of all of the date/time tokens in the string. My output should be:
['dddd', 'MMMM', 'D', 'YYYY', 'h', 'mm', 'A']

I tried a couple of attempts, but I still cannot wrap my head around how to do this. I was able to come up with the regex:
[^\w]|[_]

which should match any character not present in [a-zA-Z0-9_] as the first alternative or match _ literally as the second alternative.
I have tested this regex and it does work, yet how can I use it properly?
I tried to use:
var format_tokens = display_format.match(/[^\w]|[_]/g);

..which, of course, returned me:
format_tokens = [",", " ", " ", ",", " ", " ", ":", " "];

..which should have been obvious...
So how do I get the inverse? How can I get the desired result of:
format_tokens = ['dddd', 'MMMM', 'D', 'YYYY', 'h', 'mm', 'A']

?
Thanks everybody!

A: You want to match alphanumeric characters and split/exclude on everything else then, right? Which would be ([a-zA-Z0-9]+)
this:
'dddd, MMMM D, YYYY h:mm A'.match(/([a-zA-Z0-9]+)/g)

returns:
["dddd", "MMMM", "D", "YYYY", "h", "mm", "A"]


text:
Q: how can we handle concurrent transactions in hibernate We have implemented a multi threaded application for updating a column of the table in database
ie, user account balance. The hibernate is used for interacting our application with data base. The application is deployed in multiple servers and will be worked as a cluster.
suppose the multiple requests are sent for updating the same user account in database. how can we handle this situation? The request from multiple servers or different threads from same server will try to update this at the same time. how can ensure the atomicity of the operation. can we do the same by data base -table or row- level lock using hibernate or spring framework
Example :
thread A from server S1 and thread B from server S2 access the same record R at the same time.
First the thread A from server S1 update the value of R to R1 and commit the transaction.
At the same time the thread B from server S2 update the value of R to R2 and commit the transaction.
what will be the outcome of this scenario?. we have to lock one of the transaction for the right results?. how can we lock the transaction because it is came from different servers?.

A: You can use Hibernate optimistic locking.

Optimistic locking assumes that multiple transactions can complete
  without affecting each other, and that therefore transactions can
  proceed without locking the data resources that they affect. Before
  committing, each transaction verifies that no other transaction has
  modified its data. If the check reveals conflicting modifications, the
  committing transaction rolls back[1].

More information here : https://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch05.html

A: For scenarios you mentioned, you need to consider below points:

*

*Setting Transaction isolation level. Refer this link for setting transaction isolation level. Most of the time, READ COMMITTED suffice the requirement, but you can explore other options as well.

*If you have multiple transactional resources like JMS then think of using XA Transaction. i.e. In your configuration you can use XA complaint DB driver. Refer this link for further details . XA drivers offers 2-phase commit protocol which maintains atomicity of transaction.

*If you have EJBs then container managed transaction can do all transaction related job for you. Refer this link for more.


text:
Q: Running entire Python script in one line I have developed a Python script to reference another Python file with functions to compute KPIs. Then, using the main file, the KPIs are cleaned and ordered and finally outputted to a word doc. In the process I am also referring an Excel file to provide further user-desired inputs.
Now I want to be able to just use one line to run the entire file. I have tried and have in the past successfully used:
exec(open("binary2.py").read())

However, with this file, I am running into a certain error which I am not facing when I simply run binary1.py on its own. As in, error happens only using the exec command.

AttributeError                            Traceback (most recent call last)  in
----> 1 exec(open("binary2.py").read())

 in
~\Desktop\Model_Validation\Playbook XLS and Jupyter
Notebook\BinaryKPI_PythonFunctionsV3.py in data_vars(df1, target)
662     stack = traceback.extract_stack()
663     filename, lineno, function_name, code = stack[-2]
--> 664     vars_name = re.compile(r'((.?)).$').search(code).groups()[0]
665     final = (re.findall(r"[\w']+", vars_name))[-1]
666
AttributeError: 'NoneType' object has no attribute 'groups'

There is a function which I am calling in the binary2 file which calls for the Traceback. It seems this Traceback is not getting carried over while using exec command.
I also tried:
source = open("binary2.py").read()
code2 = compile(source, filename, 'exec')
exec(code2)

but to no benefit.
Any ideas appreciated.
Thanks,
Ansh
Edit: The code generating an error while running the exec command runs fine while running the py file directly:


text:
Q: Web Scraping Wikipedia With BeautifulSoup I'm just trying to scrape the title of an input Wikipedia page but I get Bad Title after running
Here's the code
import requests
from bs4 import BeautifulSoup

wiki = input('Enter the wiki:')

url = "https://en.wikipedia.org/wiki/{wiki}"
response = requests.get(url)

soup = BeautifulSoup(response.content, 'html.parser')

title = soup.find(id="firstHeading")
print(title.string)

I wanted to eventually summaries the whole page but cant seem to get past printing the title

A: You will need to prefix your string with f for it to parse {wiki} correctly. You will probably also need to encode the URL to handle special characters correctly e.g. spaces. For example:
import urllib.parse
import requests
from bs4 import BeautifulSoup

wiki = input('Enter the wiki:')

url = f"https://en.wikipedia.org/wiki/{urllib.parse.quote(wiki)}"
response = requests.get(url)

soup = BeautifulSoup(response.content, 'html.parser')

title = soup.find(id="firstHeading")
print(title.string)


text:
Q: Push object in array and save into mongoDB using Js
I want to save my details as {userId:status} into list but I'm not able to able to achieve can you help where I'm doing wrong?

if(campResp){
    let userId = await req.body.userId
    let status = req.body.status
    let userResp = await User.findOne({'id':req.body.userId}).exec()
    var data = {}
    data[userId] = status

    if(userResp){
        campResp.views = {}
        let visiterResp = await Campaign.find({'views':data})
        if(visiterResp.length>0){
            res.status(400).json({'status':false,'message':'Already watched'})
        }else{
            let pushResp = await campResp.views.push(data)
            if(pushResp){
                await campResp.save(async(err,response)=>{
                    if(response){
                        res.status(200).json({'status':true,'message':'campaign finished'})
                    }
                })
            }
        }
    }

Schema is like, but still it's not working.

const mongoose = require('mongoose')

const campaignSchema = new mongoose.Schema({
    id: mongoose.Schema.Types.ObjectId,
    imageUrl:{
        required:true,
        type:String
    },
    link:{
        required:true,
        type:String
    },
    ownerId:{
        required:true,
        type:String
    },
    setting:{
        types:{
            type:String
        },
        bill:{
            type:String
        },
        dateTime:{
            type:String
        },
        expected_time:{
            type:String
        },
        expected_views:{
            type:String
        },
        expected_subs:{
            type:String
        },
        expected_likes:{
            type:String
        }
    },
    views:[{
        userId:Boolean
    }]
},{versionKey: false},{_id:false})

module.exports = mongoose.model('Campaign',campaignSchema)

and in response what it's saving how can i save into my db like userId:status. Ex "6789786722hgdvasnbad":true how to achieve the same.

"views": [
            {
                "_id": "609b60a82445e32e8060b0c2"
            },
            {
                "_id": "609b60a82445e32e8060b0c4"
            }
        ]

A: You may want to use mongoose.Schema.Types.Mixed
views:[{
    type: mongoose.Schema.Types.Mixed
}]

An "anything goes" SchemaType. Mongoose will not do any casting on
mixed paths. You can define a mixed path using Schema.Types.Mixed or
by passing an empty object literal. The following are equivalent.


text:
Q: VBA code needed to clear contents of cell AQ when value of cell D changes; Microsoft Excel for Office 365 MSO 32-bit I'll preface this by saying that programming is not my strong suit but I would appreciate any help.
I have used the below formula in an attempt to clear the contents of cell AQ when the value of cell D (on the same row) changes. Currently, the contents are only cleared in AQ when the value in cell D changes to 1 (presumably due to the line "If Target = 1 Then". What do I use instead of "1" so that all changes, from any value to any value, will initiate the ClearContents instruction for cell AQ?
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("D7:D506")) Is Nothing Then
        If Target = 1 Then
            Range("AQ" & Target.Row).ClearContents
        End If
    End If
End Sub

A: To make sure a true change has occurred, we first save the value of the selected cell as a public variable. Since you can select more than one cell at once, I've decided to use a public Collection.
Then when a change occurs we compare the new value of that cell to the old value in the collection, and only if they don't match, clear the contents of AQ.
Something like:
Public coll As New Collection

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cel As Range
    Set coll = New Collection
    If Not Intersect(Target, Range("D7:D506")) Is Nothing Then
        For Each cel In Target
            coll.Add cel.Value, cel.Address
        Next cel
    End If
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("D7:D506")) Is Nothing Then
        If Not Target.Value = coll(Target.Address) Then
           Range("AQ" & Target.Row).ClearContents
        End If
    End If
End Sub

Edit updated to work when selecting multiple cells.
Obviously, if you change a value in Range("D7:D506") without actually selecting the cell first, this code will throw an error.
Come to think of it, you can edit multiple cells at once, if you delete the value. Then this code will also throw an error.
But we can work around that by using the same approach in Worksheet_Change as we are doing in Worksheet_SelectionChange:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cel As Range
    If Not Intersect(Target, Range("D7:D506")) Is Nothing Then
        For Each cel In Target
            If Not cel.Value = coll(cel.Address) Then
                Range("AQ" & cel.Row).ClearContents
            End If
        Next cel
    End If
End Sub


text:
Q: PeakVirtualMemorySize64, PeakWorkingSet64 and PeakPagedMemorySize64 for a process have different value if we executed several time? I run a code multiple time and i measure in the end of it the PeakPagedMemorySize64 , PeakWorkingSet64 and PeakVirtualMemorySize64 using the Process class .
But in each time i get different value for the same code
PeakPagedMemorySize64 112758784 PeakVirtualMemorySize64 332701696   PeakWorkingSet64 143835136
PeakPagedMemorySize64 113696768 PeakVirtualMemorySize64 332636160   PeakWorkingSet64 144642048
PeakPagedMemorySize64 113528832 PeakVirtualMemorySize64 332701696   PeakWorkingSet64 144547840

why I have this different values instead of getting the same value each time? And how can I optimize it to minimize this variation?

A: "Working set" is the amount of virtual memory which fits into physical RAM. The amount of physical RAM available depends on other programs as well, so this value changes over time. If the "working set" value changes due to other programs, so will the peak value.
In fact, you should be happy if this value is high: this means that all your data is in RAM and RAM is fast. If this value is low, some data has been swapped to disk and disk is very slow.
The question is: why do you want to measure this value? If you're looking for a memory leak, measure private bytes instead.
Since you have tagged this .net, the amount of private bytes heavily depends on the implementation of the .NET garbage collector. It may request more or less memory depending on garbage collections which ran or did not run previously and how much physical RAM was available at the time .NET requested additional memory the last time.
To see those internals, I recommend using windbg and sos. You can then see the amount of free memory of the .NET garbage collector.


text:
Q: Laravel JWT Auth error I'm trying to implement JWT in Laravel 5.2 but I get this error:
"message": "call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\\Auth\\TokenGuard' does not have a method 'once'",
  "status_code": 500,
  "debug": {
    "line": 288,
    "file": "/home/vagrant/Code/lsupport/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php",
    "class": "ErrorException",

My routes file:
$api = app('Dingo\Api\Routing\Router');

$api->version('v1',function($api)
{
    $api->post('login','App\Http\Controllers\Auth\AuthController@authenticate');
});

My AuthController:
 public function authenticate(Request $request)
    {
        $credentials = $request->only('email','password');

        try {
            if(!$token = JWTAuth::attempt($credentials)) {
                return $this->response->error(['error' => 'User credentials are not correct!'],401);
            }
        } catch(JWTException $ex) {
            return $this->response->error(['error' => 'Something went wrong!'],500);
        }
        return $this->response->item(compact('token'));
    }

I'm testing with postman.

A: Also had the same issue, I solved it by setting my default guard to 'web' in the auth.php file inside config folder.
'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

Remember, your route should not have the auth middleware for this login, because, this is just to authenticate.


text:
Q: log4net logs message into all appenderes (/all files) I am having issues with how log4net manages appenders, and the messages to these appenders.
When I log 1 message to 1 logger (which corresponds to 1 appender), still the message ends up in ALL log files (thus the message seems to go to ALL appenders)
What am I doing wrong?!
I managed to reproduce my problem in a unit test:
    [Test]
    public void Test()
    {
        var hierarchy = (Hierarchy)LogManager.GetRepository();

        var patternLayout = new PatternLayout
        {
            ConversionPattern = "%date %level %logger - %message%newline" //CreateLayoutPattern(appenderConfiguration.Layout),
        };
        patternLayout.ActivateOptions();

        hierarchy.Configured = true;
        for (var i = 1; i < 10; i++)
        {
            var logFile = Path.Combine(_testLogFolder, $"SomeLog_Test{i}.csv");

            var roller = new RollingFileAppender
            {
                Name = $"Test{i}",
                AppendToFile = true,
                File = logFile,
                CountDirection = 1,
                Layout = patternLayout,
                ImmediateFlush = true,
                // MaxSizeRollBackups is set to max int, software will have an independent mechanism in place (reaper) to clean up old files
                MaxSizeRollBackups = int.MaxValue,
                MaximumFileSize = "1MB",
                RollingStyle = RollingFileAppender.RollingMode.Size,
                StaticLogFileName = false,
                PreserveLogFileNameExtension = true,
                Threshold = Level.All
            };

            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);
        }

        // A
        LogManager.GetLogger("Test1").Info("Whatever");

        // Now the ALL of the log files contain the message "Whatever", why?!?! I only logged to 'Test1'
    }

A: Apparently this is default behavior (which makes sense when I think about it a little longer :)).
What I need is achievable. Instead of adding all appenders to the hierarchy.Root.AddAppender I had to create the logger for each appender name, and then add the roller to that logger. E.g:
var logger = hierarchy.GetLogger("Test1", hierarchy.LoggerFactory);

logger.AddAppender(roller);
logger.Level = Level.All;
logger.Additivity = false;

And remove :
hierarchy.Root.AddAppender(roller);