text:
Q: How to disable prestashop's page-not-found redirect? I have a Prestashop 1.6 installed on a VPS hosting and all is working well with it, except that when I try to reach a page that doesn't exist, instead of serving the 404 page of the template, a 301 redirect is returned and the client is redirected to index.php?controller=page-not-found where the 404 template is shown.
This is not working for me due to SEO reasons.
How do I disable this redirect?
Thanks

A: Turns out the default behavior of prestashop is to redirect. It was not a override. Anyway - I found a way to achieve what I wanted to do anyway.
After some time struggling with that - I came up with a retarded solution, that will do for now.
I am sharing it here, because I sure would have appreciated finding it few days ago, but be warned - it is retarded to the point of no return.
Not recommended if you can come up with something else.
What I did was this - I found the CategoryController.php file in the controllers/front/ folder.
There should  be this row:
if (!$this->category->active)

In it I make a php file_get_contents request to the 404.html page of the website, and serve it.
Afterwards I terminate the php script with an exit(); command.
This way the server sends out the 404.html content, without redirecting.
Here is the full code:
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found');

echo file_get_contents('https://website.com/404/'
false,
stream_context_create(
array(
'http' => array(
'ignore_errors' => true
)
)
)
);
exit();

Don't forget that if the controller is overridden it might not work properly.

A: I've done this in overrided Tools controller
public static function redirectLink($url)
  {
 $init_url=$url;

  if (!preg_match('@^https?://@i', $url)) {
      if (strpos($url, __PS_BASE_URI__) !== false && strpos($url, __PS_BASE_URI__) == 0) {
          $url = substr($url, strlen(__PS_BASE_URI__));
      }
      if (strpos($url, 'index.php?controller=') !== false && strpos($url, 'index.php/') == 0) {
          $url = substr($url, strlen('index.php?controller='));
      }
      $explode = explode('?', $url);
      $url = Context::getContext()->link->getPageLink($explode[0]);
      if (isset($explode[1])) {
          $url .= '?'.$explode[1];
      }
  }

if ((string)trim($init_url)==='404') {
      header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

      header('Status: 404 Not Found');
      echo file_get_contents($url, false,
            stream_context_create(
              array('http' =>  array('ignore_errors' => true,
                               ),
              )
            )
          );

      exit();
    } else {

            header("HTTP/1.1 301 Moved");
            header('Location: '.$url);
            exit();

    }

}

A: A global solution for this (so you don't have to go controller by controller) is going straight to the -> classes/Dispatcher.php
In there you will find the dispatch function.
You can do something like ->
if ($this->controller == $this->controller_not_found) {
//your code here
}

before the line where the controller is going to be executed
$controller->run();


text:
Q: Pytest with Django Celery: ERROR django.db.utils.InterfaceError: connection already closed I have celery task which create models entries in database. Celery uses Redis as a broker.
I create new config for test in test_settings.py (the application works with Docker, so I'm changing host for database and Redis):
# test_settings.py

from .settings import *

DATABASES = {
    'default': {
        'ENGINE': env('POSTGRES_ENGINE'),
        'NAME': env('POSTGRES_DB'),
        'USER': env('POSTGRES_USER'),
        'PASSWORD': env('POSTGRES_PASSWORD'),
        'HOST': 'localhost',
        'PORT': env('POSTGRES_PORT')
    }
}
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': 'redis://localhost:6379/1',
    }
}

CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'django-db'

# tasks.py

from .models import Message
from itertools import islice
from celery import shared_task

@shared_task(ignore_result=True)
def create_entries(data: list):
    batch_size = 100
    obj_iterator = (Message(**obj) for obj in data)
    while True:
        batch = list(islice(obj_iterator, batch_size))
        if not batch:
            break
        Message.objects.bulk_create(batch, batch_size)

In application everything works fine, but tests don't work. Test method code:
# tests/test_celery_tasks.py

import tasks
import pytest
from .models import Message
from celery.result import AsyncResult

@pytest.mark.django_db
@pytest.mark.celery
def test_create_entries(celery_worker):
    message_data = [
        {
            text: 'hello bro',
            client: 'Nick'
        },
    ]
    assert Message.objects.count() == 0
    task = tasks.create_entries.delay(message_data)
    result = AsyncResult(task.task_id)
    assert result.status == 'SUCCESS'
    assert Message.objects.count() == 1

I get an error ERROR service/tests/test_celery_tasks.py::test_create_entries[Message] - django.db.utils.InterfaceError: connection already closed
if I add a transaction, then this error disappears, but there will be Assert Fail:
@pytest.mark.django_db(transaction=True)
@pytest.mark.celery
def test_create_entries(celery_worker):
    # the same code
    assert result.status == 'SUCCESS' # Fail, status=PENDING
    assert Message.objects.count() == 1 # Fail, count=0

I have no idea why tasks don't work in tests

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mouse leave after editing div height When I hover over #hoverme, I want #header to change the height. But I also want it to go back to normal, once the mouse has left #hoverme.
Does anyone know how to do this? My jsfiddle doesn't seem to work as intended.
JAVASCRIPT
$(document).ready(function(){
  $('#hoverme').on('mouseover', function(){
    $('#header').css('height', '500px');
  });

  $('#header').on('mouseout', function(){
    $('#header').css('height', '100px');
  });
});

HTML

hover over me

CSS
#header {
    height:100px;
    border:1px solid red;
}

A: At mouseout use #hoverme as well:
$(document).ready(function(){
  $('#hoverme').on('mouseover', function(){
    $('#header').css('height', '500px');
  });

  $('#hoverme').on('mouseout', function(){
    $('#header').css('height', '100px');
  });
});

and change the div of hoverme to a span so that not the entire line is used:

    hover over me

The new fiddle

A: Not sure what you mean by "work as intended", but try this:
$(function(){

var hdr = $('#header');
hdr.mouseenter(function(){
  hdr.css('height', '500px');
});
hdr.mouseleave(function(){
  hdr.css('height', '100px');
});

});


text:
Q: How to pick up and use varying number of users in a group and get them to do some task in Jmeter Wonder if any one could help!
I m trying replicate scenario where a group could have varying number of members. All these members has a file attached to them as well. I need to pickup these users and associated file and them to a batch task. Currently, Im having to fix the number of users to 15 do this but keen to do this with varying number users. I have used regEx extractor to pick these 2 values and using it in following HTTP request. In the image attached, the 'ReportUids' and the 'ContributerUids' are the one in question. How do I get Jmeter to pick up these if there are dynamic??
Bactch Script Step 4

A: You can use Beanshell PreProcessor for dynamically adding request parameters.

*

*Add Beanshell PreProcessor as a child of your Batch Step 3 of 5 request

*Put the following code into Beanshell PreProcessor's "Script" area
Iterator it = vars.getIterator();
while (it.hasNext()) {
    Map.Entry var = (Map.Entry) it.next();
    log.info("Processing variable: " + var.getKey());
    if (var.getKey().toString().startsWith("Pld")) {
        sampler.addArgument("ContributorUids", var.getValue().toString());
    }
    if (var.getKey().toString().startsWith("Ruid")) {
        sampler.addArgument("ReportUids", var.getValue().toString());
    }

}

See How to Use BeanShell: JMeter's Favorite Built-in Component guide for extended information on using Beanshell in JMeter.
The tricky thing is that uniqueness of HTTP method parameter names isn't a must so it's up to a developer how to handle duplicate parameter names. JMeter uses Java Properties to store arguments so it will be the most recent one. If you need to amend arguments names as well - you should be able to do it by slightly changing above Beanshell.


text:
Q: Handsontable delete multiple rows I am new to Handsontable. I am trying to delete multiple selected table rows using 'getSelected' and 'alter' methods (remove_row). However, with my code below I am getting the error "selection" not defined in Firebug and "Uncaught TypeError: Cannot read property '0' of undefined " in Chrome. It doesn't matter which row I select or how many. I still get the error and no rows are deleted. What am I doing wrong please?
    $(document).ready(function () {

    var myData = [
        ["", "Kia", "Nissan", "Toyota", "Honda"],
        ["2008", 10, 11, 12, 13],
        ["2009", 20, 11, 14, 13],
        ["2010", 30, 15, 12, 13]
    ];

    $("#exampleGrid").handsontable({
        data: myData,
        startRows: 5,
        startCols: 5,
        //minSpareCols: 1, //always keep at least 1 spare row at the right
        //minSpareRows: 1, //always keep at least 1 spare row at the bottom,
        rowHeaders: true,
        colHeaders: true,
        contextMenu: true,
        currentRowClassName: 'currentRow',
        currentColClassName: 'currentCol'

    });

    $edit = $('#exampleGrid');

    function editRows() {

        $('#addtop').on('click', function () {
            $edit.handsontable('alter', 'insert_row', 0);
        });

        $('#addbottom').on('click', function () {
            $edit.handsontable('alter', 'insert_row');
        });

        var selection = $edit.handsontable('getSelected');
        $('.deletebutton').on('click', function () {
            $edit.handsontable('alter', 'remove_row', selection[0], selection[2]);
        });

    }

    editRows();
  });

Here is my fiddle http://jsfiddle.net/EfhqJ/48/.
Thanks.

A: your "selection" variable is not visible within the scope of the onClick handler.
Try moving "var selection = ..." into the handler function.
Something like...
    $('.deletebutton').on('click', function () {
        var selection = $edit.handsontable('getSelected');
        $edit.handsontable('alter', 'remove_row', selection[0], selection[2]);
    });

A: As it currently stands, getSelected() returns nothing...
getSelected: function () {
     //https://github.com/warpech/jquery-handsontable/issues/44
     //cjl if (selection.isSelected()) {
     //return [priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()];
     //}
     }

which is a huge problem since handsontable references that function quite a bit.  However, we can fortunately use the afterSelectionEnd event.

afterSelectionEnd (r: Number, c: Number, r2: Number, c2: Number)
  Callback fired after one or more cells are selected (on mouse up).
  Parameters:
r selection start row
c selection start column
r2 selection end row
c2 selection end column

According to the API,

alter ('remove_row', index: Number, amount: Number (Optional), source: String (Optional))
  Remove the row(s) at given index. Default amount equals 1

This means in order to use alter('remove_row'), we only need to provide the index.

Here is a working demo I made to get the desired result.
NOTE:
Due to a bug, we need to add some logic in the afterSelectionEnd event.
JAVASCRIPT:
var myData = [
    ["", "Kia", "Nissan", "Toyota", "Honda"],
    ["2008", 10, 11, 12, 13],
    ["2009", 20, 11, 14, 13],
    ["2010", 30, 15, 12, 13]
    ];

//declare row vars
var row1 = null,
    row2 = null;

var $container = $("#exampleGrid");

$container.handsontable({
    data: myData,
    startRows: 5,
    startCols: 5,
    minSpareCols: 0,
    minSpareRows: 0,
    rowHeaders: true,
    colHeaders: true,
    contextMenu: true,
    afterSelectionEnd: function(x1, y1, x2, y2){

        //add this because of bug
          if( (x1 <= x2 && y1 < y2) || (x1 < x2 && y1 <= y2) || (x1 == x2 && y1 == y2)) {
            row1 = x1;
            if(x1 == 0)
                row2 = parseInt(x2 + 1);
              else
                row2 = x2;
        }
        else if( (x1 >= x2 && y1 > y2) || (x1 > x2 && y1 >= y2)) {
            row1 = x2;
            if(x2 == 0)
                row2 = parseInt(x1 + 1);
              else
                row2 = x1;
        }
        else if(x1 < x2 && y1 > y2) {
            row1 = x1;
            row2 = x2;
        }
        else if(x1 > x2 && y1 < y2) {
            row1 = x2;
            row2 = x1;
        }
    }
});

//gets instance of handsontable
    var instance = $container.handsontable('getInstance');

$('#delete').click(function(){
    if(row1 != null){
        if(row2 != null || row2 != row1 ){
            instance.alter('remove_row', row1, row2);
        }
        else{
            instance.alter('remove_row', row1);
        }
        row1 = null;
        row2 = null;
    }else{
        alert('Please select a cell...');
    }
});

Hope this helps and let me know if you need anything else!

A: you just need to add outsideClickDeselects: false to your options of constructor, then you will get the correct result of getSelected().
and here is the live demo http://jsfiddle.net/czz82kL5/2/


text:
Q: Extended Kalman filter converging to incorrect value, is this just the nature of the beast? (pics) I've designed a quaternion extended Kalman filter for fusing gyroscope and accelerometer data. The shape of the estimate plot seems perfect, however the estimate seems to be constantly converging to the wrong solution. Is this just down to the fact that I'm not using an optimal estimator like the linear Kalman filter, or should it be possible to obtain an unbiased estimate using the EKF? I've used two different implementations so far and ran into the same problem both times.
Here is a plot of the filter output:

*

*Green: angle estimated from accelerometer alone

*Blue: Integrated gyroscope output

*Red: Linear KF output

*Cyan: EKF output, note the offset

Here is the matlab code for one iteration:
function [ q, wb ] = EKF2( a,w,dt )

persistent x P;

% Tuning paramaters
Q = [0, 0, 0, 0, 0, 0, 0;
    0, 0, 0, 0, 0, 0, 0;
    0, 0, 0, 0, 0, 0, 0;
    0, 0, 0, 0, 0, 0, 0;
    0, 0, 0, 0, 0.01, 0, 0;
    0, 0, 0, 0, 0, 0.01, 0;
    0, 0, 0, 0, 0, 0, 0.01];

R = [1000000,    0,    0;
        0, 1000000,    0;
        0,    0, 1000000;];

if isempty(P)
    P = eye(length(Q))*10000; %Large uncertainty of initial values
    x = [1, 0, 0, 0, 0, 0, 0]';
end

q0 = x(1);
q1 = x(2);
q2 = x(3);
q3 = x(4);
wxb = x(5);
wyb = x(6);
wzb = x(7);
wx = w(1);
wy = w(2);
wz = w(3);

z(1) = a(1);
z(2) = a(2);
z(3) = a(3);
z=z';

% Populate F jacobian
F = [              1,  (dt/2)*(wx-wxb),  (dt/2)*(wy-wyb),  (dt/2)*(wz-wzb), -(dt/2)*q1, -(dt/2)*q2, -(dt/2)*q3;
    -(dt/2)*(wx-wxb),                1,  (dt/2)*(wz-wzb), -(dt/2)*(wy-wyb),  (dt/2)*q0,  (dt/2)*q3, -(dt/2)*q2;
    -(dt/2)*(wy-wyb), -(dt/2)*(wz-wzb),                1,  (dt/2)*(wx-wxb), -(dt/2)*q3,  (dt/2)*q0,  (dt/2)*q1;
    -(dt/2)*(wz-wzb),  (dt/2)*(wy-wyb), -(dt/2)*(wx-wxb),                1,  (dt/2)*q2, -(dt/2)*q1,  (dt/2)*q0;
                   0,                0,                0,                0,          1,          0,          0;
                   0,                0,                0,                0,          0,          1,          0;
                   0,                0,                0,                0,          0,          0,          1;];

%%%%%%%%% PREDICT %%%%%%%%%
%Predicted state estimate
% x = f(x,u)
x = [q0 - (dt/2) * (-q1*(wx-wxb) - q2*(wy-wyb) - q3*(wz-wzb));
     q1 - (dt/2) * ( q0*(wx-wxb) + q3*(wy-wyb) - q2*(wx-wzb));
     q2 - (dt/2) * (-q3*(wx-wxb) + q0*(wy-wyb) + q1*(wz-wzb));
     q3 - (dt/2) * ( q2*(wx-wxb) - q1*(wy-wyb) + q0*(wz-wzb));
     wxb;
     wyb;
     wzb;];

% Re-normalize Quaternion
qnorm = sqrt(x(1)^2 + x(2)^2 + x(3)^2 + x(4)^2);
x(1) = x(1)/qnorm;
x(2) = x(2)/qnorm;
x(3) = x(3)/qnorm;
x(4) = x(4)/qnorm;

q0 = x(1);
q1 = x(2);
q2 = x(3);
q3 = x(4);

% Predicted covariance estimate
P = F*P*F' + Q;

%%%%%%%%%% UPDATE %%%%%%%%%%%
% Normalize Acc and Mag measurements
acc_norm = sqrt(z(1)^2 + z(2)^2 + z(3)^2);
z(1) = z(1)/acc_norm;
z(2) = z(2)/acc_norm;
z(3) = z(3)/acc_norm;

h = [-2*(q1*q3 - q0*q2);
     -2*(q2*q3 + q0*q1);
     -q0^2 + q1^2 + q2^2 - q3^2;];

%Measurement residual
% y = z - h(x), where h(x) is the matrix that maps the state onto the measurement
y = z - h;

% The H matrix maps the measurement to the states
H = [ 2*q2, -2*q3,  2*q0, -2*q1, 0, 0, 0;
     -2*q1, -2*q0, -2*q3, -2*q2, 0, 0, 0;
     -2*q0,  2*q1,  2*q2, -2*q3, 0, 0, 0;];

% Measurement covariance update
S = H*P*H' + R;

% Calculate Kalman gain
K = P*H'/S;

% Corrected model prediction
x = x + K*y;      % Output state vector

% Re-normalize Quaternion
qnorm = sqrt(x(1)^2 + x(2)^2 + x(3)^2 + x(4)^2);
x(1) = x(1)/qnorm;
x(2) = x(2)/qnorm;
x(3) = x(3)/qnorm;
x(4) = x(4)/qnorm;

% Update state covariance with new knowledge
I = eye(length(P));
P = (I - K*H)*P;  % Output state covariance

q = [x(1), x(2), x(3), x(4)];
wb = [x(5), x(6), x(7)];

end

A: The problem you are describing is said to be one of the main drawbacks of the EKF. It does not guarantee any convergence to the real value. If you want to keep using it:

*

*Try increasing the system noise Q and/or measurement noise R  (can be interpreted as  'putting the nonlinearities into the noise'). This also makes the linear KF perform better on nonlinear problems

*To judge how well you're doing, plot the 2-sigma-band around your estimate to see if your real value lies within in it (else you noise is too small).

The Unscented Kalman filter has the reputation of being more robust in dealing with non-linearities than the EKF. The implementation complexity is roughly the same as EKF.

A: I am not an expert on Kalman Filtering, but I think a static error is the best you can get with gyro/accel measurements. In my previous lab, they fused the inertial meas with GPS to recalibrate.

A: I have just tried you algorithm and it works really well. In order to avoid the output of the filter to follow the drifting integrated angular rate you need to decrease the value of the variance of the measurement noise. I have tried with a value of 100 instead of 1000000. This way you tell the filter to 'trust' more the observation and, therefore, the angle estimate does not diverge.
I have also implemented a script which optimizes the fix parameters (variances of the process noise and measurement noises) using an external angle reference. This way it is easier to bound their value.
It is also important to notice that the value of R and Q will depend on the intensity of the movement, i.e. the amount of linear acceleration 'corrupting' the accelerometer estimate. To increase the precision of the estimation I have implemented an intensity detector which varies for each sample the value of R and Q depending on the intensity of the motion. If you are interested, please contact me on: alberto.olivares (gmail.com) and I will happily send it to you (or any other person who is interested).

A: Currently I am testing both the EKF and the Complementary Filter performances to estimate the attitude with sensor fusion (gyro, acc, mag) in the quaternion form. The ultimate scope is to get different velocity estimates. At the moment I have a Nonlinear Complementary Filter that does a good job to estimate the attitude, then I subtract the gravity and integrate to get the velocity. It works fine on the short period.
Take this code as mine and consider that the measured output of my EKF are the accelerometer readings where the inertial acceleration is NOT negligible. Hence, my predicted output matrix "h" the result of z = T*acc, where T is the transformation matrix from sensor to local frame and acc are the accelerometer readings affected by the gravity. Assume there are almost no yaw rotations, but just significant partial rotations (<90deg) around pitch and roll.
The thing I cannot explain by myself is that EKF performs better if I consider negligible the inertial acceleration than when I consider that significant inertial accelerations are measured. Due to the movement I want to observe, I need to consider inertial accelerations though.

A: I have been contacted by some people having similar issues as the one stated in the first post. I would like to include a Github repository of mine where you will find a complete library to estimate the orientation using a MIMU.
The methods included are: Acceleration and magnetic field projections (this one is just to show why fusion is necessary), Regular Kalman Filter, a Extended Kalman Filter, Gated Kalman Filter and a Gated Extended Kalman Filter.
You will also find a paper explaining the process and the slides I used in the conference where I presented the paper.
Everything is commented thoroughly so I hope you are able to understand what is done in each step.
Let me know if you have any doubts about it.
https://github.com/aolivares/inmed2014
Cheers!


text:
Q: Parallel::ForkManager takes too much time to start 'finish' function I use the regular Parallel::ForkManager module in Perl. I execute around 10 children processes. 'passes_thresholds' function takes few milliseconds or nanoseconds (checked it). In case I run all processes one by one (without Parallel::ForkManager) the whole process took 80-250 milliseconds. In case I run them as parallel, the whole process takes at least 1 second. I found that the Fork spends 1 second to start the 'finish' function. I put a timer when the child process finished his job and should go to 'finish'- function. One second is too much for my development.
sub parallel_execute {
    my $this = shift;
    foreach my $a (@a_array) {
        my $pid = $this->{fork_manager}->start and next;
        my $res = $a->passes_thresholds();
        $a->{timer} = Benchmark::Timer->new();
        $svc->{timer}->start;
        $this->{fork_manager}->finish(0,{a => $a, plugin_result => $res});
    }
}

$this->{fork_manager}->run_on_finish( sub {
    my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_;
    my $a = $data_structure_reference->{a};
    if (exists $a->{timer}) {
        $a->{timer}->stop;
        debug "took: " . $a->{timer}->report;
    }
});

Do you have any idea why it took at least 1 second to start the 'finish' command?
(I am using Unix server, and perl 5.10)

A: Thanks you all, i found the problem. ForManager module has 'waitpid_blocking_sleep' parameter, which defined as 1 second by default. There is a function called 'set_waitpid_blocking_sleep' which we can defined this parameter (sleep time). We can set zero or fraction of seconds. I set this paramter to zero and it fixed my issue.

A: The on_finish callback is only called when P::FM reaps a child, and P::FM only reaps a child under three conditions:

*

*When $pm->start is called and the number of children that have been started but not reaped is equal to the maximum.

*When $pm->reap_finished_children is called.

*When $pm->wait_all_children is called.

There could be an arbitrarily long delay between a child exiting and one the above events. Adding the following to your program should eliminate that delay:
$SIG{CHLD} = sub { $pm->reap_finished_children };

By the way, if the work performed by your child only takes "a few milliseconds or nanoseconds", you are actually slowing things down by using P::FM. Data passed to finish gets serialized and written to disk, then read from the disk and deserialized for the on_finish callback!


text:
Q: Using Git Desktop and USB stick for Version Control I am trying to use git and making USB stick as my private remote server(could move to another computer easily and work in a 3-4 people small group) for my code version control and backup. As I would like to have a fancy interface to show my readme and commit history list, so I am trying to use Git Desktop in Windows, but I found I can't achieve my goal like showing readme, push commits to USB stick. Is there any suggestion for me so that I could achieve?

A: On your machine you'd want to clone the repo to the USB stick, and then add it as a remote on every machine you work on.
What might be simpler is to put an 'authoritative' repo on a network share or something and again add it as a remote.
However, before you proceed, understand that both of these methods effectively turn your distributed version control system into a centralized one.


text:
Q: What is the difference between these two regular expressions Sorry for asking this dumb question, but I just want to make sure I am doing right.
What is the difference between
^Sentence.*$

and
^Sentence.*

I usually use the first one, but I want to make sure which is the more appropriate.

A: It's depend of the context (i.e. the string).
The $ means by default: end of the string
And the quantifiers, like *, are by default greedy.
If the string doesn't contain a newline character, the two patterns are exactly the same. (in the sense they will match exactly the same strings)
But if your string contain a newline character, the .* will stop before it, because the dot, by default, doesn't match the newline character. So the first pattern will always fail, and the second pattern will only match the first line (if it begins with "Sentence" obviously)

A: From RegExBuddy;;
^ "Assert position at the beginning of a line (at beginning of the string or before a line break character)"
. "Match any single character that is not a line break character"
* "Between zero and unlimited times, as many times as possible, giving back as needed (greedy)"
$ "Assert position at the end of a line (at the end of the string or before a line break character)"

HTH.
http://www.regular-expressions.info/


text:
Q: С чем связано ограничение названия переменной в 251 byte в Perl? Это ограничение операционной системы или самого Perl? И можно ли на это как-то влиять?

A: Это ограничение самого perl
Источник: https://perldoc.perl.org/perlvar.html


text:
Q: A general Chinese Remainder Theorem
Let $R$ be a ring. If $I_1,\ldots, I_k$ are ideals of $R$ and for all $i$:
$$I_i + \bigcap_{j\neq i} I_j = R$$
then for all $a_1,\ldots,a_k \in R$, there exists some $a \in R$ such that for all $i$, $a \equiv a_i \pmod{I_i}$

I could prove this for $k=2$: for $a_1,a_2 \in R$, $a_1 - a_2 \in I_1 + I_2$, so there are $i_i \in I_i$ such that $a_1 - a_2 = -i_1  + i_2$. Hence $a_1 + i_1 = a_2 + i_2 = a$, and $a \equiv a_i \pmod{I_i}$ for $i=1,2$.
I couldn't prove the general case. Any help?

A: Hint for the inductive step:
Suppose $I_1,\dots, I_k,I_{k+1}$ are ideals in $R$ such that for any $1\le i \le k+1$,
$$I_i+\bigcap_{\substack{1\le j \le k+1\\j\ne i}}I_j=R. $$
Then, a fortiori, we have for any $1\le i \le k$,
$$I_i+\bigcap_{\substack{1\le j \le k\\j\ne i}}I_j=R. $$
So, given $a_1, \dots, a_k, a_{k+1}\in R$, there exists some $a\in R$ such that
$$a\equiv a_i\mod I_i\quad(1\le i\le k)$$
and $a$ is unique mod. $\displaystyle\bigcap_{j=1}^k I_j$.
Can you end the inductive step?
Some more details:
Note that if $J=\displaystyle\bigcap_{j=1}^k I_j $, we have $J+I_{k+1}=R$.
So we have to find $A\in R$ such that \begin{cases}A\equiv a& \mkern-12mu\bmod J\\A\equiv a_{k+1},&\mkern-12mu\bmod I_{k+1}.\end{cases}
which is possible by the case $k=2$, and the solution is unique modulo $J\cap I_{k+1} =\displaystyle\bigcap_{j=1}^{k+1} I_j$.

A: Hint $ $ It is easy if we view the solutions as "vectors" in the product ring $\,  (R/I_1,\ldots, R/I_k).\,$ Then every such congruence is solvable iff the natural image of $R$ in the product ring is onto iff the image contains all unit vectors $e_j$ with $1$ in the $j$'th component and $0$ in all others, since they span, e.g. $$(a_1,a_2,a_3) = a_1(1,0,0)+a_2(0,1,0)+ a_3(0,0,1) = a_1 e_1 + a_2 e_2+ a_3 e_3$$
But the hypotheses imply that unit vector systems are solveable, since by hypothes $\,a+b = 1\,$ for $\,a\in I_j,\ b\in I_i, \forall\, i\neq j$ so $\,e_j := 1\!-\!a = b\,$  $\,\Rightarrow\,e_j\equiv 1\pmod{I_j},\ $ $e_j\equiv 0\pmod{I_i},\forall\,i\ne j$
Remark $ $ The classical CRT formula for integers is a special case, where the unit vectors are constructed by the formula
$\qquad  e_j := M_j(M_j^{-1} \bmod m_j)\,$ where $M_j$ is the product of all moduli except $m_j$
Note $\,M_j \equiv 1\pmod{m_j}\,$ and $\,M_j\equiv 0\,$ mod other moduli since they divide $\,M_j$


text:
Q: Patch & Update requests to remarketingAudiences returning 500 error I am trying to patch or update Remarketing Audiences using the Google Analytics Management API. However, when I do so, I keep getting a 500 error. Here is an example of the audience I'm trying to patch/update:
{u'linkedAdAccounts': [{u'linkedAccountId': u'679-395-yyyy', u'type': u'ADWORDS_LINKS'}], u'linkedViews': [xyz], u'name': u'Test - 123', u'audienceType': u'SIMPLE', u'audienceDefinition': {u'includeConditions': {u'daysToLookBack': 30, u'isSmartList': False, u'segment': u'users::condition::ga:browser==Safari', u'membershipDurationDays': 30}}}

The problem does not occur for inserting, however. Any ideas on what might be going on?

A: A 500 error might result during heavy load or for larger more complex requests. Try to use a shorter time period or reduce the complexity of the request, for example by removing the segment and check if the error persists.


text:
Q: Is it possible to create an OpenGL 4+ context within GTK / GtkGLExt? To avoid unnecessary UI coding for a small 3D application, I would like to use GTK to create the necessary widgets. But I don't see a possibility to create a core 4+ context with GtkGLExt?
Update: 13 Apr. 15:
I recently found the following article halting problem :: Using OpenGL with GTK+ about this topic. Perhaps this could become useful for others.
However, the missing possibility to query and select the core-profile version is an indication that the usage is still limited to OpenGL 3.2 (Released in 2009).


text:
Q: Print out hyperlink in Jenkins console output using Python I am triggering a python script through a Jenkins job, and would print a hyperlink in the Jenkins console output. Is there a Jenkins plugin or python module I can use to achieve this.
From a test script, I tried doing this - echo 'print "http://www.google.com>Google"' but on console output it simply displays that as raw text and not as a hyperlink (It does make the http url link clickable).
I am aware that this will work correctly in case of HTML file

A: You may try ANSI Color plugin it shall auto convert it to hyperlink. I tried with java it works, you may try with Python :)

A: Install the anything-goes-formatter
https://wiki.jenkins-ci.org/pages/viewpage.action?pageId=60915753
Enable the Markup formatter on global configuration (security section)
http://127.0.0.1:8080/configureSecurity/

A: It took me a while to figure this out from Groovy code (jenkinsfile), but I knew there has to be a way as steps/plugins can do it.
In this case you need ModelHyperlinkNote (https://javadoc.jenkins-ci.org/hudson/console/ModelHyperlinkNote.html) and its static methods; so for a link to Job started you'd do:
final Run buildRun = Jenkins.instance.getItemByFullName(buildJobName
  ).getBuildByNumber(runId) as Run
final String link = ModelHyperlinkNote.encodeTo(buildRun)

and then you can simply write that value to log and Console Log will interpret it and add widget with all relevant operations.
In addition to type-specific methods, there is general-purpose encodeTo(String url, String text) that allows links to other kinds of entities.


text:
Q: What can potentially cause CMS routines:CMS_SIGNERINFO_VERIFY_CERT:certificate verify error? I am trying to verify the signer cert based on its issuer CA cert. I am using following OpenSSL API to verify the certs.
int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, X509_STORE *store, BIO *indata, BIO *out, unsigned int flags);

The first parameter contains the base 64 encoded message.
The second parameter is the Stack of both CA and signer certs,
The third parameter is the pointer to the cert store,
The fourth and fifth parameter is BIO pointers.
The last parameter is set to 0.
When I try to verify signer certificate based on the CA certificate I get
CMS routines:CMS_SIGNERINFO_VERIFY_CERT:certificate verify error

The issuer certificate for the signer cert is the CA cert and both CA and signer cert is valid.
Does anyone know what could be causing this verification failure? And any ways of getting around it?


text:
Q: When I open a python shell in powershell, I cannot close it When I open a python shell in PowerShell, I cannot close it using Ctrl+c, Ctrl+z, or Ctrl+d. I swore it worked before, it works in VS Code's terminal as well, so I'm not quite sure what is wrong with powershell. The only way to exit is using the quit() function.
When I do Ctrl+c, I get
KeyboardInterrupt

Ctrl+d gets me
^d

and likewise for Ctrl+z
Info:

*

*Windows 10

*python 3.8.0

A: According to this answer, eof on Windows is different from *nix.
It is Crtl + z on Windows that gives you end of file, not Crtl + d.
Therefore, press Crtl + z and enter should do the trick.


text:
Q: Understanding of Static variables across cluster environment We have been trying to implement some sort of Cache mechanism where we are trying to render  list of Objects through a plugin. These list of values are then held in a concurrent hash map within a class . We are creating a Instance of the class when required through UI and referring to this cache to display the list of values. The cache is refreshed either via online button or  a overnight job(also program loads cache if empty/null) .
This was working okay until we were in single cluster. As we moved to cluster environment and when we added a new/amend Objects on other system(interacted via plugin), the list is refreshed only on batch-cum-online server and the other cluster is out of sync. This issue is happening intermittently and now having a doubt on static variables. Is static variables created one each for separate jvms? If so, is it synchronized on some way. Also any hint on why this is intermittent(we doubted if there was a out of cluster during batch run - but not sure) .
private static Map _cache = new ConcurrentHashMap(16, 0.75, 1)
java version 1.6
using IBM WAS server

A: Of course your static variable only live and meaningful inside the JVM it's created.
To address this issue, you can trick by sending update request to all other server when your batch sync complete.
But the formal way is to separate your cache storage into a standalone server (like redis) instead of a static variable


text:
Q: Expected ':' Lexical or Preprocessor error Well this should be a pretty quick and easy question. I am creating a scrollview and i have it all done, but there is an error that i just dont understand it! like its just confusing and  doesnt make sense to me!
THE ERROR:  // Expected ':'
ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{

}
@property (weak, nonatomic) IBOutlet UIScrollView *ScrollView;

@end

ViewController.m
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
[self ScrollView setScrollEnabled YES]    // Expected ':'
[self ScrollView setContentSize: CGSizeMake(320, 900)]
}

EDIT:
I did all of this and it just says expected identifier.
[super viewDidLoad];
[self.ScrollView setScrollEnabled: YES];
[[self.ScrollView setContentSize: CGSizeMake(320, 900)]];    //expected identifier

A: It looks like you are missing a colon, a couple of dots, and a couple of semicolons:
[self.ScrollView setScrollEnabled:YES];
//   ^                           ^    ^
[self.ScrollView setContentSize:CGSizeMake(320, 900)];
//   ^                                                ^

You need to watch out for these small elements of the syntax - Objective C does not tolerate deviations. The worst part about syntax errors is that you often get a report pointing to a wrong line.

A: There are quite a few problems with that line.
[self.ScrollView setScrollEnabled: YES];
     ^                           ^     ^
     ^
//I've assumed this was supposed to be either self.ScrollView or _ScrollView
//I can't tell if you are using a custom getter.

A: [[self.ScrollView setContentSize: CGSizeMake(320, 900)]];
^                                                      ^
|                                                      |

Remove these two.


text:
Q: How many license plates could begin with A and end with Zero Suppose that  in a certain state , all automobile license plates have four letters followed by three digits.
A)  How many license plates could begin with  A and end with Zero
B)  How many plates are possible in which all the letters and digits are distinct?

A: Have you drawn a picture? It's usually quite a good strategy. In case a) the picture is something like
$$A,\_,\_,\_,|\_,\_,0$$
You have 26 choices for each of the first 3 empty slots and 10 choices for the remaining 2 slots. I'm guessing you can take it from here.
For case b) you have 26 choices for the first slot
$$26,\_,\_,\_,|\_,\_,\_$$
The next slot must be different from the previous so there are 25 choices for the next slot
$$26,25,\_,\_,|\_,\_,\_$$
Can you finish it off?


text:
Q: Javascript - Constructor's properties & Prototype I'm trying to understand one thing about constructors. Namely I don't understand how function object's properties, aka constructor's properties can't be accessed using Foo.prototype.property, example:
//let's create new function object with predefined properties
function Foo() {
    this.name = "Mike";
    this.returnName = function() {
                       return 'This persons name is ' + this.name + '.';
                      };
};

//now let's create new object using constructor and prototypal inheritance
var mike = new Foo();

mike.returnName(); //returns "This persons name is Mike."

I understand that mike inherits properties from Foo's prototype. So these properties must be present inside of the prototype. new object points toward the prototype with internal prototype link using __ proto __. I get that.
Thing that I can't get around is how this doesn't work:
Foo.prototype.returnName();

Constructor has .prototype link with prototype property and vice versa prototype has .constructor link with the Foo.
I know that calling the Foo();
function first then calling for window.returnName(); would return the    sentence, since this context is set to window.
Is this because when I call the method using prototype it assigns it to the window? Is there any way I could access/call this constructor's property?

A: You are not specifying returnName on the prototype of Foo. If you would do it like this:
function Foo(){
    this.name = "Mike";
}

Foo.prototype.returnName = function(){
   return 'This persons name is ' + this.name + '.';
};

var mike = new Foo();

mike.returnName();

Things would be different.

A: The function returnName is not assigned to the prototype of Foo. Instead it's assigned to every instance of Foo, just like the name is "Mike".
Whenever you call new Foo() a new context is created, this is the this context of that instance.
If you call Foo() directly (without new) this is the global object (window).


text:
Q: Is there a way to collect a map using "groupingBy" for MULTIPLE elements within a nested structure? First, a bit of context code:
import java.util.*;
import java.util.concurrent.atomic.DoubleAdder;
import java.util.function.Function;
import java.util.stream.Collectors;

class Scratch {

  static enum Id {A, B, C}
  static class IdWrapper {
    private final Id id;
    public IdWrapper(Id id) {this.id = id;}
    Id getId() { return id; }
  }

  public static void main(String[] args) {
    Map<String, Object> v1 = new HashMap<>();
    v1.put("parents", new HashSet<>(Arrays.asList(new IdWrapper(Id.A), new IdWrapper(Id.B))));
    v1.put("size", 1d);

    Map<String, Object> v2 = new HashMap<>();
    v2.put("parents", new HashSet<>(Arrays.asList(new IdWrapper(Id.B), new IdWrapper(Id.C))));
    v2.put("size", 2d);

    Map<String, Map<String, Object>> allVs = new HashMap<>();
    allVs.put("v1", v1);
    allVs.put("v2", v2);

The above represents the data structure I am dealing with. I have an outer map (key type is irrelevant), that contains inner "property maps" as values. These inner maps use strings to lookup different kind of data.
In the case I am working on, each v1, v2,... represents a "disk". Each disk has a specific size, but can have multiple parents.
Now I need to sum up the sizes per parent Id as Map<Id, Double>.
For the above example, that map would be {B=3.0, A=1.0, C=2.0}.
The following code gives the expected result:
    HashMap<Id, DoubleAdder> adders = new HashMap<>();
    allVs.values().forEach(m -> {
        double size = (Double) m.get("size");
        Set<IdWrapper> wrappedIds = (Set<IdWrapper>) m.get("parents");
        wrappedIds.forEach(w -> adders.computeIfAbsent(w.getId(), a -> new DoubleAdder()).add(size));
    });

    System.out.println(adders.keySet().stream()
            .collect(Collectors.toMap(Function.identity(), key -> adders.get(key).doubleValue())));

But the code feels pretty clunky (like the fact that I need a second map for adding up the sizes).
I have a similar case, where there is always exactly one parent, and that can easily be solved using
collect(Collectors.groupingBy(...), Collectors.summingDouble(...);

But I am lost for the "multiple" parents case.
So, question: can the above transformation to compute the required Map<Id, Double> be rewritten using groupingBy()?
And just for the record: the above is just a mcve for the problem I need an answer for. I understand that the "data layout" might look strange. In reality, we actually have distinct classes representing these "disks" for example. But our "framework" also allows for accessing the properties of any object within the database using such IDs and property names. And sometimes, when you have performance issues, then fetching data in such a "raw property map" way is orders of magnitude faster compared to accessing the true "disk" objects themselves. In other words: I can't change anything about the context. My question is solely about rewriting that computation.
( I am constrained to Java8 and "standard" Java libraries, but additional answers for newer versions Java or nice non-standard ways of solving this will be appreciated, too )

A: Here's a single stream pipeline solution:
Map<Id,Double> sums = allVs.values ()
                           .stream ()
                           .flatMap (m -> ((Set<IdWrapper>)m.get ("parents")).stream ()
                                                                             .map (i -> new SimpleEntry<Id,Double>(i.getId(),(Double)m.get ("size"))))
                           .collect (Collectors.groupingBy (Map.Entry::getKey,
                                                            Collectors.summingDouble (Map.Entry::getValue)));

Output:
{B=3.0, A=1.0, C=2.0}

The idea is to convert each inner Map to a Stream of entries where the key is an Id (of the "parents" Set) and the value is the corresponding "size".
Then it's easy to group the Stream into the desired output.


text:
Q: Installing/Configuring Zend Debugger for Eclipse PDT I`m unable to configure in IDE or install properly Zend debugger.

*
*Installed php5.6 libapache2-mod-php5.6 and so on.

*Downloaded Zend debugger for php5.6 separate from other zend stuff. (It last available separate from zend studio, thats why I choose php5.6)

*Copy dummy.php to document root, check in browser it works(empty page without errors)

*Add following to php.ini:

  $ tail -n 10 /etc/php/5.6/apache2/php.ini
  [Zend]
  zend_extension="/usr/lib/php/20131226/ZendDebugger.so"
  zend_debugger.allow_hosts=127.0.0.0/8,192.168.0.0/16
  zend_debugger.expose_remotely=1
  zend_debugger.connector_port=10137

Do configure debugger in eclipse>Window>PHP>Servers>Localhost>Edit:
local server configure
debugger settings for server
global debugger settings
Error occurred: click on test button in debugger settings
Error occurred: return to global debugger settings
Try to debug:
click on debug as>php web application
What I`m doing wrong? Reading a lot of pages, all give similar instructions as above. Please help.
Also posting phpinfo() screenshot, all seems fine there:
 - zend debugger settings
 - zend modules
UPDATE: I found a solution, for thus who interested read the post bellow. Site does`t accept it as answer yet.

A: Zend Debugger installed from separate bundle not working with PHP5.6. Problem in Zend opcache module. Seems they loaded in incorrect order.
Disabling zend opcache makes the solutions. Debugger work fine. But it possible to make work both this way:
Comment out it in config: (cli version seems to be symlink as also disabled)
lenya@JabbaDesktop:~$ sudo nano /etc/php/5.6/apache2/conf.d/10-opcache.ini
; configuration for php opcache module
; priority=10
; zend_extension=opcache.so

At bottom of /etc/php/5.6/apache2/php.ini:
[Zend]
zend_extension="/usr/lib/php/20131226/opcache.so"
zend_extension="/usr/lib/php/20131226/ZendDebugger.so"
zend_debugger.allow_hosts=127.0.0.0/8,192.168.0.0/16
zend_debugger.expose_remotely=1
zend_debugger.connector_port=10137

First two lines(.so) should be exactly in this order.
Installing debugger "how to" easy to find in google. No one mention above problem.


text:
Q: how to List or highlight all class field used in a method of the same class? class A{
    private Object a;
    private Object a1;
    private Object a2;

    public void method(){
        // Tons of code
         code line using a;
        // Tons of code
         code line using a1;
    }
}

Now i want to list or highlight all fields used in method().. i.e result should be list of a, a1 or highlighted a,a1 in method body.


text:
Q: VB6 read barcode while program is running in background i have a problem to make a program that can read Barcode.
What i want to do is a program (maybe a service? i don't know) that can capture barcode from a barcode scanner while is running in background.
I have found that i can check if is plugged in a specific barcode scanner with his VID/PID, here some code:
Set wmi = GetObject("winmgmts://./root/cimv2")

Dim VID As String
Dim PID As String

   'Barcode scanner
   VID = "VID_040B"
   PID = "PID_6510"
   'REV = "REV_0120"

   For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice")
     If InStr(d.Dependent, VID & "&" & PID) > 0 Then
       Debug.Print ("Barcode Scanner found it!")
       Debug.Print wmi.Get(d.Dependent).Description
     End If
   Next

How can I do that is read by my program only the input of my barcode scanner?
Thank you in advance.


text:
Q: VOLATILE required in single core multi Threaded environment? Do I need to use VOLATILE variable, if I am on a single core machine & multi Threaded environment
From my understanding, Threads do not have a cache space of their own.
They use the cache of the core they are running in.
Now if it is a single core machine, they will all be sharing the same cache.
Please correct/addMore over my understanding

A: The compiler can also reorder instructions.
For example:
class SomeRunnable implements Runnable{
  public boolean stop;

  public void run(){
     while(!stop)
         println("hello");
  }
}

Since the stop variable isn't marked as volatile (or used in a synchronized block), the compiler is free to transform the above code to:
class SomeRunnable implements Runnable{
  public boolean stop;

  public void run(){
     if(stop)return;
     for(;;)
         println("hello");
  }
}

This optimization is called 'loop invariant code motion'. The reason this optimization is done is to reduce the overhead of reading 'stop'; what is the point of reading it, if it doesn't change in the loop.
It is best not to think in terms of caches because:

*

*unless you know what you are talking about, probably you don't understand it correctly

*it depends on the CPU architecture.

If you want to understand Java concurrent, then you need to understand the Java Memory Model.


text:
Q: Custom class implementing interface IDictionary that could be static? This is a bit Software Engineering and C# question. It seems to me this question will end up all about what c# CAN do so I'll post it here first.
I have a project that has multiple classes that need to access the same dataset. I have created a custom class for that dataset that has a private Dictionary<byte[], MyCustomInterface> instance. The class implements IDictionary<byte[], MyCustomInterface>. For the methods and properties I just wrap the private dictionary methods and properties. I have then added some methods and properties of my own dedicated to my specific needs.
As I said I need access to the custom dictionary and it's data in many classes. I tried making my custom class static but can't because it implements interfaces.
I could make a database in the background but that would be a way heavyweight solution. I have done this before but it ends up being a lot of maintenance.
What other ways would be available to have access to the same set of data/same class from all my classes? I need to be able to serialize/deserialize this custom data set and save the data in a file for retrieval later. I'd prefer to not give up on using Interfaces, they're really handy.
public class EntityDictionary : IDictionary<byte[], IDispenseEntity>
{
    private Dictionary<byte[], IDispenseEntity> _backing = new(new ByteArrayComparer());

    public IDispenseEntity this[byte[] key]
    {
        get => _backing[key];
        set => _backing[key] = value;
    }

    public ICollection<byte[]> Keys => _backing.Keys;

    public ICollection<IDispenseEntity> Values => _backing.Values;

    ...
    //My custom properties and methods
}

A: Singleton pattern?
public class EntityDictionary : IDictionary<byte[], IDispenseEntity>
{

    private EntityDictionary() {}
    static EntityDictionary() {}
    private static _instance = new EntityDictionary();
    public static Instance { get { return _instance; }}

    ...

}

So there is only one dictionary that's shared by all uses, you can;t create your own instance, and are forced to use the single instance.


text:
Q: Excel manipulating columns I want to build a formula in which it looks at a column in excel and if the column contains x as the value, it then finds the max of a different column.
For example. = IF(F:F = "rate", Max(k:k)) but this columns up as a value error. Could someone show me how to correctly write this formula.
Thanks

A: Hello and welcome to SO - Next time, try to also show what you have tried yourself to solve the issue. This page should help.
{=MAX(IF(F:F="rate",K:K,""))}

enter as arry formula: ctrl+shift+enter


text:
Q: Can I disable error/exception handling in Silex? I'm building an app based on Silex 1.3.  This is my first encounter with Silex, so I'm not very familiar with it.
I'd like to use my own error/exception handler, which is basically a class that registers itself and then will catch all errors, fatal errors, and uncaught exceptions and handle them, either with Whoops in development, or a graceful handler in production.
However, once I'm inside a silex controller, middleware, whatever, Silex will take over and use it's own error handling. Mine will still catch fatal errors, since Silex apparently doesn't hook into shutdown, but everything else is replaced with the default "Something went wrong" page from Silex.
I do understand that I can use $app->error() to override HOW Silex handles errors, but I haven't found a way to set things back to the original ErrorHandler from there, or to override WHETHER Silex handles errors.
So, does anyone know how to either a) tell Silex to use my error handler, using $app->error() or some other way, b) just disable error handling in Silex entirely, or c) as a last resort, get Silex to catch fatal errors so I can handle all three types from within $app->error()?
Since this is my first time using Silex, feel free to correct me or show me how you handle errors in Silex if there's a better way, but please also answer the question if you can.
Some example code:
// This will register itself and then handle all errors.
$handler = new ErrorHandler();

// These are all handled appropriately.
nonexistentfunction();            // Correctly caught by ErrorHandler::handleFatalError
trigger_error("example");         // Correctly caught by ErrorHandler::handlePhpError
throw new \Exception("example");  // Correctly caught by ErrorHandler::handleException

$app = new \Silex\Application();
$app->get('/', function () use ($app) {

    // This is still handled correctly.
    nonexistentfunction();            // Correctly caught by ErrorHandler::handleFatalError

    // However, these are now overridden by Silex.
    trigger_error("example");         // INCORRECTLY DISPLAYS SILEX ERROR PAGE.
    throw new \Exception("example");  // INCORRECTLY DISPLAYS SILEX ERROR PAGE.

});
$app->run();

And a very simplified ErrorHandler for reference:
Class ErrorHandler
{
    public function __construct()
    {
        $this->register();
    }

    private function register()
    {
        register_shutdown_function( array($this, "handleFatalError") );
        set_error_handler(array($this, "handlePhpError"));
        set_exception_handler(array($this, "handleException"));
    }

    // Etc.

}

A: I know the option the (b) you can entirely disable Silex app error handler and after that, your custom error handler should work fine as you defined it.
Entirely disabled Silex error handler:
$app['exception_handler']->disable();

So, It will be like:
require_once  'Exception.php'; # Load the class
$handler = new ErrorHandler(); # Initialize/Register it

$app = new \Silex\Application();
$app->get('/', function () use ($app) {

    nonexistentfunction();
    trigger_error("example");
    throw new \Exception("example");

});
$app->run();

A: Please note that ExceptionHandler::disable() has been deprecated in 1.3 and removed in 2.0. So:
In Silex before 2.0:
$app['exception_handler']->disable();

In Silex 2.0+:
unset($app['exception_handler']);

A: See Silex doc
Seemingly, you need to register an ExceptionHandler as well. Silex will turn fatal errors to exceptions in order to deal with them. Also, if I remember correctly, exceptions of this kind will be caught when 'thrown' inside controllers and middlewares (at least before middleware), but not inside models.
At the end, you can add the following to work with handling things.
// register generic error handler (this will catch all exceptions)
$app->error(function (\Exception $e, $exceptionCode) use ($app) {
    //if ($app['debug']) {
    //    return;
    //}

    return \Service\SomeHelper::someExceptionResponse($app, $e);
});

return $app;

I hope that helped a little.

A: You have to register specific provider in your app:
https://github.com/whoops-php/silex-1


text:
Q: How to solve $\phi(n)=n$ for $n$? I wish to solve $\phi(n)=n$ for $n$ where $\phi(n)$ is the Euler's Totient function.
I solved this by splitting this into three possible cases:

($1$) $n$ is prime
($2$) $n$ is composite
($3$) $n=1$.

($1$) gives contradiction as $\phi(n)=n-1\not=n$.
($2$) gives contradiction as $\phi(n)\geq\frac{1}{2}n$.
($3$) Works and is the only left choice so we conclude that $n=1$.
Is there a nicer way to answer this question?

A: There are only $n-1$ positive integers below $n$, so unless $\gcd(n, n) = 1$ we must have $\phi(n)\leq n-1$.

A: Note that $$n=\phi(n)=n\prod_p\left(1-\frac1p\right)=n\implies\prod_p\left(1-\frac1p\right)=1$$ which does not hold for any primes $p$, forcing $n=1$.


text:
Q: Is it better to split sequences into overlapping or non-overlapping training samples? I have $N$ (time) sequences of data with length $2048$. Each of these sequences correseponds to a different target output. However, I know that only a small part of the sequence is needed to predict this target output, say a sub-sequence of length $128$.
I could split up each of the sequences into $16$ partitions of $128$, so that I end up with $16N$ training smaples. However, I could drastically increase the number of training samples if I use a sliding window instead: there are $2048-128 = 1920$ unique sub-sequences of length $128$ that preserve the time series. That means I could in fact generate $1920N$ unique training samples, even though most of the input is overlapping.
I could also use a larger increment between individual "windows", which would reduce the number of sub-sequences but it could remove any autocorrelation between them.
Is it better to split my data into $16N$ non-overlapping sub-sequences or $1920N$ partially overlapping sub-sequences?

A: You are correct to question the dependence between succecssice slices of training data as indeed they are not fully independent samples. That said, I suggest using these partialy overallaping sub-sequences, i.e. the widely-used sliding-window approach when training. It is very common for (D)NNs; Keras even has a pre-defined function to do exactly that timeseries_dataset_from_array.
There are not hard absolute rules on the choice of window sizes or their overlap. For example, even in simple ARIMA application it is unclear if a fixed size window or a fixed origin window is always better than another. What is though very likely is  that using non-overlapping sequences will not provide enough samples to train experessive models as DNNs (LSTM?). If we are very worried about leakage we might use "purging" (not a commonly used term in my opinion). In effect we create a buffer between our training and test data. That way while training there is "some overlap" between samples' training features and the response, when testing no time-point $t_i$ from training appearing in the test set  (see Lopez de Prado (2018) "Advances in Financial Machine Learning" Chapt. 7 Cross-validation in Finance for more details). I have not seen this approach being widely used but it might be worth exploring. In any case, I would urge checking, after establishing some notion of stationarity, the ACF/PACF plot of the series to get an idea of what potential time-lagged correlations we might expect.
Finally, I think it is worth emphasing that it preprocessing the time-series data at hand is rather relevant. Especially if the time-series exhibit strong seasonlity, although a DNN should be able to deal with them well, it often helps to remove the seasonality before applying a DNN procedure.


text:
Q: One-page website + AJAX + History.js + googlebot I am building a sliding one-page website with the following structure:

    // AJAX action fires on document ready (jquery) and loads ALL pages in here
    // then I slide to the correct page-panel found via URL

    // Normal rendering of the SINGLE page that was requested by the url

I am using History.js, so I don't have hashbanged URLs. All (menu-)links to the several pages are just normal links with a data-page attribute that return false by JS.
I want google to index all pages seperately.
The problem I am facing is that all documentation I found about ajaxed websites state that google needs hashbangs.
So if I only have normal URLs in my href tags, google won't do any ajax actions, right?
Other question: Google will read the  tag. But as the content of the noscript is different than content shown to users, will google see this approach as cloaking?
Google states:

Ensure that you provide the same content in both elements (for instance, provide the same text in the JavaScript as in the noscript tag). Including substantially different content in the alternate element may cause Google to take action on the site.

What do you think about this approach?

A:
So if I only have normal URLs in my href tags, google won't do any ajax actions, right?

Correct.

But as the content of the noscript is different than content shown to users, will google see this approach as cloaking?

No. Cloaking is intentionally showing different content to search engines then to your users for the purpose of manipulating search results. Using  this was is good usability as any non-JavaScript user, which includes some human beings with JavaScript turned off, can still use your website. So what you're doing is a good thing.


text:
Q: LDAP Bind request failing I have a Windows Server 2008 R2 Active Directory domain controller with domain madhurmoss.com
I have a Linux box which is trying to connect to LDAP (389) on above box, which is failing.
Upon inspection in Wireshark, I see a bind request with following query
sAMAccountName=Administrator,DC=madhurmoss,DC=com
and result with
invalid Credentials 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db0
I want it to connect it through Administrator which lies in
CN=Administrator,CN=Users,DC=madhurmoss,DC=com
The supplied credentials are correct. I believe the query sAMAccountName=Administrator,DC=madhurmoss,DC=com is wrong.
Can anyone guide me what could be wrong ?

A: Use CN=Administrator,CN=Users,DC=madhurmoss,DC=com as your binddn string. That should do it.

A: I usually use Apache Directory Studio to graphically browse to what is needed and then I right click and Copy DN from there. Makes things a ton easier. Not that LDAP formatting is tricky but it has saved me on typos, switching CN for OU, etc.
Give a go with that and see how it works. Plus, it'll let you know if it is a permissions issue you are having.

A: The string sAMAccountName=Administrator,DC=madhurmoss,DC=com isn't a valid X.500 definition.  The attribute sAMAccountName is a valid attribute for all Security Principals, but it's not a valid X.500 node type (DC, OU or CN are).  I'd be looking at your LDAP bind definition.  What LDAP implementation are you using?


text: Q: Problems with mariadb create trigger I have 2 tables (tasks - where adding new tasks with user phone and his company id and tenant_phones_comp - where i add only 2 col: user phone and user company id) and i try to create a trigger at mariadb server. Trigger must insert row to tenant_phones_comp after inserted new line at tasks and if phone and company_id of that new task is not exists in tenant_phones_comp table insert them from new record in tasks. I have problem when i try to create triger. example here


text:
Q: Loop through list elements I have a page with an unordered list built like this:

155Section 1

248Section 2

856Section 3

What I would like to do is after the page loads have some jQuery code loop through all the
248
numbers and convert the numbers into hh:mm:ss. So that 248 becomes 2:08. I think I can probably find somewhere else how to convert the seconds into hh:mm:ss, but what I don't know how to do is loop through each span element and replace it with the result of the conversion.
Thanks

A: you can try
$("span").each(function(){
 var text = $(this).text();//get the currently looped span's text
 //your conversion code here
 $(this).text(/*calculated hh:mm:ss here*/);
});


text:
Q: What is this specific method called? I'm curios as to what this specific method is called:
public Word(String word) {
    this._word = word;
}

Thanks in advance!

A: This is called a constructor. In this case, it would be for a Word object. It takes parameters to assign values to instance variables (in this case, the String word.)
Here is a link to the Oracle documentation on providing constructors in Java for further reference.


text:
Q: Whats the best way to get a Custom Element object for Conditional Elements Using Polymer Dart I often need to get hold of the Polymer-Element object behind one of the child elements.
ButtonElement nextButton;

void inserted()
{
  //Get hold of the elements
  nextButton = shadowRoot.query('#nextButton');
  //Do some thing useful with nextButton
}

<template if="{{emailValid}}">
   <button id="nextButton" on-click="nextStep">
</template>

This works fine. However if in this case nextButton is underneath a conditional template its not part of the DOM when inserted() is called and is therefore not found. Is there anyway other way to get hold of it?
Otherwise I will have to some how determine when that conditional template is displayed and grab it then.

A: This might depend on what exactly "Do something useful with nextButton" means, but the Polymer-ic way to accomplish this is generally to encapsulate any reusable behavior together with the DOM it operates on. That is, instead of including code to operate on #nextButton in the enclosing element's inserted method, create a new custom element, let's call it super-button, and put the relevant code in super-button's ready or inserted method.
Then, if you find some behavior that really should be outside of super-button, follow the same pattern as the on-click handler you use above. Have super-button fire a custom event at the appropriate time and then declaratively map a handler to that event:
<template if="{{emailValid}}">
   <super-button on-click="nextStep" on-my-special-event="mySpecialEventHandler"></super-button>
</template>


text:
Q: Erro em fazer um Insert no banco Estou tentando salvar alguns dados no banco e estou recebendo esse erro:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Ocorrencias_dbo.Alunoes_AlunoId". The conflict occurred in database "aspnet-CEF01-20140410111235", table "dbo.Alunoes", column 'Id'.
The statement has been terminated.

O que acontece é que tenho dois models em minha aplicação: Alunos e Ocorrências(1-n). O relacionamento está certinho, o que acontece é na hora de inserir uma ocorrência me gera esse erro ai em cima. No model de ocorrência, tem que escolher o nome do aluno pra dar a ocorrência a ele, e eu acho que é ai que da o erro, vou colocar a action de create e edit pra ficar mais claro. O que acontece é que ele tenta inserir o Id do aluno, e no caso estou inserindo o nome dele. Enfim, estou meio confuso e queria a ajuda de vocês.
Actions:
 public ActionResult Create()
    {
        //ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome");
        return View();
    }

    // POST: /Ocorrencias/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="Id,Tipo,Causa,Descricao,AlunoId")] Ocorrencia ocorrencia)
    {
        if (ModelState.IsValid)
        {
            db.Ocorrencias.Add(ocorrencia);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome", ocorrencia.AlunoId);
        return View(ocorrencia);
    }

    // GET: /Ocorrencias/Edit/5
    public ActionResult Edit(long? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Ocorrencia ocorrencia = db.Ocorrencias.Find(id);
        if (ocorrencia == null)
        {
            return HttpNotFound();
        }
        ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome", ocorrencia.AlunoId);
        return View(ocorrencia);
    }

    // POST: /Ocorrencias/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include="Id,Tipo,Causa,Descricao,AlunoId")] Ocorrencia ocorrencia)
    {
        if (ModelState.IsValid)
        {
            db.Entry(ocorrencia).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome", ocorrencia.AlunoId);
        return View(ocorrencia);
    }

E quase ia me esquecendo. Estou usando uma biblioteca chamada ASP.net Awesome e nela, on de tem esse Select List ai, eu substitui pelo Helper que tem nessa biblioteca chamado Lookup, que é um popup com uma lista de todos os dados do banco. E para ele funcionar precisa colocar um outro controller dentro da classe pra que ele funcione. Então aqui, vou inserir o controller do Lookup e a view como que ta. Outra coisa que percebi é que, tenho que implementar uma lógica pra salvar e pra editar os dados, pois teria que vir carregados os campos com os dados já cadastrados.
Códigos
AlunoLookupController:
public class AlunoLookupController : Controller
{
    private EntidadesContext db = new EntidadesContext();
    public ActionResult GetItem(int? v)
    {
        var o = db.Alunos.SingleOrDefault(f => f.Id == v) ?? new Aluno();

        return Json(new KeyContent(o.Id, o.Nome));
    }

    public ActionResult Search(string search, int page)
    {
        search = (search ?? "").ToLower().Trim();
        var lista = db.Alunos.Where(f => f.Nome.Contains(search)).ToList();
        return Json(new AjaxListResult
        {
            Items = lista.OrderBy(f => f.Nome).Skip((page - 1) * 7).Take(7).Select(o => new KeyContent(o.Id, o.Nome)),
            More = lista.Count() > page * 7
        });
    }
}

Então explicando esse código: GetItem -> ele pega o item escolhido pelo usário e popula o campo com o valor escolhido. Search -> Ele procura pelos dados no banco pra colocar na lista pro usuário escolher.
Create.cshtml:

Ocorrencia

    @Html.ValidationSummary(true)

        @Html.LabelFor(model => model.Tipo, new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Tipo)
            @Html.ValidationMessageFor(model => model.Tipo)

        @Html.LabelFor(model => model.Causa, new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Causa)
            @Html.ValidationMessageFor(model => model.Causa)

        @Html.LabelFor(model => model.Descricao, new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Descricao)
            @Html.ValidationMessageFor(model => model.Descricao)

        @Html.LabelFor(model => model.AlunoId, "AlunoId", new { @class = "control-label col-md-2" })

           @* @Html.DropDownList("AlunoId", String.Empty)*@
            //Aqui o helper que abre um popup com a lista de todos os dados do banco pro usuário escolher !
            @Html.Awe().Lookup("Aluno")
            @Html.ValidationMessageFor(model => model.AlunoId)

            <input type="submit" value="Create" class="btn btn-default" />

Esse é o Html que é gerado:

<input name="Aluno" id="Aluno" type="hidden" class="awe-lookup">

<button type="button" class="awe-btn awe-openbtn">

</button>

Lembrando que pra num ficar extensa a pergunta eu ocultei algumas partes do Create.cshtml

A: O erro significa que AlunoId não está definido. Como já dito em outras respostas, sua View precisa ter uma das duas coisas:
@Html.HiddenFor(model => model.AlunoId)

Ou então
@Html.DropDownListFor(model => model.AlunoId, ((IEnumerable)ViewBag.Alunos).Select(option => new SelectListItem {
    Text = option.Nome,
    Value = option.AlunoId.ToString(),
    Selected = (Model != null) && (option.AlunoId == Model.AlunoId)
}, "Selecione...")

Pra atualizar o hidden use o seguinte na sua View:
@section scripts {

}

A: Galera eu resolvi. O que acontece é que eu tenho um relacionamento onde pega a FK AlunoId que é a referência a tabela alunos... Para que o Asp.Net Awesome funcione precisa que onde ta no helper @Html.LookupFor("Aluno") seja igual ao controller que faz a manipulação, ou seja, dessa forma: AlunoLookupController. Para resolver o meu problema tive que colocar Ao invés de Aluno, no helper e no controller, AlunoId, que seria a referência exata que estava antes e que é a referência a tabela. Então os códigos ficariam assim:
Controller
//Onde está AlunoIdLookup, estava Aluno...., então mudei e ficou como esta abaixo
public class AlunoIdLookupController : Controller
{
   //Aqui vai as actions
}

View
 .....
 @Html.Awe().Lookup("AlunoId")
 ......

Pronto, resolvido o problema.
Para quem quiser saber mais sobre a biblioteca Asp.Net Awesome o site é esse aqui. Eu acho ela muito funcional, mas tem lá suas peculiaridades. Enfim, a resposta é essa !


text:
Q: How allow user to select phone/facetime/email/iMessage in iPhone and iPad In iPhone and iPad when the user taps on a phone number or email address,how allow user to select phone/facetime/email/iMessage where appropriate.Plz help...

A: As i understood, You want to know about URL Schemes.
Please find reference on Apple Docs...
More Links: WIKI
Sample Project.
Hope it works for you.


text:
Q: Get percentage rate between two metrics in a define interval [Prometheus] I have a question about Prometheus. In my service I have 2 Counters, metric_1 is the total number of requests and metric_2 is the number of failed requests. I need to derive a further metric from these to determine the error rate of requests in terms of percentage in a defined interval (e.g. 2 hours). How can I achieve this through, for example, PromQL?

A: Try something like the following:
increase(metric_2[2h]) / increase(metric_1[2h])

See increase() function documention.
It is assumed that metric_1 and metric_2 are counters. If these metrics are gauges, then increase() must be substituted by sum_over_time().


text:
Q: About character comparision in JavaScript According to the route i type in in the address blank localhost:3000/ff00ff
here 'ff00ff', it should be like a hex code,
if it is, reply Hello world,'ff00ff'!
if it isn't, reply 404 not found.
but the problem is, it doesn't work. Hint:"Error: Uncaught error: reply interface called twice"
Here's the code i wrote
server.route({
    method: 'GET',
    path: '/{name}',
    handler: function (request, reply) {
        var judge = new String(request.params.name);
        console.log(judge);
        for(var i=0; i<6; i++){
        if (judge[i]==='0'||'1'||'2'||'3'||'4'||'5'||'6'||'7'||'8'||'9'||'a'||'b'||'c'||'d'||'e'||'f'||'A'||'B'||'C'||'D'||'E'||'F'){
             reply('Hello, ' + judge + '!')
           }
        else{
              reply('404 Page Not Found')
            }
       }
    }
});

A: Your comparison is attempting to OR all the characters together, which JavaScript will simply evaluate to '0', thus yielding false on judge[i]==='0' for all non-zero characters.
For comparisons, you'll have to do each comparison separately. i.e.:
if (judge[i] === '0' || judge[i] === '1' || ...) { // ...

However, there is a far easier way to achieve what you're trying to do.
Enter RegExp and the String.match function.
if (judge.match(/^[A-F0-9]{6}$/i)) { // ...

This checks that judge is a 6-character long string containing only A-F (or a-f) and 0-9.


text:
Q: How to convert a string to Blob in web_sys? I am trying to convert a string to blob using web_sys

let json_string = json::stringify(data);
let json_jsvalue = JsValue::from_str(&json_string);

let json_blob_result = Blob::new_with_str_sequence(&json_jsvalue);
let json_blob = json_blob_result.unwrap();

It gives error:
panicked at 'called Result::unwrap() on an Err value: JsValue(TypeError: Blob constructor: Argument 1 can't be converted to a sequence.

A: As explained in MDN, to create a Blob from string you need to wrap it in array:
let json_string = json::stringify(data);
let json_jsvalue = JsValue::from_str(&json_string);
let json_jsvalue_array = js_sys::Array::from_iter(std::iter::once(json_jsvalue));

let json_blob_result = Blob::new_with_str_sequence(&json_jsvalue_array);
let json_blob = json_blob_result.unwrap();


text:
Q: AfxSetResourceHandle does not load all language resources in VS2013 I have a C++ project in VS2013/SP3 and a German language resource DLL which is changed with AfxSetResourceHandle at runtime.
It worked perfectly with VS2012, now when I compile it in VS2013 and run the application all resources are changed to the language resource (Strings, Dialogs) except PropertySheetDialogs, have any ideea what's changed in VS2013 because it does not work anymore ? I use codejock CXTPropertySheet class, but I don't think this has something to do with the resource file.
The projects is exactly the same as before when it worked in VS2012, no changes were made.
When I open the compiled DLL in visual studio it contains all the property sheet dialogs translated correctly, but it seems that AfxSetResourceHandle loads them in English from main EXE, the other resources are loaded correctly from the German DLL.


text:
Q: How to apply Anti CSRF tokens in each request in Java Web Apps? I am making a Java Web App. Very new to this technology. I need to implement Anti CSRF token in each server request so that the requests can be made CSRF attack safe. I came across the following link:
https://dzone.com/articles/preventing-csrf-java-web-apps
So while following this, I created my code as follows:
LoadSalt.java
public void doFilter(final ServletRequest req,final ServletResponse res,
    final FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.addHeader("Access-Control-Allow-Origin","*");
    response.addHeader("Allow-Access-Control-Credentials", "true");
    response.addHeader("Access-Control-Allow-Methods","POST");
    response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
    response.addHeader("Access-Control-Max-Age", "1728000");
    response.addHeader("X-Content-Type-Options", "nosniff");
    response.addHeader("X-XSS-Protection", "1; mode=block"); // on
    response.addHeader("X-Frame-Options", "deny");
    response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate, private"); // HTTP 1.1.
    response.addHeader("Pragma", "no-cache"); // HTTP 1.0.
    response.addDateHeader("Expires", 0); // Proxies.

    System.out.println(request.getRequestURL());

    // Check the user session for the salt cache, if none is present we create one
    @SuppressWarnings("unchecked")
    Cache<String, Boolean> csrfPreventionSaltCache = (Cache<String, Boolean>) request.getSession().getAttribute("csrfPreventionSaltCache");

    if (csrfPreventionSaltCache == null)
    {
        csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(5000).expireAfterWrite(20, TimeUnit.MINUTES).build();
        request.getSession().setAttribute("csrfPreventionSaltCache", csrfPreventionSaltCache);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());
    csrfPreventionSaltCache.put(salt, Boolean.TRUE);
    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    request.setAttribute("csrfPreventionSalt", salt);
    filterChain.doFilter(request, response);
    }

ValidateSalt.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    // Get the salt sent with the request
    String salt = (String) httpReq.getAttribute("csrfPreventionSalt");

    // Validate that the salt is in the cache
    @SuppressWarnings("unchecked")
    Cache<String, Boolean> csrfPreventionSaltCache = (Cache<String, Boolean>) httpReq.getSession().getAttribute("csrfPreventionSaltCache");
    if (csrfPreventionSaltCache != null && salt != null && csrfPreventionSaltCache.getIfPresent(salt) != null)
    {
        // If the salt is in the cache, we move on
        chain.doFilter(request, response);
    } else {
        // Otherwise we throw an exception aborting the request flow
        throw new ServletException("Potential CSRF detected!! Inform a scary sysadmin ASAP.");
    }
}

Added the filters in web.xml
<filter>
     <filter-name>LoadSalt</filter-name>
     <filter-class>com.sample.filter.LoadSalt</filter-class>
 </filter>
  <filter-mapping>
     <filter-name>LoadSalt</filter-name>
     <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter>
     <display-name>ValidateSalt</display-name>
     <filter-name>ValidateSalt</filter-name>
     <filter-class>com.sample.filter.ValidateSalt</filter-class>
  </filter>
  <filter-mapping>
     <filter-name>ValidateSalt</filter-name>
     <servlet-name>ControllerServlet</servlet-name>
  </filter-mapping>

The problem is that when a request is executed, it does not fail. It always creates a new 'salt' value. Ideally it should fail because I have not written the following code in HTML form within any JSP page (as given in the link shared above):
<form action="/transferMoneyServlet" method="get">
<input type="hidden" name="csrfPreventionSalt" value="<c:out
value='${csrfPreventionSalt}'/>"/>
 ...
 </form>

Someone, please help me in this. Thanks in Advance.


text:
Q: Permutations of $\{1,\ldots,2pq\}$ modulo $2pq$ I am proposing here a variant of this problem.
Let $p$ and $q$ be distinct odd primes. Is it true that there exists a permutation $\sigma$ of $\{1,\ldots,2pq\}\times \{1,2\}$ such that
$$
\{\sigma(1,x),\ldots,(2pq)\sigma(2pq,x)\}=\{1,\ldots,2pq\}
$$
modulo $2pq$ for each $x \in \{1,2\}$?
[I think the answer is affirmative, as in the other case]

The question is related to this one. In particular, it follows that the answer is affirmative if $p=3$ and $q=5$.


text:
Q: Getting warning in console ag-grid: invalid colDef property 'sortable' I am getting a warning message on console while trying to use the colDef property 'sortable'
I am working in
Angular 6

A: not enough information to give an answer, what's the warning?
the property colDef.sortable came out in version 20, maybe you are using an older version of ag-Grid?

A: I am getting this warning as well.
My version:
"ag-grid-angular": "20.2.0",
"ag-grid-community": "20.2.0",

Most likely bug in ag-grid


text:
Q: Dsum/Running Total using textbox and comboBox - Ms Access I am trying to calculate sales of agents seperately in the database. For total sales the DSUM is working fine. But if i try to bound it to some criteria (specific aget name) it gives ?NAME? error. Here is my code i applied for value selected from combobox.
=DSum("[totalsales]","MainTable","[Agent_Name]='" & me.cbo1 & "'")

and code for textbox is .
=DSum("[totalsales]","MainTable","[Agent_Name]='" & me.filteragent & "'")

here is the detail of the items on my form...
1: There is no Subform on the form
2: Form is based on MainTable
3: filteragent is unbounded textbox
4: cbo1 is a comboBox peresent on that form taking values from Agent_Name field on MainTable
5: Filter agent is Unbounded textbox on the form
6: agentwisesum is the name of unbounded textbox on which i am appling the dsum function
database image
kindly tell where i am doing wrong in the code. thanks


text:
Q: Android app_process segmentation fault trying to run own app I am trying to run a java app/script from adb shell on an unrooted device without installing it as a package first. I tried to use app_process the same way as e.g. am is run - however I get a segmentation fault. I am wondering if this is possible at all considering security.
This is the code:
public class example {
    public static void main(String[] args) {
        System.out.println("Hello world");
        }
}

This works fine in Windows:
$ javac example.java
$ java example
Hello world
$ java -jar example.jar
Hello world

I created an example.jar file with a manifest and the class inside (I tried with and without the class as am does not use an executable jar) and uploaded both to /sdcard/. Now in the shell (via adb) I do the following, which just produces Segmentation Fault on the console:
base=/system && export CLASSPATH=/sdcard/example.jar && app_process $base/bin example

Here is what logcat says:
D/AndroidRuntime(14289): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(14289): CheckJNI is OFF
D/AndroidRuntime(14289): setted country_code = UK
D/AndroidRuntime(14289): setted countryiso_code = GB
D/AndroidRuntime(14289): setted sales_code = TMU
D/AndroidRuntime(14289): readGMSProperty: start
D/AndroidRuntime(14289): readGMSProperty: already setted!!
D/AndroidRuntime(14289): readGMSProperty: end
D/AndroidRuntime(14289): addProductProperty: start
D/dalvikvm(14289): Trying to load lib libjavacore.so 0x0
D/dalvikvm(14289): Added shared lib libjavacore.so 0x0
D/dalvikvm(14289): Trying to load lib libnativehelper.so 0x0
D/dalvikvm(14289): Added shared lib libnativehelper.so 0x0
I/dalvikvm(14289): Zip is good, but no classes.dex inside, and no valid .odex file in the same directory
E/appproc (14289): ERROR: could not find class 'example'
E/JNIHelp (14289): Native registration unable to find class 'android/debug/JNITest', aborting
F/libc    (14289): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 14289 (app_process)
I/DEBUG   ( 1835): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG   ( 1835): Build fingerprint: 'samsung/GT-I9100/GT-I9100:4.1.2/JZO54K/I9100XWLSY:user/release-keys'
I/DEBUG   ( 1835): pid: 14289, tid: 14289, name: app_process  >>> app_process <<<
I/DEBUG   ( 1835): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad
I/DEBUG   ( 1835):     r0 00000027  r1 deadbaad  r2 40141b0c  r3 00000000
I/DEBUG   ( 1835):     r4 00000000  r5 bec3690c  r6 402a8ea8  r7 00000002
I/DEBUG   ( 1835):     r8 402b1828  r9 400ddfc1  sl 400ddf94  fp 400ddfca
I/DEBUG   ( 1835):     ip 40181fe0  sp bec36908  lr 40113c65  pc 401102fe  cpsr 60000030
I/DEBUG   ( 1835):     d0  0000000000000004  d1  0000000000000000
I/DEBUG   ( 1835):     d2  0000000000000000  d3  0000000000000000
I/DEBUG   ( 1835):     d4  0000000000000000  d5  0000000000000000
I/DEBUG   ( 1835):     d6  0000000000000000  d7  83cc7a9b00000000
I/DEBUG   ( 1835):     d8  0000000000000000  d9  0000000000000000
I/DEBUG   ( 1835):     d10 0000000000000000  d11 0000000000000000
I/DEBUG   ( 1835):     d12 0000000000000000  d13 0000000000000000
I/DEBUG   ( 1835):     d14 0000000000000000  d15 0000000000000000
I/DEBUG   ( 1835):     d16 0000000000000017  d17 0000000000000000
I/DEBUG   ( 1835):     d18 4172e2b5a0000000  d19 0000000000000000
I/DEBUG   ( 1835):     d20 0000000000000000  d21 0000000000000000
I/DEBUG   ( 1835):     d22 0000000000000000  d23 0000000000000000
I/DEBUG   ( 1835):     d24 0000000000000000  d25 0000000000000000
I/DEBUG   ( 1835):     d26 0000000000000000  d27 0000000000000000
I/DEBUG   ( 1835):     d28 0000000000000000  d29 0000000000000000
I/DEBUG   ( 1835):     d30 0000000000000000  d31 0000000000000000
I/DEBUG   ( 1835):     scr 60000010
I/DEBUG   ( 1835):
I/DEBUG   ( 1835): backtrace:
I/DEBUG   ( 1835):     #00  pc 000182fe  /system/lib/libc.so
I/DEBUG   ( 1835):     #01  pc 0000dc04  /system/lib/libc.so (abort+4)
I/DEBUG   ( 1835):     #02  pc 00000955  /system/lib/libnativehelper.so (jniRegisterNativeMethods+72)
I/DEBUG   ( 1835):     #03  pc 0004d4a7  /system/lib/libandroid_runtime.so (android::AndroidRuntime::startReg(_JNIEnv*)+34)
I/DEBUG   ( 1835):     #04  pc 0004d5a5  /system/lib/libandroid_runtime.so (android::AndroidRuntime::start(char const*, char const*)+200)
I/DEBUG   ( 1835):     #05  pc 00000dcf  /system/bin/app_process
I/DEBUG   ( 1835):

Is there any way to get this work? If yes what am I missing - I can see the ERROR in the log so the class is probably in the wrong place, by can I get it working from the .jar file, or from a location where I can put the class on an unrooted device?
My goal is to run a Java app/script (similar to how you can run am, pm, dumpsys) in the background using adb, doing some things, while the device runs other things as usual from the GUI, so I don't want to install it as a package / run an intent.


text:
Q: Docker container doesn't start up SCNEARIO:
A custom image with the following Dockerfile
FROM node:10
WORKDIR /usr/src/app
ENTRYPOINT ["docker-entrypoint.sh"]
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 7070
CMD [ "npm", "start"]

I can build the image just typing docker build . (from the project's folder). But... always exists a but :-( When I execute:
docker run -d --restart=always <imageid>

The container is created fine but....
CONTAINER ID        IMAGE               COMMAND
CREATED             STATUS                          PORTS
NAMES
4314ffc2afcb        a68faf70e589        "docker-entrypoint.s…"   20
minutes ago      Restarting (0) 44 seconds ago
magical_hopper

Sorry for the bad indentation, to sum up, I don't have idea WHY? the container it's not UP.
I think that the problem is on the Dockerfile.
PD: I know that this issue can be duplicated but I don't understood the solutions (I am newbie using docker, excuse me).
Can anybody help me?
Thanks in advance to everybody.

A: Ok -- issue is with entrypoint and cmd both are defined.
at the end it's equivalent command would be docker-entrypoint.sh  npm  start.
npm and start are passed as an argument to docker-entrypoint.sh script.
It will not start npm and hence it will come out of container immediately.
Try first removing ENTRYPOINT from your Dockerfile
or
use docker-entrypoint.sh to include npm start command at the end.


text:
Q: How to prevent Excel from wanting to start in Safe Mode? We have a background process that calls Excel for generation of report spreadsheets. Occasionally, a crash or inadvertent server reboot will occur while Excel is running. The first launch of Excel after the restart brings up the dialog box (paraphrasing here) "Would you like to start Excel in safe mode?" (Yes/No)
The issue is that our background app can't handle this dialog box, and acts as if Excel will not start properly, and the background jobs fail as a result.
I can find CL switches for starting Excel in safe mode, but I can't find anything that will instruct Excel to always start in normal mode without that prompt dialog.
(I don't have access to the other program's code, so I can't make it pass through a "Yes" value if it runs into that box.)
Is there a registry hack or some other way I can force Excel into normal mode every time it's called?

A: I just had this problem, I fixed it using Excel switches. You can find more info here https://support.microsoft.com/en-us/kb/291288
Try adding "/e" when starting Excel, for example:
EXCEL.exe /e "C:\My Documents\File.xls"
That should do the trick!

A: I doubt if there would be a switch to prevent excel from opening in safe mode, since safe mode is a recovery mechanism its bound to be activated if excel experiences a crash.


text:
Q: How to use django UserCreationForm correctly I am new to Django and am just starting my first website. I am trying to set registration for new users.
I used the built in view for login and logout but there is none for registration, in the doc, it says that I should use built in form : UserCreationForm.
The code of my view is :
def register(request):
if request.method =='POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        user = User.objects.create_user(form.cleaned_data['username'], None, form.cleaned_data['password1'])
        user.save()
        return render_to_response('QCM/index.html') # Redirect after POST
else:
    form = UserCreationForm() # An unbound form

return render_to_response('register.html', {
    'form': form,
},context_instance=RequestContext(request))

It works fine but I am not satisfied as this code is written in the views.py that handles the core of my application (multiple choice question).
My questions are :

*

*Is this the correct way of using the UserCreationForm

*Where could I put this code so it would be separated from the rest of
my app

Thank you for your answers.

A: *

*Django is modular, so you can write a separate accounts or user management app that can handle user creation, management.
In that case, you put the code for register in the views.py of accounts app.

*You can directly save the UserCreationForm which will give you user object.
example:
...
form = UserCreationForm(request.POST)
if form.is_valid():
   user = form.save()
...


text:
Q: Unity animation not completing i'm beginner on unity and game development. i'm trying to make a platformer game with unity, and i want to play a animation when the player is moving right or left, but the problem is that the isMoving variable for some reason is true animation is playing for a few moments (less than a second) and then is going to false again and the idle animation is playing.
My Animator (Exit time is disabled for all transitions):

My Movement script:
public class PlayerMovement : MonoBehaviour
{

    private bool canPlayerJump;
    private float horizontalInput;
    private Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space) && canPlayerJump)
        {
            GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
        }

        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.A))
        {
            animator.SetBool("isMoving", true);
        } else
        {
            animator.SetBool("isMoving", false);
        }

        horizontalInput = Input.GetAxis("Horizontal");

    }

    private void FixedUpdate()
    {
        GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput * 5, GetComponent<Rigidbody>().velocity.y, 0);
    }

    private void OnCollisionEnter(Collision collision)
    {
       canPlayerJump = true;
       Debug.Log(collision.gameObject.name);
    }

    private void OnCollisionExit(Collision collision)
    {
        canPlayerJump = false;
    }

}

A: You using Update loop function that means this code will be executed each frame by unity. Similar to FixedUpdate, LateUpdate etc...
You can read more here: HERE
Once you pressing down you IF statement will be executed because you listening for BTN DOWN event. This means that TRUE will be returned only in one frame when you press actually button next frame it will return false. and your animations stops.

*

*Try to change bool to Trigger

*Or handle in another way bool var state.

A: Input.GetKeyDown
is only true in the one frame the button went down.

Returns true during the frame the user starts pressing down the key identified by the key KeyCode enum parameter.

You rather want to use Input.GetKey which stay true as long as the key stays pressed.

Returns true while the user holds down the key identified by the key KeyCode enum parameter

alternatively in order to not have redundant accesses you could also simply use
horizontalInput = Input.GetAxis("Horizontal");

animator.SetBool("isMoving", !Mathf.Approximately(horizontalInput, 0));

And as a general note: Cache the component references and don't use GetComponent over and over again!
[SerializeField] private Rigidbody _rigidbody;

private void Awake ()
{
    if(!_rigodbody) _rigidbody = GetComponent<Rigidbody>();
}

then later everywhere use _rigidbdoy instead of GetComponent<Rigidbody>()