text:
Q: Cannot import scipy though already installed I recently installed Python 2.7.11 and am installing some packages. I installed numpy though pip and was trying to install scipy but on running sudo pip install scipy, it gave me the following error.
Collecting scipy
  Downloading scipy-0.17.0.tar.gz (12.4MB)
100% |████████████████████████████████| 12.4MB 143kB/s
Installing collected packages: scipy
  Running setup.py install for scipy ... error
Complete output from command /usr/local/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-dO0a3N/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-LbzadC-record/install-record.txt --single-version-externally-managed --compile:
lapack_opt_info:
openblas_lapack_info:
  libraries openblas not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu']
  NOT AVAILABLE

lapack_mkl_info:
mkl_info:
  libraries mkl,vml,guide not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu']
  NOT AVAILABLE

  NOT AVAILABLE

atlas_3_10_threads_info:
Setting PTATLAS=ATLAS
  libraries tatlas,tatlas not found in /usr/local/lib
  libraries lapack_atlas not found in /usr/local/lib
  libraries tatlas,tatlas not found in /usr/lib
  libraries lapack_atlas not found in /usr/lib
  libraries tatlas,tatlas not found in /usr/lib/x86_64-linux-gnu
  libraries lapack_atlas not found in /usr/lib/x86_64-linux-gnu
<class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
  NOT AVAILABLE

atlas_3_10_info:
  libraries satlas,satlas not found in /usr/local/lib
  libraries lapack_atlas not found in /usr/local/lib
  libraries satlas,satlas not found in /usr/lib
  libraries lapack_atlas not found in /usr/lib
  libraries satlas,satlas not found in /usr/lib/x86_64-linux-gnu
  libraries lapack_atlas not found in /usr/lib/x86_64-linux-gnu
<class 'numpy.distutils.system_info.atlas_3_10_info'>
  NOT AVAILABLE

atlas_threads_info:
Setting PTATLAS=ATLAS
  libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib
  libraries lapack_atlas not found in /usr/local/lib
  libraries ptf77blas,ptcblas,atlas not found in /usr/lib
  libraries lapack_atlas not found in /usr/lib
  libraries ptf77blas,ptcblas,atlas not found in /usr/lib/x86_64-linux-gnu
  libraries lapack_atlas not found in /usr/lib/x86_64-linux-gnu
<class 'numpy.distutils.system_info.atlas_threads_info'>
  NOT AVAILABLE

atlas_info:
  libraries f77blas,cblas,atlas not found in /usr/local/lib
  libraries lapack_atlas not found in /usr/local/lib
  libraries f77blas,cblas,atlas not found in /usr/lib
  libraries lapack_atlas not found in /usr/lib
  libraries f77blas,cblas,atlas not found in /usr/lib/x86_64-linux-gnu
  libraries lapack_atlas not found in /usr/lib/x86_64-linux-gnu
<class 'numpy.distutils.system_info.atlas_info'>
  NOT AVAILABLE

/usr/local/lib/python2.7/site-packages/numpy/distutils/system_info.py:1542: UserWarning:
    Atlas (http://math-atlas.sourceforge.net/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [atlas]) or by setting
    the ATLAS environment variable.
  warnings.warn(AtlasNotFoundError.__doc__)
lapack_info:
  libraries lapack not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu']
  NOT AVAILABLE

/usr/local/lib/python2.7/site-packages/numpy/distutils/system_info.py:1553: UserWarning:
    Lapack (http://www.netlib.org/lapack/) libraries not found.
    Directories to search for the libraries can be specified in the
    numpy/distutils/site.cfg file (section [lapack]) or by setting
    the LAPACK environment variable.
  warnings.warn(LapackNotFoundError.__doc__)
lapack_src_info:
  NOT AVAILABLE

/usr/local/lib/python2.7/site-packages/numpy/distutils/system_info.py:1556: UserWarning:
    Lapack (http://www.netlib.org/lapack/) sources not found.
    Directories to search for the sources can be specified in the
    numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    the LAPACK_SRC environment variable.
  warnings.warn(LapackSrcNotFoundError.__doc__)
  NOT AVAILABLE

Running from scipy source directory.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-dO0a3N/scipy/setup.py", line 265, in <module>
    setup_package()
  File "/tmp/pip-build-dO0a3N/scipy/setup.py", line 262, in setup_package
    setup(**metadata)
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/core.py", line 135, in setup
    config = configuration()
  File "/tmp/pip-build-dO0a3N/scipy/setup.py", line 182, in configuration
    config.add_subpackage('scipy')
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/misc_util.py", line 1003, in add_subpackage
    caller_level = 2)
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/misc_util.py", line 972, in get_subpackage
    caller_level = caller_level + 1)
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/misc_util.py", line 909, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy/setup.py", line 15, in configuration
    config.add_subpackage('linalg')
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/misc_util.py", line 1003, in add_subpackage
    caller_level = 2)
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/misc_util.py", line 972, in get_subpackage
    caller_level = caller_level + 1)
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/misc_util.py", line 909, in _get_configuration_from_setup_py
    config = setup_module.configuration(*args)
  File "scipy/linalg/setup.py", line 20, in configuration
    raise NotFoundError('no lapack/blas resources found')
numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

----------------------------------------
Command "/usr/local/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-dO0a3N/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-LbzadC-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-dO0a3N/scipy/

So, I proceeded to install it via sudo apt-get install python-scipy, which ran with no problems. But, when I go into the python interpreter and try to import scipy, it says the module does not exist. Where did I go wrong? I also tried the following code.
for p in sys.path:
    if os.path.exists(os.path.join(p, 'numpy')):
        print p
        break
else:
    print "Numpy does not exist"

which resulted in "/usr/local/lib/python2.7/site-packages". Running the same code for scipy says "Scipy does not exist". I think it is a path problem maybe. Any help would be appreciated.

A: In Ubuntu, Python 2.7 packages installed with apt-get install are put in the folder /usr/lib/python2.7/dist-packages. So, you'll need to update you Python path.
export PYTHONPATH="/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/site-packages"

Also, your pip install scipy failed because you didn't install the libraries/packages scipy is dependent on.

A: What I was missing were a dependency of scipy. The library that was missing was libatlas-base-dev. Once I installed that, scipy installed with no problems.
Thanks everyone for sparing time for this. And special mention to @knh170 for the helpful comment. I found the answer there.


text:
Q: Paper Icon Buttons not rendering in Firefox I have a problem with paper icon buttons not rendering in firefox (latest update). In chrome the icons render perfectly. I've narrowed the problem down to any icons which have an external source.
<paper-icon-button icon="favorite" title="heart"></paper-icon-button>
<paper-icon-button src="https://assets-cdn.github.com/images/modules/logos_page/Octocat.png" alt="octocat" title="octocat"></paper-icon-button>

adding both lines to my project, the first one renders correctly but the second one does not. (Both render in chrome)

A: You cannot mix HTTPS and HTTP assets without issue.  Either access your page over HTTPS, or change the second button src protocol to HTTP.
Unfortunately, it looks like github is going to kick you over to HTTPS regardless.
Realted: https://developers.google.com/web/fundamentals/security/prevent-mixed-content/fixing-mixed-content

redpajama_set_name: RedPajamaStackExchange


text:
Q: View not sending the data array to the AngularJs controller view

    <input id="boxInsumo{{supplie.id_supplies}}" type="checkbox" name="name" ng-model="dataSupplies.name" class="form-control-custom col-lg-2" ng-true-value="{{supplie.name}}">
    {{supplie.name}}

            Cantidad
            <input type="number" placeholder="cuantity" name="cuantity" ng-model="dataSupplies.cuantity" class="form-control form-control-sm col-lg-5">

<button ng-click="formSupplies(dataSupplies)">SEND</button>

/***********************************************
controller angulajs
$scope.formSupplies = function (dataSupplies) {
        console.log(dataSupplies);
    }

Result
Undefined

A: If supplies is not part of $scope will not work for the ng-repeat, and it will not work as a method parameter.
Also your ng-repeat is not binded to some variables. Instead of:
<input type="number" placeholder="cuantity" name="cuantity" ng-model="supplie.cuantity" class="form-control form-control-sm col-lg-5">

You may be using:
<input type="number" placeholder="cuantity" name="cuantity" ng-model="dataSupplie.cuantity" class="form-control form-control-sm col-lg-5">

It appears you're using supplie where you should be using dataSupplie (or viceversa). When you solve that issue, you can use a $filter for the selected items:
  $scope.isSelected = function(product) {
    return product.selected;
  };

  $scope.formSupplies = function() {
    var filteredSupplies =
        $filter('filter')($scope.dataSupplies, $scope.isSelected);
  };

Example: https://codepen.io/zameb/pen/KvjqON


text:
Q: Apply method in R missing argument (missing argument error) I am trying to use the apply method in R. But I keep getting the error: Error in FUN(newX[, i], ...) : missing argument in "b".
The code which produces the error:
my_data <- data.frame(x1 = 1:5, x2 = 2:6, x3 = 3)

myFunction <- function(a, b, c){
  return(a + b + c)
}

results = apply(my_data, 1, myFunction) #this line is producing the error massage

If I change "myFunction" to "sum" for example. Then there is no error. How can I get rid of this error?

A: Either the function should be changed to
myFunction <- function(x) sum(x)
apply(my_data, 1, myFunction)
#[1]  6  8 10 12 14

Also, the sum operation by row is more efficient with rowSums
rowSums(my_data)

or specify the arguments separately by using a lambda/anonymous function in the OP's original function
apply(my_data, 1, function(x) myFunction(x[1], x[2], x[3]))

A: You can use mapply:
with(my_data, mapply(myFunction, x1, x2, x3))

A: Also note your data.frame is a list of 3 vectors. You can add vectors just like a scalar.
with(my_data, x1 + x2 + x3)


text:
Q: Convert PHP readfile to WP_Filesystem In the script below, I need to convert the readfile to the WP_filesytem equivalent. However, I can't find same in Codex. Any help much appreciated.
This script saves the settings.ini file to the user's desktop/pc.
WP_Filesystem();
global $wp_filesystem;

$mySettingsFileLocation = WP_PLUGIN_DIR.'/my-settings/settings.ini';

if ( ! $wp_filesystem->put_contents( $mySettingsFileLocation, $mySettings, 0644) ) {
    return true;
}

// Define the path to file
 $file = WP_PLUGIN_DIR.'/my-settings/settings.ini';

 if(!$file)
 {
         // File doesn't exist, output error
         die('file not found');
 }
 else
 {
 // Set headers
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-Disposition: attachment; filename=settings.ini");
 header("Content-Type: application/ini");
 header("Content-Transfer-Encoding: binary");

 // Read the file from disk
 readfile($file);
 }

A: Reading a file to send to the user is perfectly safe and does not necessarily need to be converted to the WP_Filesystem methods. Only writing is potentially an issue.
However, if you wanted to do so, this would be the equivalent:
echo $wp_filesystem->get_contents( filename variable here );
Also, note that your filename for "put_contents" is incorrect. Instead of using WP_PLUGIN_DIR, you need to use $wp_filesystem->wp_plugins_dir() because the "remote" directory might not be the same as the "local" directory.
$mySettingsFileLocation = $wp_filesystem->wp_plugins_dir() . '/my-settings/settings.ini';


text:
Q: Excel adds equal sign to SOME lines I have a .csv file that I generated with a program. And when I open it with Excel. Some lines get an equal sign '=' added in front of them, which causes the excel file to write #NAME? in the cell. But some don't...
Some of the lines:
these lines
+P moc maksymalna skumulowana; + P moc maksymalna skumulowana  M717

becomes into
=+P moc maksymalna skumulowana; =+ P moc maksymalna skumulowana  M717

therefore it's #NAME?
But this line
+ P moc maksymalna w OR, M1

Remains fine.
There are many more. Some with a '-' in the front, some with a '+'. Some have a space after the sign, some don't. Some have a text like "M1" in them, that could be treated like a cell, some don't.
And some of them get a '=' added in front of them, and some of them don't. Randomly. With no connection.
I can't find anything specific that is causing it. Anyone ever faced a problem like this before?
P.S. I'm not polish, just making some localization files translated by someone else.


text:
Q: How to combine Git hook with Sonar in Visual Studio Code? I need a help in the followings.

*

*How to add pre-hook stuff in git?

*How to i make git to run the sonar test before the code commit in vs code?

*How can i only do with current commit ( not already pushed code )

I keep searching a solution across the web. but getting no valid and detailed demo, tutorials. please any one help me to understand all above?
Thanks in advance.


text:
Q: Validação de RNE (Registro Nacional de Estrangeiros) ou CIE (Cédula de Identidade de Estrangeiro) Alguém sabe como posso validar o número da CIE (Cédula de Identidade de Estrangeiro) ou RNE (Registro Nacional de Estrangeiros)? Acredito que existe duas nomenclaturas.
Independente da linguagem.

A: Eu resolvi a validação e formatação do RG / RNE com este código:
function formatarRG(input, teclapres) {
   var numeroRG  = input.value.trim().toUpperCase().replace(/[^\dX]/g, '');
   var numeroRNE = input.value.trim().toUpperCase();

   if (numeroRNE.substring(0, 3) == 'R' || numeroRNE.substring(0, 3) == 'RN' || numeroRNE.substring(0, 3) == 'RNE') {
    input.value = numeroRNE.replace(/^(RNE)(\w)(\d{6})(\w)$/, '$1$2$3$4');
   } else {
    if ((numeroRG.length == 8 || numeroRG.length >= 9) &&
          (numeroRG.substring(0, 8) == '00000000' ||
           numeroRG.substring(0, 8) == '11111111' ||
           numeroRG.substring(0, 8) == '22222222' ||
           numeroRG.substring(0, 8) == '33333333' ||
           numeroRG.substring(0, 8) == '44444444' ||
           numeroRG.substring(0, 8) == '55555555' ||
           numeroRG.substring(0, 8) == '66666666' ||
           numeroRG.substring(0, 8) == '77777777' ||
           numeroRG.substring(0, 8) == '88888888' ||
           numeroRG.substring(0, 8) == '99999999')) {
        alert("ATENÇÃO! Número do RG inválido, digite novamente. ");
        input.value = '';
        input.focus();
        return false;
    } else {
            input.value = (numeroRG.length == 8 ? numeroRG.replace(/^(\d{1,2})(\d{3})(\d{3})$/, '$1.$2.$3') : numeroRG.replace(/^(\d{1,2})(\d{3})(\d{3})([\dX])$/, '$1.$2.$3-$4'));
         if (numeroRG.length >= 9 && !verificaRG(numeroRG)) {
            alert("ATENÇÃO! O dígito verificador do Número do RG está inválido, o correto é "+ RetornarDigitoVerificadorRG(numeroRG));
            input.value = input.value.substring(0, 11) + RetornarDigitoVerificadorRG(numeroRG);
            input.focus();
            return false;
         }
    }
   }
    return input.value;
}

function validarRG(input) {
    var numero  = input.value.trim().toUpperCase();

    if ((numero.substring(0, 3) == 'RNE' && numero.match(/^(RNE)(\w)(\d{6})(\w)$/) == null) ||
          (numero != '' && numero.length < 8) ||
          ((numero != '' && numero.length > 1) &&
           (numero.substring(0, 8) == '00000000' ||
            numero.substring(0, 8) == '11111111' ||
            numero.substring(0, 8) == '22222222' ||
            numero.substring(0, 8) == '33333333' ||
            numero.substring(0, 8) == '44444444' ||
            numero.substring(0, 8) == '55555555' ||
            numero.substring(0, 8) == '66666666' ||
            numero.substring(0, 8) == '77777777' ||
            numero.substring(0, 8) == '88888888' ||
            numero.substring(0, 8) == '99999999'))) {
    alert("ATENÇÃO! Número do RG inválido, digite novamente.");
    input.value = '';
    input.focus();
    return false;
    } else return true;
}

function verificaRG(value) {

    // Regra encontrada no site: https://www.ngmatematica.com/2014/02/como-determinar-o-digito-verificador-do.html

    var numeroRG  = value.trim().toUpperCase();
    var numero    = numeroRG.split("");
    var total     = 0;
    var resto     = 0;
    var digito    = 0;
    var resultado = true;

    if (numeroRG != "") {
    total  = (parseInt(numero[0])*2)+(parseInt(numero[1])*3)+(parseInt(numero[2])*4)+(parseInt(numero[3])*5)+(parseInt(numero[4])*6)+(parseInt(numero[5])*7)+(parseInt(numero[6])*8)+(parseInt(numero[7])*9);
    resto  = total % 11;
    digito = 11 - resto;

    if (numero.length >= 9) {
        if (numero[8] == 'X')
            resultado = (digito == 10);
        else if (numero[8] == '0')
            resultado = (digito == 11);
        else
            resultado = parseInt(numero[8]) == digito;
    }
    } else
        resultado = false;
    return resultado;
}

// No seu HTML
<fmt:message key="colaborador.numeroDoRG.rotulo" />:
<input type="text" tabindex="2" name="colaborador.numeroDoRG" id="colaborador.numeroDoRG" maxlength="12" size="20" class="campo uppercase" onKeyUp="return formatarRG(this, event);" onBlur="return validarRG(this);"/>

Espero que te ajude...


text:
Q: How can I persist resource data when my route changes in AngularJS? I'm wiring up an AngularJS based admin app template to an API. This is a snippet of what my navigation menu looks like:

As you can see, I have a main "Listings" page as well as two sub-pages of listings, which are just subsets of the main data set.
In my listingCtrl, I use a Listing resource that I created to fetch JSON data from an API. That data is then populated into my $scope. It's very easy to filter the data from within the controller, but the nav menu is outside of the listingCtrl scope.
This is the snippet of my listings controller that fetches the resource:
angular.module('app.listings', [])
.controller('listingCtrl', [
    '$scope', '$filter', '$location', 'Listing'
    ($scope, $filter, $location, Listing) ->

    # The listing controller checks the last segment of the URL
    # to determine which API call to place
    segments = $location.url().split('/')
    parameter = segments[segments.length-1]

    Listing.get({listingId: parameter}, (listings) ->
        $scope.listings = listings
    )
])

This is the configuration for my route provider for this specific page:
angular.module('app', [
    'ngRoute'
])
.config([
    '$routeProvider'
    ($routeProvider) ->
        $routeProvider
            .when('/listings/:status?'
                templateUrl: 'views/listings/list.html'
            )
])

I was hoping that by specifying all of the /listings routes under one when method, it would prevent the controller from being reloaded when switching among those routes. That is apparently not the case.
I don't want to reload my Listing resource when switching among /listings, /listings/active and /listings/need-photos, although I do want the location hash to change. Currently, when I click on one of my nav links, it changes the hash and apparently the $routeProvider reloads the templateUrl and associated listingCtrl, which tosses my existing listing data and reloads it from the server. I would rather have the data persist and only the filter change when navigating among the three URLs.
How can I get my controller and router working together so that my REST resources aren't being reloaded when switching among the above routes?

A: @Nikos is correct. You can make a service to hold a cache for your listings:
    app.factory('cacheExample', ['$cacheFactory', function($cacheFactory){
        return $cacheFactory('listingsData');
    }]);

Inject the service into your controller and use it to assign listings to the cache and refrain from making the API call if the listings have previously been cached. Should look something like:
    app.controller('listingCtrl', ['$scope', 'Listing', 'cacheExample', ($scope,
    Listing, cacheExample){
        var listingsCache = cacheExample.get('listingsData');
        if(listingsCache){
            $scope.listings = listingsCache;
        }
        else{
            //the cache is empty, so make your API call with the Listing service
            //and assign the result to the cache
            // ... other methods....
            Listing.get({listingId: parameter}, function(listings){
                $scope.listings = listings;
                cacheExample.put('listingsData', listings);
            });
        }
    }]);

Alternatively, you can use the service as above, inject it into your controller, and use it with the cache option for $http:
    app.controller('ListingCtrl', ['$scope', '$http', 'cacheExample', function($scope,
    $http, cacheExample){
        $http.get('/listingsUrl', {cache:
        cacheExample}).success(function(response){
            $scope.listings = response;
        });
    }]);

Here is a fiddle demonstrating the second case. Note that if you use $http with the cache option, delivery of the data is asynchronous in the same way that real requests are, even if the response if served from your cache.


text:
Q: Multiclass SVM + Ineffective X Validation, Time Series Prediction  I've recently run into an interesting and rather odd problem with cross validating a multiclass SVM that I can't figure out. Basically, I have a timeseries to predict and have created a dataset of what I believe are relevant predictors (also timeseries). I've done some preprocessing (reduced the example size of the dataset using a priori knowledge). I'm left with about 3000 training examples and a test set of 700 with about 650 features.  When I do stratified 5-fold X validation on my training set, my average training error is fairly low. However, when I test the final model on my test set, my error is very high. In addition, I've noticed that my training error increases dramatically when I run regular 5-fold (non-stratified) X validation, which preserve the order of the timeseries (e.g. trains on older examples to predict newer ones and vice versa, whereas stratified will have various examples from different times mixed together).
I started with stratified because my target data is unbalanced. Additionally, I'm using class weights due to difference in misclassification costs. Unfortunately, I have basically just selected some weights using a priori knowledge and not via X validation due to computational feasibility. Eventually I will try to use X validation.
Any thoughts on what could cause such a difference between the stratified and non-stratified 5 fold X validation? To me, I thought maybe certain training examples seem to predict certain test examples better depending on close in time they were. I was considering using sample weights or perhaps taking out my initial data preprocessing, though that will increase my computation time (30000 vs 3000 examples). Any suggestions and recommendations are most welcome. Let me know if any additional information on my problem will help.

A: You can't use standard cross-validation techniques on time series because the observations aren't independent. This may be the source of your problems. If you are randomly sampling to get your five folds for cross-validation, your CV statistics will be mistakenly low due to correlations across the folds. If your test set on which you calculate the final model is somehow more independent from those five folds (for example, maybe you split training/cv vs. test by time?) you will see poor performance on the test set.
For instructions on properly handling time series cross-validation, see Rob Hyndman's overview of cross-validation (scroll down for time series coverage) and his example of time series cross-validation using R. Rob describes using a rolling origin for time series cross-validation that seems like it might work for you.
Why are you seeing different results for your stratified vs. non-stratified cross-validations? In the unstratified case, it sounds like you are creating training and validation sets that are less correlated than in the stratified case, since you are splitting by time when doing unstratified cross-validation. This might lead to higher cross-validation error because of less correlation across the sets. In the stratified case, you say you have "various examples from different times mixed together." In this case, the training vs validation sets have more correlation, leading to lower training error, representative of overfitting rather than useful predictive power.


text:
Q: Jasper Report Parameter Display I've tried couple of options for parameter display:
alert_type.name --> varchar
alert_type.id --> integer
Alert_Type --> java.util.collection

1.a Parameter in Report Query:
    $X{IN, alert_type.name, Alert_Type}
1.b Parameter display in Report:
[Alert1, Alert2, ..., Alertn)
In this case selected parameters where shown correctly but I needed to change alert_type.name (varchar) to alert_type.id (integer)
2.a Parameter in Report Query:
    $X{IN, alert_type.id, Alert_Type}
2.b Parameter display in Report:
Report was not generated so I tried what is in number 3.
3.a Report query:
    $X{IN, COALESCE (CAST (alert_type.id AS varchar (100))), Alert_Type}
3.b Parameter display in Report:
[1,2,3,4....n]
Now the question is how can I in Parameter display Alert1, Alert2... instead of 1,2...? So do not want to see ID's but the Names.
Here is the relevant code that was requested:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Alert Report" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" whenNoDataType="AllSectionsNoDetail" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="94b79d03-4940-4b89-bbf7-552871a5f749">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <property name="ireport.jasperserver.reportUnit" value="/reports/LTA/Alert_Report_2"/>
    <property name="ireport.jasperserver.url" value="http://10.5.5.59:8080/jasperserver/services/repository"/>

    <subDataset name="New Dataset 1" uuid="acd41491-54fa-4316-8fe7-de309d164657">
        <parameter name="Alert_Type" class="java.util.Collection"/>
        <queryString>
            <![CDATA[SELECT
    alert.event_timestamp,
    alert_type.id,
    alert_type.name
FROM
    alert
JOIN
    alert_type ON alert.type = alert_type.id
WHERE
     $X{IN, COALESCE (CAST (alert_type.id AS varchar (100))), Alert_Type}]]>
        </queryString>
        <field name="event_timestamp" class="java.sql.Timestamp"/>
        <field name="id" class="java.lang.Integer"/>
        <field name="name" class="java.lang.String"/>
    </subDataset>
    <parameter name="Alert_Type" class="java.util.Collection"/>
    <queryString>
        <![CDATA[SELECT
    alert.event_timestamp,
    alert_type.id,
    alert_type.name
FROM
    alert
JOIN
    alert_type ON alert.type = alert_type.id
WHERE
    $X{IN, COALESCE (CAST (alert_type.id AS varchar (100))), Alert_Type}]]>
    </queryString>
    <field name="event_timestamp" class="java.sql.Timestamp"/>
    <field name="id" class="java.lang.Integer"/>
    <field name="name" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="84" splitType="Stretch">
            <staticText>
                <reportElement uuid="673a92ae-a498-47f7-8bb2-cf09f3e08b50" x="0" y="0" width="154" height="30"/>
                <textElement>

                </textElement>
                <text><![CDATA[Alert Report]]></text>
            </staticText>
            <staticText>
                <reportElement uuid="b6c26413-0c0d-40d3-81f7-33b8f15799d8" x="599" y="33" width="83" height="20"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Creation Time:  ]]></text>
            </staticText>
            <textField pattern="dd/MM/yyyy HH:mm:ss">
                <reportElement uuid="f5b19632-5fda-44bb-85d3-963aff9e744f" x="682" y="33" width="120" height="20"/>
                <textElement textAlignment="Left" verticalAlignment="Middle">

                </textElement>
                <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <line>
                <reportElement uuid="0d130948-71cd-490d-93cf-6f43c6ae924b" x="0" y="30" width="802" height="1"/>
            </line>
            <textField isStretchWithOverflow="true" pattern="">
                <reportElement uuid="1c06e35e-23a6-4fd4-90a8-c88116876423" positionType="Float" stretchType="RelativeToBandHeight" x="116" y="55" width="673" height="20" isPrintWhenDetailOverflows="true"/>
                <textElement verticalAlignment="Middle">

                </textElement>
                <textFieldExpression><![CDATA[$P{Alert_Type}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement uuid="e6d2f050-af99-4a2b-ba4a-1491365ffb53" x="0" y="55" width="109" height="20"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Selected Alert Types:  ]]></text>
            </staticText>
        </band>
    </title>
    <detail>
        <band height="177" splitType="Stretch">
            <printWhenExpression><![CDATA[$V{REPORT_COUNT}==1]]></printWhenExpression>
            <componentElement>
                <reportElement uuid="277271e9-b212-446c-9be3-84bd266ce97b" key="table 3" style="table 3" x="0" y="14" width="360" height="50"/>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="New Dataset 1" uuid="e7fe0328-3db3-42ab-aa27-8c9ad0843710">
                        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    </datasetRun>
                    <jr:column width="90" uuid="21dcad58-1a5c-4d93-9c59-8346e4923544">
                        <jr:columnHeader style="table 3_CH" height="30">
                            <staticText>
                                <reportElement uuid="4e38f6d5-e810-440d-b66e-d10284cb8cc3" x="0" y="0" width="90" height="30"/>
                                <textElement/>
                                <text><![CDATA[event_timestamp]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table 3_TD" height="20">
                            <textField>
                                <reportElement uuid="ffdaada2-ec5e-413f-9c67-0eba447e4581" x="0" y="0" width="90" height="20"/>
                                <textElement/>
                                <textFieldExpression><![CDATA[$F{event_timestamp}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="90" uuid="dccb3cdd-5cb1-413f-9d00-24fc950a35af">
                        <jr:columnHeader style="table 3_CH" height="30">
                            <staticText>
                                <reportElement uuid="394a428e-351d-4271-bc04-f58018ea0077" x="0" y="0" width="90" height="30"/>
                                <textElement/>
                                <text><![CDATA[id]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table 3_TD" height="20">
                            <textField>
                                <reportElement uuid="311b77d8-3d60-4149-8dd9-52ee5b3062c8" x="0" y="0" width="90" height="20"/>
                                <textElement/>
                                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="90" uuid="bb72b714-6cac-45a1-a5db-c5d8ebc17b02">
                        <jr:columnHeader style="table 3_CH" height="30">
                            <staticText>
                                <reportElement uuid="d0d4e3d7-fedf-4fc7-837e-97572d0c1a56" x="0" y="0" width="90" height="30"/>
                                <textElement/>
                                <text><![CDATA[name]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table 3_TD" height="20">
                            <textField>
                                <reportElement uuid="18bc66b3-228f-4d32-a764-95a72950e430" x="0" y="0" width="90" height="20"/>
                                <textElement/>
                                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </detail>
    <pageFooter>
        <band height="28" splitType="Stretch">
            <textField>
                <reportElement uuid="7dc7143d-623f-46ef-baf0-0297979eea1c" x="682" y="5" width="80" height="20"/>
                <textElement textAlignment="Right">

                </textElement>
                <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Report">
                <reportElement uuid="6c6ad707-c542-42d7-88b7-ef4a4ba4d473" x="762" y="5" width="40" height="20"/>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
</jasperReport>


text:
Q: Filter objects in array of objects So I have an array with 3 objects
categories:[
{
 id: '1',
 name: 'firstItem',
 description: 'firstDesc'
}
{
 id: '2',
 name: 'secondItem',
 description: 'secondDesc'
}
{
 id: '3',
 name: 'thirdItem',
 description: 'thirdDesc'
}
]

My question is, how can I filter this array to get the same array of 3 objects but without 'description' property?

A: Use array.map to achieve this:

const array = [{
    id: '1',
    name: 'firstItem',
    description: 'firstDesc'
  },
  {
    id: '2',
    name: 'secondItem',
    description: 'secondDesc'
  },
  {
    id: '3',
    name: 'thirdItem',
    description: 'thirdDesc'
  }
];

const array1 = array.map(item => {
  const {
    description,
    ...rest
  } = item;
  return rest;
});

console.log(array1);

A: Simple one-liner to mutate the original array:

let arr = [{id: '1',name: 'firstItem',description: 'firstDesc'},{id: '2',name: 'secondItem',description: 'secondDesc'},{id: '3',name: 'thirdItem',description: 'thirdDesc'}];

arr.forEach(e => delete e.description);

console.log(arr);

A: let categories = [
{
 id: '1',
 name: 'firstItem',
 description: 'firstDesc'
}
{
 id: '2',
 name: 'secondItem',
 description: 'secondDesc'
}
{
 id: '3',
 name: 'thirdItem',
 description: 'thirdDesc'
}
];

let newCategories = categories.map(({ id, name }) => ({ id, name }))

A: You don't actually want to "filter" per say, as in depending on a condition removing elements from an array.
You want to map over your array and then for each object (item) composing this array you want to remove the description property
You can easily achieve this by using the .map method available for Arrays
The .map method works as follows (from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) :

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

// For each object, return a new one without the description property
const result = yourArray.map(obj => {
  const { name, description, id } = obj;
  return { name, id };
})


text:
Q: Not able to catch org.hibernate.StaleObjectStateException Can we not catch the StaleObjectStateException? I have catch block with StaleObjectStateException , so when method is throwing this error it is coming to this catch block but still throwing the same exception again.
I know the reason why this exception is coming but i want to catch the exceptiion and proceed further.
[13/05/15 10:00:07:751 BST] 00000053 TaskUtils$Log E org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler handleError Unexpected error occurred in scheduled task.
                                     org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [com.lgs.mem.model.MemService] with identifier [3038]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.lgs.mem.model.MemService#3038]
                    at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:676)
                    at org.springframework.orm.hibernate3.SpringSessionSynchronization.translateException(SpringSessionSynchronization.java:160)
                    at org.springframework.orm.hibernate3.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:148)
                    at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:95)
                    at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:927)
                    at org.springframework.transaction.jta.WebSphereUowTransactionManager.access$4(WebSphereUowTransactionManager.java:1)
                    at org.springframework.transaction.jta.WebSphereUowTransactionManager$UOWActionAdapter.run(WebSphereUowTransactionManager.java:338)
                    at com.ibm.ws.uow.EmbeddableUOWManagerImpl.runUnderNewUOW(EmbeddableUOWManagerImpl.java:786)
                    at com.ibm.ws.uow.EmbeddableUOWManagerImpl.runUnderUOW(EmbeddableUOWManagerImpl.java:365)
                    at org.springframework.transaction.jta.WebSphereUowTransactionManager.execute(WebSphereUowTransactionManager.java:281)
                    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:127)
                    at at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy156.updateRetryCountAndTSP(Unknown Source)
    at com.lgs.mem.service.impl.MemDAOServiceImpl.updateRetryCountAndTSP(MemDAOServiceImpl.java:181)
    at com.lgs.mem.scheduler.MEMRecoveryScheduler.processFailedNicheRequests(MEMRecoveryScheduler.java:82)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:452)
    at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:328)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:161)
    at org.springframework.scheduling.commonj.TimerManagerTaskScheduler$TimerScheduledFuture.timerExpired(TimerManagerTaskScheduler.java:112)
    at org.springframework.scheduling.commonj.TimerManagerTaskScheduler$ReschedulingTimerListener.timerExpired(TimerManagerTaskScheduler.java:165)
    at com.ibm.ws.asynchbeans.timer.TimerImpl.callListenerMethod(TimerImpl.java:361)
    at com.ibm.ws.asynchbeans.timer.GenericTimer.run(GenericTimer.java:228)
    at com.ibm.ws.asynchbeans.J2EEContext$RunProxy.run(J2EEContext.java:265)
    at java.security.AccessController.doPrivileged(AccessController.java:252)
    at javax.security.auth.Subject.doAs(Subject.java:495)
    at com.ibm.websphere.security.auth.WSSubject.doAs(WSSubject.java:132)
    at com.ibm.websphere.security.auth.WSSubject.doAs(WSSubject.java:90)
    at com.ibm.ws.asynchbeans.J2EEContext$DoAsProxy.run(J2EEContext.java:336)
    at java.security.AccessController.doPrivileged(AccessController.java:280)
    at com.ibm.ws.asynchbeans.J2EEContext.run(J2EEContext.java:1174)
    at com.ibm.ws.asynchbeans.timer.TimerImpl.runListenerAsCJWork(TimerImpl.java:490)
    at com.ibm.ws.asynchbeans.am._Alarm.fireAlarm(_Alarm.java:333)
    at com.ibm.ws.asynchbeans.am._Alarm.run(_Alarm.java:230)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1659)
Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.lgs.mem.model.MemService#6768]
    at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1950)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2595)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2495)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2822)
    at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
    at org.springframework.orm.hibernate3.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:145)
    ... 38 more

A: Yes you can catch the exception.
Problems like this can occur if the exception does not propagate to the place that you are trying to catch it.  For example:

*

*It may be thrown on a different thread.

*It may be further up the stack, and then re-thrown as a different exception.

Judging from the stacktrace, I'd say that it is the second explanation.  The original exception has been caught and a HibernateOptimisticLockingFailureException has been created that wraps it.  It is the latter exception you are seeing.
If you want to specifically handle the original exception, you probably need to catch HibernateOptimisticLockingFailureException (or a superclass), and then call the exception object's getMostSpecificCause() to extract the original exception for diagnosis.

A: Use This:
@Transactional(propagation = Propagation.REQUIRES_NEW,readOnly=true)


text:
Q: How can I plot a numpy array of x, y, z in 3D surface plot? I have reviewed both of these threads, but am still struggling to make a 3D surface plot from a numpy array of x, y, z coordinates.
My array looks like this:
>>> points
array([[ 322697.1875    , 3663966.5       ,  -30000.        ],
       [ 325054.34375   , 3663966.5       ,  -30000.        ],
       [ 325054.34375   , 3665679.5       ,  -30000.        ],
       [ 322697.1875    , 3665679.5       ,  -30000.        ],
       [ 322697.1875    , 3663966.5       ,  -27703.12304688],
       [ 325054.34375   , 3663966.5       ,  -27703.15429688],
       [ 325054.34375   , 3665679.5       ,  -27703.70703125],
       [ 322697.1875    , 3665679.5       ,  -27703.67382812]])

ax.plot_surface accepts x, y, z points so I convert the above array into separate pieces below:
x = points[:, 0]
y = points[:, 1]
z = points[:, 2]

I then put it into a meshgrid for passing into ax.plot_surface():
import numpy as np
X, Y, Z = np.meshgrid(x, y, z)
And then try to plot:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(16,10))
ax = plt.axes(projection = '3d')
ax.plot_surface(X, Y, Z, alpha=0.5)
plt.show()

When I run this I receive an error: rows, cols = Z.shape ValueError: too many values to unpack (expected 2).
I'm not sure where to go with this now, I don't expect the answer but a push in the correct direction would be great.
I would like the output to be similar in appearance to this but with my data:

UPDATE: If I do not include z in the meshgrid, but only x and y, I get this output when I run ax.plot_surface(X, Y, z, alpha=0.5):

This is really close, but I want all the sides to be filled in. Only one is showing as filled in. I've added the point coordinates to show the boundaries. I feel like it has something to do with the meshgrid that I'm creating. Here is the output of X, Y:
>>> X, Y = np.meshgrid(x, y)
(array([[322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ],
       [322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ],
       [322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ],
       [322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ],
       [322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ],
       [322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ],
       [322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ],
       [322697.1875 , 325054.34375, 325054.34375, 322697.1875 ,
        322697.1875 , 325054.34375, 325054.34375, 322697.1875 ]]), array([[3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5,
        3663966.5, 3663966.5],
       [3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5,
        3663966.5, 3663966.5],
       [3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5,
        3665679.5, 3665679.5],
       [3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5,
        3665679.5, 3665679.5],
       [3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5,
        3663966.5, 3663966.5],
       [3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5, 3663966.5,
        3663966.5, 3663966.5],
       [3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5,
        3665679.5, 3665679.5],
       [3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5, 3665679.5,
        3665679.5, 3665679.5]]))

If I just take x, y unique values I get an error thrown:
x = np.unique(x)
y = np.unique(y)

>>> x
array([322697.1875 , 325054.34375])
>>> y
array([3663966.5, 3665679.5])

X, Y = np.meshgrid(x, y)
>>> X, Y
(array([[322697.1875 , 325054.34375],
       [322697.1875 , 325054.34375]]), array([[3663966.5, 3663966.5],
       [3665679.5, 3665679.5]]))

>>> ax.plot_surface(X, Y, z, alpha=0.5)
Traceback (most recent call last):
  File "<pyshell#61>", line 1, in <module>
    ax.plot_surface(X, Y, z, alpha=0.5)
  File "/Users/NaN/anaconda/envs/py36/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1586, in plot_surface
    X, Y, Z = np.broadcast_arrays(X, Y, Z)
  File "/Users/NaN/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 259, in broadcast_arrays
    shape = _broadcast_shape(*args)
  File "/Users/NaN/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 193, in _broadcast_shape
    b = np.broadcast(*args[:32])
ValueError: shape mismatch: objects cannot be broadcast to a single shape

A: The arrays x, y, z need to be parametrized in two dimensions. One way of doing this is to use spherical coordinates as e.g. in Plot surfaces on a cube.
The remaining task is to distill the unique coordinates from the input data. I'm assuming here that there are only 2 distinct values per dimension.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def get_cube():
    phi = np.arange(1,10,2)*np.pi/4
    Phi, Theta = np.meshgrid(phi, phi)

    x = np.cos(Phi)*np.sin(Theta)
    y = np.sin(Phi)*np.sin(Theta)
    z = np.cos(Theta)/np.sqrt(2)
    return x,y,z

points = np.array([[ 322697.1875    , 3663966.5       ,  -30000. ],
                   [ 325054.34375   , 3663966.5       ,  -30000. ],
                   [ 325054.34375   , 3665679.5       ,  -30000. ],
                   [ 322697.1875    , 3665679.5       ,  -30000. ],
                   [ 322697.1875    , 3663966.5       ,  -27703.12],
                   [ 325054.34375   , 3663966.5       ,  -27703.12],
                   [ 325054.34375   , 3665679.5       ,  -27703.12],
                   [ 322697.1875    , 3665679.5       ,  -27703.12]])

ux = np.unique(points[:,0])
uy = np.unique(points[:,1])
uz = np.unique(points[:,2])

x,y,z = get_cube()
offset = lambda X, o: o[0] + (X+.5)*np.diff(o)[0]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(offset(x, ux), offset(y, uy), offset(z, uz))

plt.show()


text:
Q: .htaccess trouble with hiding file extension and forcing trailing slash When I type domain.com/page.php it doesn't automatically change to domain.com/page/. Also, for the pages in subdirectories, if I follow a link to domain.com/sub/1/ everything is fine, but if I type it in the browser it redirects to domain.com/1/
This is what i have in .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/$ $1.php

# Forces a trailing slash to be added
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

Any ideas what I should do to htaccess files in the subdirectories and root directory? I'm new at this.

A: Change the order of rules.
Try this:
RewriteEngine on

# Forces a trailing slash to be added
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?[^/])$ /$1/ [R=301,L]

# .php ext hiding
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]


text:
Q: userContent.css - GMail Compose Same Color as "about:blank" I have some code in my Firefox userContent.css that sets the background color for the about:blank page.  However, the about:blank color also seems to apply to the text area background for creating mesages in Google Mail.
How can I set the Google Mail text background in userContent.css so that it doesn't use the same color as about:blank?
Here's my CSS for the colored about:blank:
@-moz-document url-prefix(about:blank)
{
    *
    {
        background-color:      #330000 !important;
    }
}

And here's my unsuccessful attempt at a fix (using info from here):
@-moz-document domain("mail.google.com")
{
    .editable
    {
        background-color: white !important;
    }
}

Update: Here is a picture of what happens from using the about:blank CSS:


text:
Q: Nginx : Sub-domain config file I have subdomain, Currently its showing an index.html page containing just the name of the domain etc.
That index.html page is loading from the /home/admin/web/****.******.com/public_html.
What i cannot find is the config file which is pointing to that directory.
I checked twice /etc/nginx/conf.d it have nothing which seems to be pointing to that page.
I am using centOs with nginx.

/etc/nginx/nginx.conf :

# Server globals
user                    nginx;
worker_processes        auto;
worker_rlimit_nofile    65535;
error_log               /var/log/nginx/error.log crit;
pid                     /var/run/nginx.pid;

# Worker config
events {
        worker_connections  1024;
        use                 epoll;
        multi_accept        on;
}

http {
    # Main settings
    sendfile                        on;
    tcp_nopush                      on;
    tcp_nodelay                     on;
    client_header_timeout           1m;
    client_body_timeout             1m;
    client_header_buffer_size       2k;
    client_body_buffer_size         256k;
    client_max_body_size            256m;
    large_client_header_buffers     4   8k;
    send_timeout                    30;
    keepalive_timeout               60 60;
    reset_timedout_connection       on;
    server_tokens                   off;
    server_name_in_redirect         off;
    server_names_hash_max_size      512;
    server_names_hash_bucket_size   512;

# Log format
    log_format  main    '$remote_addr - $remote_user [$time_local] $request '
                        '"$status" $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';
    log_format  bytes   '$body_bytes_sent';
    #access_log          /var/log/nginx/access.log main;
    access_log off;

    # Mime settings
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

# Compression
    gzip                on;
    gzip_comp_level     9;
    gzip_min_length     512;
    gzip_buffers        8 64k;
    gzip_types          text/plain text/css text/javascript text/js text/xml application/json application/javascript application/x-javascript application/xml application/xml+r$
    gzip_proxied        any;
    gzip_disable        "MSIE [1-6]\.";

    # Proxy settings
    proxy_redirect  off;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP   $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass_header   Set-Cookie;
    proxy_connect_timeout   90;
    proxy_send_timeout  90;
    proxy_read_timeout  90;
    proxy_buffers   32 4k;

    # Cloudflare https://www.cloudflare.com/ips
    set_real_ip_from   199.27.128.0/21;
    set_real_ip_from   173.245.48.0/20;
    set_real_ip_from   103.21.244.0/22;
    set_real_ip_from   103.22.200.0/22;
    set_real_ip_from   103.31.4.0/22;
    set_real_ip_from   141.101.64.0/18;
    set_real_ip_from   108.162.192.0/18;
    set_real_ip_from   190.93.240.0/20;
    set_real_ip_from   188.114.96.0/20;
    set_real_ip_from   197.234.240.0/22;
    set_real_ip_from   198.41.128.0/17;
    set_real_ip_from   162.158.0.0/15;
    set_real_ip_from   104.16.0.0/12;
    set_real_ip_from   172.64.0.0/13;
    #set_real_ip_from   2400:cb00::/32;
    #set_real_ip_from   2606:4700::/32;
    #set_real_ip_from   2803:f800::/32;
    #set_real_ip_from   2405:b500::/32;
    #set_real_ip_from   2405:8100::/32;
    real_ip_header     CF-Connecting-IP;

# SSL PCI Compliance
    ssl_session_cache   shared:SSL:10m;
    ssl_protocols   TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers        "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SH$

    # Error pages
    error_page          403          /error/403.html;
    error_page          404          /error/404.html;
    error_page          502 503 504  /error/50x.html;

# Cache settings
    proxy_cache_path /var/cache/nginx levels=2 keys_zone=cache:10m inactive=60m max_size=1024m;
    proxy_cache_key "$host$request_uri $cookie_user";
    proxy_temp_path  /var/cache/nginx/temp;
    proxy_ignore_headers Expires Cache-Control;
    proxy_cache_use_stale error timeout invalid_header http_502;
    proxy_cache_valid any 1d;

    # Cache bypass
    map $http_cookie $no_cache {
        default 0;
        ~SESS 1;
        ~wordpress_logged_in 1;
    }

    # File cache settings
    open_file_cache          max=10000 inactive=30s;
    open_file_cache_valid    60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors   off;
    proxy_cache_valid any 1d;

    # Cache bypass
    map $http_cookie $no_cache {
        default 0;
        ~SESS 1;
        ~wordpress_logged_in 1;
    }

    # Wildcard include
    include             /etc/nginx/conf.d/*.conf;
}

A: If you check the configuration file you'll see the following:
include /etc/nginx/sites-enabled/*;

This means that additional vhost config files are being loaded from "/etc/nginx/sites-enabled/".
The correct way to use this is to have the config files in /etc/nginx/sites-available/ and create symlinks to them in /etc/nginx/sites-enabled/.


text:
Q: Compare workbook and generate report with highlighted differences and additional column I have two huge workbooks (old & new) of annual employee data and trying to compare. Each workbook has the same header and employees are in random order.
Here is what I'm trying to accomplish:

*

*Use employee ID (in column D) as reference and compare if they've changed information, specially Physician (in column L).

*Generate report highlight the different cell with added column (Change Information "Yes/No") if there are changes or not.

Problem:
This code compare cell by cell only (took a lot of time) and not per employee id how could I insert here the looping of employee id? I am newbie in VBA. Any guidance on how I should go about this? Thanks.
Sub compare2Worksheets()
Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer
Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String
Dim report As Workbook, difference As Long
Dim row As Long, col As Integer
Dim ws1 As Workbooks
Dim ws2 As Workbooks

Set report = Workbooks.Add

'range of Data1
Set ws1 = ThisWorkbook.Worksheets("Data1")
With ws1.UsedRange
ws1row = .Rows.Count
ws1col = .Columns.Count
End With

'range of Data2
Set ws2 = myworkbook.Worksheets("Data2")
With ws2.UsedRange
ws2row = .Rows.Count
ws2col = .Columns.Count
End With

maxrow = ws1row
maxcol = ws1col
If maxrow < ws2row Then maxrow = ws2row
If maxcol < ws2col Then maxcol = ws2col

'generate report
report.Worksheets("Sheet1").Activate
Cells.Clear
Range("A1") = "FirstName"
Range("B1") = "LastName"
Range("C1") = "DOB"
Range("D1") = "EmployeeID"
Range("E1") = "Address"
Range("F1") = "Emailadd"
Range("G1") = "Mobilenumber"
Range("H1") = "DeptID"
Range("I1") = "DeptName"
Range("J1") = "Position"
Range("K1") = "Status"
Range("L1") = "Physician"
Range("M1") = "Change InformationY / N"
erow = Data1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).row

'look for differences
difference = 0
For col = 1 To maxcol
    For row = 1 To maxrow
    colval1 = ws1.Cells(row, col)
    colval2 = ws2.Cells(row, col)
        If colval1 <> colval2 Then
        difference = difference + 1
        'not matched display and highlight
        Cells(row, col) = colval1 & " <> " & colval2
        Cells(row, col).Interior.Color = 255
        Cells(row, col).Font.ColorIndex = 2
        Cells(row, col).Font.Bold = True
        'to update "Change InformationY / N"
        Cells(row + 1, 13).Value = "Yes"
        Else
        Cells(row, col) = colval2
        Cells(row + 1, 13).Value = "No"
        End If
Next row
Next col

'saving report
If difference > 0 Then
Columns("A:B").ColumnWidth = 25
myfilename = InputBox("Enter Filename")
myfilename = myfilename & ".xlsx"
ActiveWorkbook.SaveAs Filename:=myfilename
End If

End Sub

A: I would do the following here:
First I would create an array for the EmployeeID and the rows I found them in both sheets.
For that I need to declare a RecordType (has to be defined at the beginning of the module, not in the procedure!)
I assume, that you have less than 1024 employees to handle, if more, simply use a higher value in the Dim-Statement.
I also assume, that the Employee-Id is a string, otherwise you have to use 'Long' or 'Integer' instead
Type EmpRowRec
   EmpId as string
   Row1 as Long
   Row2 as Long
End Type
Dim EmpRowArr(1 to 1024) as EmpRowRec, EmpRowCnt as integer

Then I would go through both sheets and search for the row with the data for an employee:
Dim CurRow as long, CurEmpRow as integer,EmpRowOut as integer
…
EmpRowCnt=0
For CurRow = 2 to ws1Row
   Colval1=ws1.cells(currow,4).value
   EmpRowCnt=EmpRowCnt+1
   EmpRowArr(EmpRowCnt).EmpId=colval1
   EmpRowArr(EmpRowCnt).row1=CurRow
Next CurRow
For CurRow = 2 to ws2Row
   Colval1=ws2.cells(currow,4).value
   EmpRowOut=0
   For CurEmpRow=1 to EmpRowCnt
      If EmpRowArr(CurEmpRow).EmpId=ColVal1 then EmpRowOut=0:Exit For
   Next CurEmpRow
   If EmpRowOut=0 then ' Employee is only in sheet 2
      EmpRowCnt=EmpRowCnt+1
      EmpRowArr(EmpRowCnt).EmpId=colval1
      EmpRowArr(EmpRowCnt).row2=CurRow
   else
      EmpRowArr(EmpRowOut).row2=CurRow
   End If
Next CurRow

Now you can go through the array and create your report:
Currow =1 'You already copied the head values
For CurEmpRow=1 to EmpRowCnt
   with EmpRowArr(CurEmpRow)
      If (.row1>0) and (.row2>0) then 'your result will show only employees in both sheets
         Currow=currow+1
         For col=1 to maxcol
            Colval1=ws1.cells(.row1,col).value
            Colval2=ws1.cells(.row2,col).value
            Report.cells(currow,col).value=colval1
            If colval1<>colval2 then report.cells(currow,col).interior.color=rgb(255,200,200)
         Next col
      End if
   End with
Next CurEmpRow

This method shall show you a generic way to solve such a problem (I have to deal very often with). For sure adaptions e.g. how to handle employees appearing only in one sheet, marking changes with low or high impact are needed, but here I can't help you since I don't know your exact requests.
Due to the fact, that I wrote this text only in word I could not test the fragments under VBA, so some small errors may occur. Please try to fix it.

A: This is the code with your logic:
Type EmpRowRec
   EmpId As String
   Row1 As Long
   Row2 As Long
End Type

Sub compare2Worksheets()
Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer
Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String
Dim report As Workbook, difference As Long
Dim row As Long, col As Integer
Dim CurRow As Long, CurEmpRow As Integer, EmpRowOut As Integer
Dim wbkA As Workbook, wbkB As Workbook
Dim EmpRowArr(1 To 1024) As EmpRowRec, EmpRowCnt As Integer

'get worksheets from the workbooks
Set wbkA = Workbooks("Data1")
Set ws1 = wbkA.Worksheets("Data1")
'range of Data1
With ws1.UsedRange
ws1row = .Rows.Count
ws1col = .Columns.Count
End With

Set wbkB = Workbooks("Data2")
Set ws2 = wbkB.Worksheets("Data2")
'range of Data2
With ws2.UsedRange
ws2row = .Rows.Count
ws2col = .Columns.Count
End With

maxrow = ws1row
maxcol = ws1col
If maxrow < ws2row Then maxrow = ws2row
If maxcol < ws2col Then maxcol = ws2col

'generate report workbook
Set report = Workbooks.Add
report.Worksheets("Sheet1").Activate
Cells.Clear
Range("A1") = "FirstName"
Range("B1") = "LastName"
Range("C1") = "DOB"
Range("D1") = "EmployeeID"
Range("E1") = "Address"
Range("F1") = "Emailadd"
Range("G1") = "Mobilenumber"
Range("H1") = "DeptID"
Range("I1") = "DeptName"
Range("J1") = "Position"
Range("K1") = "Status"
Range("L1") = "Physician"
Range("M1") = "Change InformationY / N"
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).row

'go through both sheets and search for the row with the data for an employee
EmpRowCnt = 0
For CurRow = 2 To maxrow  'ws1row
   colval1 = ws1.Cells(CurRow, 4).Value
   EmpRowCnt = EmpRowCnt + 1
   EmpRowArr(EmpRowCnt).EmpId = colval1
   EmpRowArr(EmpRowCnt).Row1 = CurRow
Next CurRow
For CurRow = 2 To maxrow  'ws2row
   colval1 = ws2.Cells(CurRow, 4).Value
   EmpRowOut = 0
   For CurEmpRow = 1 To EmpRowCnt
      If EmpRowArr(CurEmpRow).EmpId = colval1 Then EmpRowOut = 0: Exit For
   Next CurEmpRow
   If EmpRowOut = 0 Then ' Employee is only in sheet 2
      EmpRowCnt = EmpRowCnt + 1
      EmpRowArr(EmpRowCnt).EmpId = colval1
      EmpRowArr(EmpRowCnt).Row2 = CurRow
   Else
      EmpRowArr(EmpRowOut).Row2 = CurRow
   End If
Next CurRow

'go through the array and create your report

CurRow = 1 'You already copied the head values
For CurEmpRow = 1 To EmpRowCnt
   With EmpRowArr(CurEmpRow)
      If (.Row1 > 0) And (.Row2 > 0) Then 'your result will show only employees in both sheets
         CurRow = CurRow + 1
         For col = 1 To maxcol
            colval1 = ws1.Cells(.Row1, col).Value
            colval2 = ws1.Cells(.Row2, col).Value
            report.Cells(CurRow, col).Value = colval1
            If colval1 <> colval2 Then report.Cells(CurRow, col).Interior.Color = RGB(255, 200, 200)
         Next col
      End If
   End With
Next CurEmpRow

If CurRow > 0 Then
Columns("A:Y").ColumnWidth = 25
myfilename = InputBox("Enter Filename")
myfilename = myfilename & ".xlsx"
ActiveWorkbook.SaveAs Filename:=myfilename
End If

End Sub

A: Use a Dictionary as a lookup table for the row number of each ID on the old data sheet. Then scan down the new sheet comparing rows with the same ID. IDs that appear on the new sheet but not the old are tagged "added". Those on the old sheet but not the new are tagged "deleted".
Option Explicit
Sub compare2Worksheets()

    ' config
    Const COL_ID = "D"
    Const COLS = 12 ' header col A to L

    Dim wb1 As Workbook, wb2 As Workbook, wbRep As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet, wsRep As Worksheet
    Dim LastRow As Long, c As Long, i As Long, r As Long, n As Long
    Dim bDiff As Boolean, t0 As Single
    t0 = Timer

    Dim dict As Object, key As String
    Set dict = CreateObject("Scripting.Dictionary")

    'range of Data1
    Set wb1 = ThisWorkbook
    Set wb2 = ThisWorkbook ' or other
    Set ws1 = wb1.Sheets("Data1") ' old data
    Set ws2 = wb2.Sheets("Data2") ' new data

    ' build lookup from data1
    With ws1
        LastRow = .Cells(.Rows.Count, COL_ID).End(xlUp).row
        For i = 2 To LastRow
            key = Trim(.Cells(i, COL_ID))
            If dict.exists(key) Then
                MsgBox "Duplicate ID " & key, vbCritical, .Name & " Row " & i
                Exit Sub
            ElseIf Len(key) > 0 Then
                dict.Add key, i
            End If
        Next
    End With

    ' format report sheet
    Set wbRep = Workbooks.Add(1)
    Set wsRep = wbRep.Sheets(1)
    wsRep.Name = "Created " & Format(Now, "YYYY-MM-DD HHMMSS")
    ws1.Range("A1").Resize(, COLS).Copy wsRep.Range("A1")
    wsRep.Cells(1, COLS + 1) = "Change InformationY / N"

    ' copare data2 new data to data1 old data
    ' copy diff to report
    Application.ScreenUpdating = False
    With ws2
        LastRow = .Cells(.Rows.Count, COL_ID).End(xlUp).row
        For i = 2 To LastRow
            key = Trim(.Cells(i, COL_ID))
            wsRep.Cells(i, COL_ID) = key
            If dict.exists(key) Then

                 r = dict(key)
                 dict.Remove key ' remove

                 ' check columns in row
                 bDiff = False
                 For c = 1 To COLS
                     If .Cells(i, c) <> ws1.Cells(r, c) Then
                         With wsRep.Cells(i, c)
                              .Value = ws2.Cells(i, c) & "<>" & ws1.Cells(r, c)
                              .Interior.Color = 255
                              .Font.ColorIndex = 2
                              .Font.Bold = True
                         End With
                         bDiff = True
                     End If
                 Next
                 If bDiff Then
                      wsRep.Cells(i, COLS + 1) = "Yes"
                      n = n + 1
                 Else
                      wsRep.Cells(i, COLS + 1) = "No"
                 End If
            Else
                ' copy all
                .Cells(i, 1).Resize(, COLS).Copy wsRep.Cells(i, 1)
                wsRep.Cells(i, COLS + 1) = "Added"
                n = n + 1
            End If
        Next
    End With

    ' keys remaining
    Dim k
    With ws1
        For Each k In dict.keys
            r = dict(k)
            .Cells(r, 1).Resize(, COLS).Copy wsRep.Cells(i, 1)
            wsRep.Cells(i, COL_ID) = k
            wsRep.Cells(i, COLS + 1) = "Deleted"
            i = i + 1
            n = n + 1
        Next
    End With
    Application.ScreenUpdating = True

    Dim s As String, yn
    wsRep.Columns("A:M").AutoFit
    yn = MsgBox(n & " lines differ, save report Y/N ?", vbYesNo, _
               Format(Timer - t0, "0.0 secs"))

    If yn = vbYes Then
        s = InputBox("Enter Filename")
        wbRep.SaveAs Filename:=s & ".xlsx"
    End If
    wbRep.Close False

End Sub

A: Sorry, I have overseen, that 'Report' is a workbook, not a sheet. PLease replace 'Report.Cells()' with 'Report.Worksheets("Sheet1").Cells()'


text:
Q: Installing mysql on mac snow leopard Mac OS X 10.6.8 error I'm a newbie to Django and I want to run it not with SQLite but with my current MySQL database set up through PHP. However, I am coding mainly on a Mac (the bane of my developer existence) and I have run into a problem with running:
python setup.py build

from my MySQL-python-1.2.4b4 folder and it's giving me the following error. I have tried Googling for the solution but most results show an error with XCode4 for Mac OS Lion or Mountain Lion and I'm running Snow Leopard. The results I found for Snow Leopard doesn't work either.
running develop

running egg_info

writing MySQL_python.egg-info/PKG-INFO

writing top-level names to MySQL_python.egg-info/top_level.txt

writing dependency_links to MySQL_python.egg-info/dependency_links.txt

warning: manifest_maker: standard file '-c' not found

reading manifest file 'MySQL_python.egg-info/SOURCES.txt'

reading manifest template 'MANIFEST.in'

writing manifest file 'MySQL_python.egg-info/SOURCES.txt'

running build_ext

building '_mysql' extension

gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -pipe -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/local/mysql/include -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/temp.macosx-10.6-universal-2.6/_mysql.o -g -Os -arch x86_64 -fno-common -D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL

unable to execute gcc-4.2: No such file or directory

error: command 'gcc-4.2' failed with exit status 1

A: Since you mention that xcodebuild is not found, the most likely explanation is that you have not yet installed a version of Xcode which includes various build tools, like the gcc C compiler needed to build the C extension module included in MySQL-python.  Since you are running on OS X 10.6, Snow Leopard, the most recent version of Xcode for 10.6 that includes gcc-4.2 is Xcode 3.2.6 which you can download without cost from the Apple Developer site after free registration.  See, for example, the directions here.  Unfortunately, the download is very large.  (More recent releases of Xcode for more recent OS X releases are packaged in smaller pieces but they are not supported on 10.6.)  The good news is: you'll only have to do it once since Xcode for 10.6 is not likely to ever be updated again!


text:
Q: Tooltips for a SVG photo that work on an iPad I have a svg photo on the page at https://bullittcountyhistory.org/1974centennial/crowdview.html that uses the title code for a tooltip to identify each person's face when hovering over it. It works fine except on a mobile device like the iPad.
I've also found at https://www.w3schools.com/css/css_tooltip.asp css tooltip code that works on the iPad as well as my computer.
Is there any way to tie the two together, creating tooltips that show up on the iPad? I've spent the last two days searching the internet for clues, but no one seems to have figured this out (that I can see).

A: You would basically do the same thing, except you would use SVG elements, instead of HTML ones.
However I don't have an iPad, so I can't vouch for whether it works on one.

.tooltiptext {
  visibility: hidden;
  font-size: 16pt;
}

.tooltiptext text {
  fill: #fff;
}

.tooltiptext rect {
  fill: black;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}
<svg>

  <g class="tooltip">
    <circle cx="150" cy="75" r="75" fill="red"/>

    <g class="tooltiptext">
      <rect x="90" y="62" width="120" height="1.4em" rx="6"/>
      <text x="150" y="75" dy="0.4em" text-anchor="middle">Tooltip text</text>
    </g>
  </g>

</svg>


text:
Q: Django Mysql Connection Pooling What is the best way to establish connection pooling for MySQL connections in Django..?
I have read a couple of blogs like SQLAlchemy
Can anyone suggest standard practices for the same.. I am running a B2C application on django and the number of simultaneous requests may hit 10000..

A: So for anyone still visiting this an unsatisfied with Django built in connection pooling (which has zero configuration and in all honesty I'm not too sure works), this project although years old since its last commit still works!
https://github.com/djangonauts/djorm-ext-pool


text:
Q: iscroll 5 multiple clicks Is there a way to solve the Iscroll 5 issue where the android browser seems to register multiple click. I have looked around but there is no solid solutions. If you click on a select box for example it opens the select box many times. I am having this issue on lollipop and kitkat and am using iscroll 5(latest). Downgrading Iscroll does not work either. I have click set to true.
Here is a sample of my code below:
    var myScroll;

    function loaded () {
    myScroll = new IScroll('#mydiv2', {
                mouseWheel: true,
                checkDOMChanges: false,
                topOnDOMChanges: false,
                scrollX: false,
                scrollY: true,
                click:true,
                scrollbars: false,
                useTransform: true,
                useTransition: false,
                probeType:3,
                tap: true
                      });

    var myScroll2 = new IScroll('#mywrapper', {
                mouseWheel: true,
                checkDOMChanges: false,
                topOnDOMChanges: false,
                scrollX: false,
                scrollY: true,
                click:true,
                scrollbars: false,
                useTransform: true,
                useTransition: false,
                probeType:3,
                tap: true
                      });

    }

    document.addEventListener('touchmove', function (e) {
    console.log('touch');e.preventDefault(); }, false);

A: I had the some problem and this works for me
The solution, just add this code in the top of the iscroll.js
var last_click_time = new Date().getTime();
$("a").live("click", function(ev) {
     var click_time = ev["timeStamp"];
     if (click_time && (click_time - last_click_time) < 1000) {
          ev.stopImmediatePropagation();
          return false;
     }
     last_click_x = click_x;
     last_click_y = click_y;
     last_click_time = click_time;
});

Source: https://www.scirra.com/forum/viewtopic.php?t=74123&start=0


text:
Q: Python class member changes value without assignment I have a class "test" of which I declare two instances, and on which I call an "update" function. "test.a" is a numpy array.
b1 = test()
b1.randomize(2, 0, 0, 0, 0, 0)
b2 = test()
b2.randomize(6, 0, 0.5, 0, 0, 0)
print(b1.a)
print(b2.a)
update(b1,b2)
print(b1.a)
print(b2.a)

The update function is defined as below.
The issue is that the value of b2.a changes after the call of update, despite never assigning it therein. I also never made an assignment like "b2.a = b1.a", which would change the reference of b2.a. The class definition is also copied in below.
def update(b1, b2):
  dx = b1.p[0,0] - b2.p[0,0]
  dy = b1.p[0,1] - b2.p[0,1]
  b1.a[0,0] += (-dx) * b2.m
  b1.a[0,1] += (-dy) * b2.m

class test:
  m = 1.0
  r = 0.1
  p = np.zeros((1,2))
  v = np.zeros((1,2))
  a = np.zeros((1,2))

  def randomize(self, m_mean, m_stddev, pos_mean, pos_stddev, v_mean, v_stddev):
      self.m = np.random.normal(loc = m_mean, scale = m_stddev)
      self.p = np.random.normal(loc = pos_mean, scale = pos_stddev, size = (1,2))
      self.v = np.random.normal(loc = v_mean, scale = v_stddev, size = (1,2))

A: a is a class variable, so it's shared by all the instances. If you want an a variable that's unique to each instance, you need to add the following in your class:
def __init__(self):
    self.a = np.zeros((1,2))

A: I see a couple of issues.

*

*Missing init

*Not using self to initialize (n, m, p, r, v, a)

Expanding on the above, you also should avoid accessing class variable directly. Gave you a small example of a getter and setter functions that you can use to access the private variables of a class.
class test:
    @property
    def m(self):
        return self._m
    @m.setter
    def m(self, value):
        self._m = value

    def __init__(self):
       self._m = 1.0
       self._r = 0.1
       self._p = np.zeros((1,2))
       self._v = np.zeros((1,2))
       self._a = np.zeros((1,2))

  def randomize(self, m_mean, m_stddev, pos_mean, pos_stddev, v_mean, v_stddev):
      self._m = np.random.normal(loc = m_mean, scale = m_stddev)
      self._p = np.random.normal(loc = pos_mean, scale = pos_stddev, size = (1,2))
      self._v = np.random.normal(loc = v_mean, scale = v_stddev, size = (1,2))

A: You are using improperly attributes of the instance you are creating.
When you define in python just after the class a variable this will be common between different instances of the same object and so if one of the instances
changes value of the attribute this will also be changed for other instances.
What you need to do is to define values when you instantiate the object,
this is done conventionally inside the __init__ method
like the this:
class Test:
    def __init__(self):
        self.m = 1.0
        self.r = 0.1

Check for example https://realpython.com/lessons/class-and-instance-attributes/ for more information.

A: Problem is here is that a is a class variable and hence is shared between both b1 and b2.
Though this would have not been an issue if you were assigning a new object to b1.a like b1.a = np.ones((1, 2)) because this will declare a new instance variable a for instance b1 and while b2.a still refers to the class object. So b1.a will change but b2.a will not. To be precise, b1.a and b2.a are now reference to two different objects.
>>> b1, b2 = test(), test()
>>> print("b1.a = {}, b2.a = {}".format(b1.a, b2.a))
b1.a = [[0. 0.]], b2.a = [[0. 0.]]

>>> b1.a = np.ones((1, 2))
>>> print("b1.a = {}, b2.a = {}".format(b1.a, b2.a))
b1.a = [[1. 1.]], b2.a = [[0. 0.]]

But when you do b1.a[0, 0] = (-dx) * b2.m  you are changing the value inside the container to which a is an reference. Since this container is shared by both b1.a and b2.a, in this case both b1.a and b2.a are changed as they are still pointing to the same class object(or the container).
>>> b1, b2 = test(), test()
>>>> print("b1.a = {}, b2.a = {}".format(b1.a, b2.a))
b1.a = [[0. 0.]], b2.a = [[0. 0.]]

>>> b1.a[0, 0] = 100  #
>>> print("b1.a = {}, b2.a = {}".format(b1.a, b2.a))
b1.a = [[100.   0.]], b2.a = [[100.   0.]]


text:
Q: addClass function doesn't work as expected Other effects of jQuery toggle, hide is working but addClass function doesn't work here. displyanone class is working outside, but doesn't work inside jQuery function. What is wrong here?

$(document).on('click', '#menu', function() {
  if($(this).is(':checked'))
    $(this).parent().find('ul').slideDown('slow');
  else
    $(this).parent().find('ul').addClass('displaynone');  //Doesn't work
  //$(this).parent().find('ul').hide('slow'); - works.
});
.displaynone {
  display: none;
}

  <input type="checkbox" id="menu" name="menu[]" value="">
  Checkbox

    <input type="checkbox" class="menusub" name="menusub" value="">
    Checkbox L2

A: .slideDown() adds an inline style property display:block, which overrides display:none from class displaynone. Adding the class after the inline style property was added, has no effect.
The easiest fix would be to replace class='displaynone' with style='display:none' and use .hide() to hide the element. In this case only inline style properties are used.

$(document).on('click', '#menu', function() {
  if($(this).is(':checked'))
    $(this).parent().find('ul').slideDown('slow');
  else
    $(this).parent().find('ul').hide();
});

  <input type="checkbox" id="menu" name="menu[]" value="">
  Checkbox

        <input type="checkbox" class="menusub" name="menusub" value="">
        Checkbox L2


text:
Q: Unmaximize is disabled for some apps I wish to enable unmaximize for a game (Super Tux Cart) to implement some OpenCV stuff.
There are only some preset resolutions in its settings but I wish to decrease it further.


text:
Q: CRUD text using Regex - Ruby I'm searching for a Solution to Parse and Update a Document. A very good example is user.js scripts.
Example Case:
A user uploads a user.js script to userscripts.org. The file must have a head of specific variables for the Browser. e.g.:
// ==UserScript==
// @name        Fancy Title
// @description Fancey Description
// @namespace   http://example.com
// @icon        http://example.com/icon.png
// @updateURL   http://example.com/user.js
// @downloadURL http://example.com/user.js
// @homepageURL http://example.com
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @include     http*://example.com
// @include     http://example.com/scripts/*
// @include     http://example.com/tags/*
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_listValues
// @version     1.0
// ==/UserScript==

What would be a good solution to back check those variables and modify or add them to the document. Basically importing the variables from @testing.title => @name Fancy Title and vice versa.
Let's say that if the Meta Head didn't contain the variables @udpateURL and @downloadeURL, I would add them respectively.
My first guess was to regex scan the document with (@\w+), that will get me all the variables @ but from there i'm lost :)
Can i solve this with plain ruby or is there handy gem available?
Edit:
Sam pointed out: \/\/\s*@(\w+)\s+(.*) Which captures exactly the variables i need..
The identifier(@title) and the value(Fancy Title).
How do i set, read or update them tho ?

@MrYoshiji provided me with a very awesome regex Meta Reader:
raw_metas = file_content.scan( /\A\/\/\s==UserScript==(\w|\W)*\/\/\s==\/UserScript==/ )
metas = {}
raw_metas.split(/\r\n|\n|\r/).each do |line_with_meta|
  attribute_name = line_with_data.scan(/@\w+/)
  value = line_with_data.sub("// #{attribute_name}", '').strip
  if metas[attribute_name.sub('@', '').to_sym].present?
    metas[attribute_name.sub('@', '').to_sym] = [ metas[attribute_name.sub('@', '').to_sym], value].flatten
  else
    metas[attribute_name.sub('@', '').to_sym] = value
  end
end

But i'm completely lost on how to set this up to interact with my Model's attributes.

What Meta Data i need to Change
Meaning that those attributes (:description etc) are stored in my Model and i need to pass them.
// @name => @model.name

// @description => @model.description
// @namespace   => Application root_path

// @updateURL   => @model show_view url
// @downloadURL => @Model show_view url
// @homepageURL => Application root_path

// @include     => Custom url (passed by me)
// @include     => Custom url (passed by me)
// @include     => Custom url (passed by me)

// @version     => @model.version

A: [EDIT: In a chat, you mentioned that your input may be on a single line. This second demo shows a regex to deal with that, and also the general procedure to rebuild the string.]
This code stores the names and values in two hashes, replaces the @version with 2.0, then outputs them (see the output at the bottom of the online demo):
subject = <<-eos
@name        Fancy Title
// @description Fancey Description
// @namespace   http://example.com
// @icon        http://example.com/icon.png
// @updateURL   http://example.com/user.js
// @downloadURL http://example.com/user.js
// @homepageURL http://example.com
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @include     http*://example.com
// @include     http://example.com/scripts/*
// @include     http://example.com/tags/*
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_listValues
// @version     1.0
eos

regex = /\/\/ (@\w+)\s*([^\n]*)/

# put captures in two hashes
tokens = Hash.new
values = Hash.new
counter = 0
subject.scan(regex) {|m|
    tokens[counter] = $1
    values[counter] = $2
    counter += 1
}

# find hash key for @version
versionkey = tokens.index("@version")
# change version to 2.0
values[versionkey] = "2.0"

# print names and values
i=0
while i < counter  do
   puts "#{tokens[i]} : #{values[i]}"
   i +=1
end

The key is that token names are captured to Group 1, and token values are captured to Group 2 (see the regex explanation below). We build hashes with the values in these two groups.
To manipulate values, you have several options:

*

*Use regex with gsub to replace lines in your string (not recommended)

*Directly manipulate values in the hashes to your heart's content, as shown in the demo, where @version is changed to 2.0, then rebuild the string if needed. That's what I would do.
Explain Regex
//                       # '// '
(                        # group and capture to \1:
  @                      #   '@'
  \w+                    #   word characters (a-z, A-Z, 0-9, _) (1 or
                         #   more times (matching the most amount
                         #   possible))
)                        # end of \1
\s*                      # whitespace (\n, \r, \t, \f, and " ") (0 or
                         # more times (matching the most amount
                         # possible))
(                        # group and capture to \2:
  [^\n]*                 #   any character except: '\n' (newline) (0
                         #   or more times (matching the most amount
                         #   possible))
)                        # end of \2


text:
Q: PayPal payment_status always Pending when I use Sandbox I am using the PayPal IPN feature but I keep getting _POST[payment_status] = Pending when I make a test using the Sandbox. Because of that, I can't test the full purchase to make sure the whole process works properly.
Here is my code:
// Set the request paramaeter
$req = 'cmd=_notify-validate';

// Run through the posted array
foreach ($_POST as $key => $value)
{
    // If magic quotes is enabled strip slashes
    if (get_magic_quotes_gpc())
    {
        $_POST[$key] = stripslashes($value);
        $value = stripslashes($value);
    }
    $value = urlencode($value);
    // Add the value to the request parameter
    $req .= "&$key=$value";
}

$ch = curl_init();    // Starts the curl handler
curl_setopt($ch, CURLOPT_URL,$paypal[$testing]); // Sets the paypal address for curl
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // Returns result to a variable instead of echoing
curl_setopt($ch, CURLOPT_TIMEOUT, 3); // Sets a time limit for curl in seconds (do not set too low)
curl_setopt($ch, CURLOPT_POST, 1); // Set curl to send data using post
curl_setopt($ch, CURLOPT_POSTFIELDS, $req); // Add the request parameters to the post
$result = curl_exec($ch); // run the curl process (and return the result to $result
curl_close($ch);

if (strcmp ($result, "VERIFIED") == 0) // It may seem strange but this function returns 0 if the result matches the string So you MUST check it is 0 and not just do strcmp ($result, "VERIFIED") (the if will fail as it will equate the result as false)
{
// It worked
// do my stuff
}else{

    foreach($_POST as $key=>$value){
        $post_str .="_POST[$key] = $value<br>";
    }

    $sub = "Paypal error";
    $mes = "$post_str";
    mailer($sub, $mes, $from, $to);

}

This is the error message I get in my email:
_POST[mc_gross] = 120.00
_POST[protection_eligibility] = Ineligible
_POST[address_status] = confirmed
_POST[payer_id] = QDZDYY4JWGFVG
_POST[tax] = 0.00
_POST[address_street] = 1 Maire-Victorin
_POST[payment_date] = 12:25:03 Apr 11, 2013 PDT
_POST[payment_status] = Pending
_POST[charset] = windows-1252
_POST[address_zip] = M5A 1E1
_POST[first_name] = gppl
_POST[address_country_code] = CA
_POST[address_name] = gppl Simard's Test Store
_POST[notify_version] = 3.7
_POST[custom] =
_POST[payer_status] = verified
_POST[address_country] = Canada
_POST[address_city] = Toronto
_POST[quantity] = 1
_POST[verify_sign] = An5ns1Kso7MWUdW4ErQKJJJ4qi4-AjAXF3KMNcb6G83Jslw18dw.Ti32
_POST[payer_email] = 78h23d8712h3d@x.com
_POST[txn_id] = 2KU491796R824634N
_POST[payment_type] = instant
_POST[payer_business_name] = gppl x's Test Store
_POST[last_name] = Simard
_POST[address_state] = Ontario
_POST[receiver_email] = x@x.x
_POST[pending_reason] = unilateral
_POST[txn_type] = web_accept
_POST[item_name] = 926537
_POST[mc_currency] = CAD
_POST[item_number] =
_POST[residence_country] = CA
_POST[test_ipn] = 1
_POST[handling_amount] = 0.00
_POST[transaction_subject] = 926537
_POST[payment_gross] =
_POST[shipping] = 0.00
_POST[ipn_track_id] = c7dcef0b1c333

This error is really driving me nuts.
Just so you guys know, I already have the Payment review set to off.

A: If you are useing sandbox, open developer.paypal.com->Dashboard->Accounts->facilitator@yourhost.com->Profile->Settings. Set 'Payment review' to 'Off'

A: Make sure your accounts have a confirmed email address.  This typically happens when you send a payment to an account that doesn't have a confirmed email address.  So check the seller account, and make sure the email address is confirmed that you sent the payment to.

A: I had this problem - I was sending PayPal my "live" payer_email, when I changed it to the business email in the sandbox it worked. same as my live email with ****-facilitator@yoursite.com

A: Login to your Sandbox account with the business, and see if you have any 'Unclaimed' payments.  This could be because they are in a different currency than the one of your main account.


text:
Q: Client side table to Excel with jquery I'd like to client side table to Excel .xls, no server side.
Following code includes simple table and Javascript and table to Excel successfully but doesn't work in Firefox or Chrome?
How can I run it in all browsers?

 Name 	 Age

 Shivani 	 25

 Naren 	 28

 Logs	 57

A: ActiveXObject is an Internet Explorer only method. You can't do what you're trying to do purely with jquery/javascript (at least, not trivially)
You're either going to have to use a server-side application that can generate the Excel spreadsheets, or generate a CSV of your file, base64-encode it and navigate the browser to the base64'ed data using the data: URI scheme to trigger a 'download' of the contents you've generated.


text:
Q: Compiling Botan 1.10.1: undefined namespaces Just switched from Botan 1.4 to Botan 1.10. Configure, make and install worked fine on my Mac (OSX10.6).
But trying to use the lib
#include <stdio.h>
#include <stdlib.h>
#include <bigint.h>

int main(void) {
    puts("!!!Hello World!!!");

    Botan::BigInt * otto = new Botan::BigInt(1);

    delete otto;

    return EXIT_SUCCESS;
}

results in an build error:
g++ -O2 -g -Wall -fmessage-length=0 -I/usr/local/include/botan    -c -o BotanTest.o
BotanTest.cpp
In file included from /usr/include/c++/4.2.1/cwchar:52,

             from /usr/include/c++/4.2.1/bits/postypes.h:46,
             from /usr/include/c++/4.2.1/iosfwd:49,
             from /usr/include/c++/4.2.1/bits/stl_algobase.h:70,
             from /usr/include/c++/4.2.1/bits/char_traits.h:46,
             from /usr/include/c++/4.2.1/string:47,
             from /usr/local/include/botan/allocate.h:12,
             from /usr/local/include/botan/secmem.h:11,
             from /usr/local/include/botan/buf_comp.h:11,
             from /usr/local/include/botan/entropy_src.h:11,
             from /usr/local/include/botan/rng.h:11,
             from /usr/local/include/botan/bigint.h:12,
             from BotanTest.cpp:11:
/usr/include/c++/4.2.1/ctime:66: error: '::clock_t' has not been declared
/usr/include/c++/4.2.1/ctime:68: error: '::tm' has not been declared
/usr/include/c++/4.2.1/ctime:70: error: '::clock' has not been declared
/usr/include/c++/4.2.1/ctime:71: error: '::difftime' has not been declared
/usr/include/c++/4.2.1/ctime:72: error: '::mktime' has not been declared
/usr/include/c++/4.2.1/ctime:73: error: '::time' has not been declared
/usr/include/c++/4.2.1/ctime:74: error: '::asctime' has not been declared
/usr/include/c++/4.2.1/ctime:75: error: '::ctime' has not been declared
/usr/include/c++/4.2.1/ctime:76: error: '::gmtime' has not been declared
/usr/include/c++/4.2.1/ctime:77: error: '::localtime' has not been declared
/usr/include/c++/4.2.1/ctime:78: error: '::strftime' has not been declared

Is there a need to use a special string implementation? All libraries are available and paths seem to be ok (/usr/local/include).

A: Botan 1.10 won't work. It's sufficient to take Botan 1.8 for using the crypt codec. This will work.


text:
Q: Alternatives to PL/SQL? Are there any other programming language/IDE combos that offer autocomplete and syntax validation for (Oracle) SQL queries? I'm looking for an alternative to PL/SQL. PL/SQL is mediocre at best but I haven't found anything that's even close to matching its productivity when writing Oracle database-centric scripts.
So, are there any other programming languages that offer any of the following features?

*

*Natively handle SQL queries (SQL treated as code, not as a string).

*Autocomplete for table & column names.

*SQL is validated against DB at compile time.

*Edit: I'm well aware of, and use, IDEs for SQL and PL/SQL that offer autocomplete. I'm merely wondering if there exists any other programming language out there that lets you intermingle SQL and code in a similar way to PL/SQL.

A:
"Awkward exception handling, a lack of many built-in datatypes and
  functions that you take for granted in most languages, lack of
  anything resembling proper support for multi-threaded programming,
  inability to access the filesystem of the person running the script
  (SSH access to prod DB servers is often out of the question), hugely
  awkward for OOP, dealing with packages can be a PITA, doesn't respect
  role-base grants, etc... PL/SQL is awesome when it comes to
  integration with the DB, but beyond that it's a fairly poor language
  once you go past a certain level of complexity."

One by one.
Awkward exception handling
Awkwardness is in the eye of the beholder but I'll give you that one.  Too much is left up to the individual developer.
a lack of many built-in datatypes ... that you take for granted in most languages
It has the same datatypes as SQL, plus BOOLEAN.  What more can you want?
lack of anything resembling proper support for multi-threaded programming
Multithreading is a tricky concept to combine with read-consistency in a multi-user environment.  The Aurora JVM doesn't support mult-threaded Java in Java Stored Procedures either.  It's not a limitation of PL/SQL.
inability to access the filesystem of the person running the script
Again, that's not a PL/SQL issue.  Ask your network administrator to map a fileshare on your PC to the network.
hugely awkward for OOP
Yeah well, OOP is on its way out, everybody's down with functional programming these days.
dealing with packages can be a PITA
Personal opinion.  I love packages.
doesn't respect role-base grants
Again, that's not PL/SQL, it's the database security model.  Views don't respect role-based grants either.
once you go past a certain level of complexity
Write it in Java and call if from a Java Stored Procedure.  Or write it on C and call it from an extproc.

A: I guess there is plenty of alternatives with various level of conformance to your set of requirements. Take a look e.g to:

*

*Squeryl for Scala

*HaskellDB for Haskell

*LINQ for .NET

A: TOAD is pretty good -- works for PL/SQL, TSQL etc. http://www.quest.com/toad/
SQL Complete is an add-in for SSMS (TSQL): http://www.devart.com/dbforge/sql/sqlcomplete/
Redgate SQL Prompt: http://www.red-gate.com
These 3 above are pretty main-stream, well-liked, well-supported.  But otherwise, just pick your desired sql dialect, and google for it -- i.e. "tsql auto-complete" or "pl/sql auto-complete" to find more.
Your question also asks about a good language...  I wouldn't exactly call pl/sql mediocre (unless I was trying to get a rise out of one of our tech guys anyway :-).  TSQL is also good, and getting more and more 'mature', as they say, though it's still often compared to pl/sql in the context of "is tsql as mature as pl/sql yet...".  But whatever you choose, "good" just means is it appropriate to your application and skillset more than anything.