text:
Q: cakePHP - redirect after login first to say I checked also into this answer and this other answer but it seems that doesn't solve the problem.
Expected result: after a successful login, redirect to "/admin/dashboard/index"
Actual result: after a successful login the application redirects to "/users/login". Login is done right, I can see it in the session. Also, when manually navigating to "/admin/dashboard" in the browser it redirects to "/admin" then following the rule defined in Config/routes.php it goes in infinite redirect loop
Here the relevant code:
in Config/core.php
Configure::write( 'Routing.prefixes', array( 'admin' ) );
in Config/routes.php
Router::connect( '/admin', array( 'controller' => 'dashboard', 'action' => 'index', 'admin' => true ) );
This is in my login action in UsersController
if ( $this->request->is( 'post' ) ) {
    if ( $this->Auth->login() ) {
        $this->redirect( $this->Auth->redirectUrl() );
    } else {
        $this->BASession->err( __( 'Login error. Please check your data!' ) );
    }
}

And, finally, this is my Auth configuration
    $this->Auth->loginAction = array( 'controller' => 'users', 'action' => 'login', 'admin' => false );
    $this->Auth->logoutRedirect = array( 'controller' => 'users', 'action' => 'login', 'admin' => false );
    $this->Auth->loginRedirect = array( 'controller' => 'dashboard', 'action' => 'index', 'admin' => true );
    $this->Auth->autoRedirect = true;

Relevant to say that changing with
$this->Auth->autoRedirect = false;
Does not makes any difference.
A DashboardController class with an empty "admin_index" function exists, even a blank view.
In the login function, debugging "$this->Auth->redirectUrl()" displays "/admin"
PHP version 5.4.10 - cakePHP version 2.5.1
I hope I have given sufficient information, if not, ask for them.
thank you!

A: Write below code in the AppController.php
public function beforeFilter() {
      $this->Auth->loginAction = array( 'controller' => 'users', 'action' => 'login', 'admin' => false );
      $this->Auth->logoutRedirect = array( 'controller' => 'users', 'action' => 'login', 'admin' => false );
      $this->Auth->loginRedirect = array( 'controller' => 'dashboard', 'action' => 'index', 'admin' => true );

}

login action in UsersController
if ( $this->request->is( 'post' ) ) {
    if ( $this->Auth->login() ) {
       $this->redirect($this->Auth->redirect());
   } else {
      $this->Session->setFlash(__('Your username or password was incorrect.'));
   }
 }


text:
Q: setting a value on object member in fabric.js Following advice from this question I keep custom attributes in a central place using a _data object.
Setting attributes using set doesn't work like expected.
var opts = {
    'width': 200,
    'height': 200,
    _data:{'key':'oldvalue'}
};
var rect = new fabric.Rect(opts);
rect.set('_data.key', 'newvalue')
//rect.get('_data.key') will still return 'oldvalue'

It seems obvious that set uses _data.key as string - but is there any other way?
Of course i can do rec._data.key = 'newvalue'...
using this approach for now:
var _data = rect.get('_data')
_data.key = 'newvalue'
rect.set('_data', _data)

A: You can use any key name in a fabric object set method. But in a typescript project the editor will complain because the interfaces for the Object class don't have these properties.
The interface "Object" extends the interface "IObjectOptions", which includes the properties that belong to the fabric base Object. There are two properties (name and data) that can be used to add custom properties. name must be a string, and data can be anything.
Here's the snippet within the IObjectOptions interface:
/**
 * Not used by fabric, just for convenience
 */
name?: string;

/**
 * Not used by fabric, just for convenience
 */
data?: any;

Example:

rect.set('name', 'myname');

rect.set('data', {
  'key1':'value1',
  'key2':'value2',
  'key3':'value3'
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Memory leaks with ARC in objective c
I am working on a project and I decided to check leaks in my app.It shows all kinds of leaks on a single page.So,I read about memory leaks and got a fair idea of how the leak checker works.
But here,as you can see,there are leaks that are not relevant to my code.What to do about these leaks?


text:
Q: PhpStorm cursor doesnt move on return in strings When I press the Enter key while using PhpStorm when my cursor is in a string, the cursor doesn't move to the next line. It creates a new line, but the cursor remains in place. How can I change this?

A: It's a bug. It affects strings with injected SQL language.
https://youtrack.jetbrains.com/issue/WI-56153 -- watch this ticket (star/vote/comment) to get notified with any progress.


text:
Q: Android, color an item of a listView I have a listView that uses the
SimpleAdapter

Each element of this list contains 2 textView
I wanna color(change the backgroud color) an item of this list, how can I do?

A: this could be done using android selector (xml). see the example here

A: To change the background color of the whole view (not just the textview) and using a very simplistic approach you would have this call:
private void setupAdapter() {
    SimpleAdapter adapter = new SimpleAdapter(this, data, resource, from, to) {
        public View getView(int position, View convertView, ViewGroup parent) {
            View superView = super.getView(position, convertView, parent);
            superView.setBackgroundColor(R.color.black); // or whatever color
            return superView;
        };
    };
    // use the adapter as: myListView.setAdapter(adapter);
}

A: One way to create custom SimpleAdapter class which overrides getView method and there you make an background change depending - I guess - on some condition.


text:
Q: SQL Server Backup through C#. File not found, could not load Microsoft.SqlServer.BatchParser what?! I am trying to create a backup. I dont understand what the error I'm getting points to. Which is not found?!
this is the error message: http://img717.imageshack.us/img717/1772/sql1.jpg
my code:
    public void BackupDatabase(String destinationPath)
    {
        try
        {
            //MY SERVER
            String userName = "NNIT-Admin";
            String password = "password";
            String serverName = @"RITZEL-PC\SQLEXPRESS";

            ServerConnection connection = new ServerConnection(serverName, userName, password);
            Server sqlServer = new Server(connection);

            Backup BackupMgr = new Backup();
            BackupMgr.Devices.AddDevice(destinationPath, DeviceType.File);
            BackupMgr.Database = @"RITZEL-PC\SQLEXPRESS\Databases\D:\MY_THESIS\WORKING FILES\NNIT-RMS.MDF";
            BackupMgr.Action = BackupActionType.Database;
            BackupMgr.SqlBackup(sqlServer);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + " " + ex.InnerException);
        }
    }

    private void BackUp_Btn_Click(object sender, EventArgs e)
    {
        String destinationPath = @"D:\";

        BackupDatabase(destinationPath);

    }

A: According to a quick Google search you need to install the 64-bit SMO components:

I found as solution here:
http://www.microsoft.com/downloads/details.aspx?familyid=D09C1D60-A13C-4479-9B91-9E8B9D835CDC&displaylang=en
Download and install
X64 Package (SQLServer2005_XMO_x64.msi) - 14675 KB
This installs the 64 bit smo objects.


text:
Q: Creation of authentication connection is failing I am following the virtual assistant get started sample:
Virtual asistant
I am stuck on the step "Skill Authentication".
I tried to use the following command with all the arguments and generated botsecret for --secret argument.
msbot connect generic --name "Authentication" --keys "{\"YOUR_AUTH_CONNECTION_NAME\":\"Azure Active Directory v2\"}" --bot YOURBOTFILE.bot --secret "YOUR_BOT_SECRET" --url "portal.azure.net"

I still get the following error:

Error: You are attempting to perform an operation which needs access to the secret and --secret is missing

Can someone tell me what am I missing?


text:
Q: SwiftSoup: removeAttr having no effect when getting body of document I am removing href attribute and adding it again with a different link.
    try document?.select(className).first()?.select(linkClassName).removeAttr("href")
    try document?.select(className).first()?.select(linkClassName).attr("href", link.utf8EncodedString())

But when I do
try document?.body()?.html() it has no change in it.


text:
Q: Why is the Node.js AWS-SDK returning the wrong SQS queue URL when creating a local queue I'm using ElasticMQ to simulate AWS SQS on my local dev machine. I'm running ElasticMQ inside a Docker container, using docker-osx-dev to host the Docker container on a Linux VM. This means that I access the local ElasticMQ instance at the IP of the VM, not my localhost IP.
When I try and create a queue in EMQ using the code below, it returns a queue URL at localhost and not the IP of the VM hosting the docker container.
var AWS = require('aws-sdk');
var config = {
  endpoint: new AWS.Endpoint('http://192.168.59.103:9324'),
  accessKeyId: 'na',
  secretAccessKey: 'na',
  region: 'us-west-2'
}
var sqs = new AWS.SQS(config);
var params = {
  QueueName: 'test_queue'
};
sqs.createQueue(params, function(err, data) {
  if (err) {
    console.log(err);
  } else {
    console.log(data.QueueUrl);
  }
});

Currently this code returns: http://localhost:9324/queue/test_queue, but it should return http://192.168.59.103:9324/queue/test_queue. If I replace 'localhost' in the URL with the actual IP address, I can access the queue with that URL successfully, indicating that it was indeed created, but this is a pretty nasty hack. What do I need to change in the code above to correct this issue?
Update: Invalid Endpoint
I returned to this after another issue came up using an ElasticMQ simulation container. This time it was part of a docker-compose file and another container was accessing it by it's docker hostname. SQS will not accept host names with underscores in them. This will mess with most peoples docker-compose files as underscores are common. If you get an error message about invalid endpoints, try renaming your container in the compose file with a hyphen instead of an underscore (i.e. http://sqs_local:9324 will fail, http://sqs-local:9324 will be fine).

A: The problem you're facing it that ElasticMq is exposing the host and port of the container it's running in.  This is a problem I've faced before and fixed it by creating a custom Docker container that lets you set the host and port programmatically.
I've written a blog post on how to fix it, but in essence what you need to do is:

*

*Use my custom image tddmonkey/elasticmq

*Set the NODE_HOST and NODE_PORT environment variables when you create the container.

Ultimately your command line for this is:
$ docker run -e NODE_HOST=`docker-machine ip default` -e NODE_PORT=8000 -p 8000:9324 tddmonkey/elasticmq


text:
Q: Laravel 4 - Validation with Validator in Packages Trying to use the Validator class in my Package class. Now with Facades, it's become a bit tricky to include the classes and use them.
use Illuminate\Validation\Validator
...
protected function valid($request)
{
  return Validator::make($request, ['url'=>'required|url'])->passes();
}

Ends up giving me:

PHP Fatal error:  Call to undefined method
  Illuminate\Validation\Validator::make()

Which is true since I am not using the Facade itself. Looking at the Validator class constructor:
__construct(\Symfony\Component\Translation\TranslatorInterface $translator, array $data, array $rules, array $messages) : void

And here's where I need help :)

A: If you would like to use the validator facade in your package then change your use to either:
use Validator;

Or:
use Illuminate\Support\Facades\Validator;

Or you can inject an instance of the validator factory (which is what actually makes your validator instance) into the class as a dependency. I'm assuming you're setting your package up with a service provider, so something like this.
$this->app->bind('Package', function($app)
{
    return new YourPackage($app['validator']);
});

You should then set the validator property on that class in the constructor.
public function __construct(\Illuminate\Validation\Factory $validator)
{
    $this->validator = $validator;
}

You should now be able to make a new validator instance.
return $this->validator->make($request, ['url' => 'required|url'])->passes();


text:
Q: How to set precision without rounding? I have big integers in database (numeric(24,0)). And I want to convert this number to "human readable" format. I have function:
def from_int(value, precision):
    fprec = "%." + str(precision) + "f"
    return fprec % (Decimal(value) * (Decimal(10)**(-1*precision)))

And it works:
from_int(1000000, 6)
'1.000000'
from_int(1000000, 8)
'0.01000000'
from_int(1000000, 12)
'0.000001000000'
from_int(1000000, 2)
'10000.00'

but for:
from_int(19999999999999999, 2)
'200000000000000.00'

How to set precision without rounding?

A: Formatting with %f converts the number to floating point losing precision. Instead use str:
def from_int(value, precision):
    return str(Decimal(value) * Decimal(10)**(-precision))

A: The problem is in the %f construct that expects a float. So even if you compute everything in decimal, you have a nasty float conversion at the end => so the rounding issue. I think you could just write :
def from_int(value, precision):
    return str((Decimal(value) * (Decimal(10)**(-1*precision))))

I tested it on your values and it gives correct results.

A: If all you want is a string representation, you may be able to get away with something like this:
>>> ('%%.%df' % 2) % 2.445
'2.44'

so in your original code:
def from_int(value, precision):
    return ('%%.%df' % precision) % value

EDIT:
To deal with precision issue, it's indeed simpler to use Decimal type, and the quantize method:
>>> d = decimal.Decimal(19999999999999999)
>>> prec = 2
>>> str(d.quantize(decimal.Decimal(10) ** -prec))
'19999999999999999.00'
>>>

ref: How can I format a decimal to always show 2 decimal places?
EDIT: Using the Decimal type, you can shift decimal places without rounding:
>>> str(d * (decimal.Decimal(10) ** -prec))
'199999999999999.99'


text:
Q: compile and install python2.6.5-devel I download python-2.6.5.tar.bz2 from http://www.python.org/ftp/python/2.6.5/
Now I want to compile and install a python-2.6.5-devel version on my custom Linux OS, how can I do that? Thanks a lot!

A: As soon as you extract the .tar.bz2 file, you will surprisingly see a file inside with an all-caps named README ! It invites you to read it as sincerely as by naming itself! Oh Please, don't let it down. And then on the line 896, you will find it kindly says:
To install the Python binary, library modules, shared library modules
(see below), include files, configuration files, and the manual page,
just type
    make install


text:
Q: Create an app for apple watch with flutter? I started developing a Bluetooth Low energy application on flutter with android studio ( Windows). As i heard flutter allows to create app for android as well as iOS, I'd like to install my app on an apple watch. But my research got me thinking that this feature was not available yet:
https://github.com/flutter/flutter/issues/2056
https://www.reddit.com/r/FlutterDev/comments/9fryg2/does_flutter_work_on_apple_watch/
So, as I need to develop this app for professionnal need and already coded my app on Flutter, I'd want to be sure that it's not possible or if some solutions exist.


text:
Q: Initialization of constexpr member variable using constexpr member function I wanted to initialize a constexpr member variable using a constexpr member function but it didn't compile. It was OK when I moved the function out of the class. Why does it happen? Is there any way to use class member constexpr functions to initialize member constexpr variables?
I'm using Apple LLVM version 8.0.0 (clang-800.0.38).
Thanks for any help.
constexpr static int Add_Ext(int a, int b) { return a + b; }

class Foo
{
public:
    constexpr static int Add_InClass(int a, int b) { return a + b; }

    // This is OK.
    constexpr static int kConstantX = Add_Ext(1, 2);

    // This results in a compile error.
    constexpr static int kConstantY = Add_InClass(1, 2);

};

clang error message:
Constexpr variable 'kConstantY' must be initialized by a constant expression

A: From CWG-1255 and CWG-1626

The Standard should make clear that a constexpr member function cannot be used in a constant expression until its class is complete.

It seems like your code is intentionally unacceptable. However, the standard should make it more clear in that matter.

Is there any way to use class member constexpr functions to initialize member constexpr variables?

w.r.t. those DRs, No. You can move it to outside or to another class instead.

A: Thanks to Danh. I looked into the WG thread you told, and after all, I found I can use member constexpr functions if I make it a class template.
// This works (it doesn't if you make it as a non-template class).
template <typename T>
class TemplateFoo
{
public:
    constexpr static T Add_InClass(T a, T b) { return a + b; }
    constexpr static T kConstantY = Add_InClass(1, 2);

};

// Even such a meaningless template works too.
template <typename T>
class TemplateBar
{
public:
    constexpr static int Add_InClass(int a, int b) { return a + b; }
    constexpr static int kConstantY = Add_InClass(1, 2);

};

// So, this would be a (dirty but) useful workaround
// when you don't want to use the class as a template.
// Any type could be used as the template argument, which has no meaning.
using Bar = TemplateBar<char>;


text:
Q: Quais os passos para criar uma imagem de Docker para Ubuntu 16:04, php 5.6 e apache (com Composer, xdebug, phpunit, npm e REDIS)? Sou iniciante em Docker e estou tentando criar uma imagem com as seguintes especificações:

*

*O OS fonte tem que ser o Ubuntu 16.04 original. Não posso usar imagens já disponíveis no docker hub;

*Tem que ter instalado apache - última versão;

*Tem que ter instalado php e algumas bibliotecas. Tem que ser php 5.5.38 (ideal) ou 5.X último update ou em último caso 5.6.X último update.

*Tem que ter instalado o REDIS.

*O REDIS, APACHE e php devem estar disponíveis assim que o container for criado, ou seja, inicializados automaticamente.

*A raíz do sistema (/var/www/html) deve apontar para um volume /home/username/vhosts/mySite. O host é um MAC OS.

*O sistema tem que ser acessado do browser do host através de mysite-dev1 ou mysite-dev2 ou mysite-devN ...

O objetivo final é criar uma imagem que vai ser compartilhada entre todos os desenvolvedores da empresa.
Este é o Dockerfile que estou usando:
FROM ubuntu:16.04

#1
RUN apt-get update
#2
RUN apt-get install -y apache2
#3
RUN apt-get install -y php5
#4
RUN apt-get install -y redis-server
#5
RUN apt-get install -y php5-redis

COPY /home/username/vhosts/mySite /var/www/html

EXPOSE 80

Em seguida estou encontrando alguns errors:
Operação #3,
php5 não faz parte do package list do ubuntu 16.04. Deste post verifica-se que ele precisa ser atualizado da seguinte maneira:
#6
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install php5.6

Operação #6,
Recebo um erro dizendo que o sudo não é reconhecido como comando (mesmo se tento rodar em modo iterativo no terminal -ti). Fazendo uma pesquisa verifico que o sudo não está habilitado na imagem do Ubuntu16.04.
Se eu tento rodar sem o sudo via terminal (docker run -ti ...), recebo uma mensagem dizendo que add-apt-repository não encontrado
.
Fazendo uma outra pesquisa sobre esse erro descubro que add-apt-repository também não está disponível para imagens de Ubuntu 14.04 em docker. E pelo visto tbm não está disponível para 16.04. A solução proposta é rodar:
#7
apt-get install -y software-properties-common python-software-properties

Rodando essa operação #7 recebo o seguinte erro:

Fazendo uma outra pesquisa, acho esse post que sugere a modificação do apt.conf localizado em /etc/apt/apt.conf.
E esse é o conteúdo do diretório apt de dentro da imagem do ubuntu 16.04
.
Ou seja, não possui apt.conf. Fazendo uma pesquisa em alguns posts encontro que apt.conf precisa ser criado.
A minha conclusão é que eu devo estar fazendo algo muito errado pois o objetivo é somente instalar php5.6 em Ubuntu16.04.
Concluindo, alguém saberia dizer alguma maneira já testada de se criar uma imagem com as características listadas anteriormente sem passar pelas etapas anteriores?
UPDATE:
Parece que outras imagens estão com o mesmo problema quando tentam instalar a versão 5.6 do php.

A: Embora a ideologia do Docker seja de individualizar ao máximo os processos executando cada um deles em containers diferentes, eu vou postar aqui a minha solução com o REDIS dentro de um só container.
Vale notar as observações do @Luiz Carlos. Usar REDIS dentro de um mesmo container rodando php, apache, etc, não é uma boa prática.
O Dockerfile:
Preparado com php 5.6, Apache, PHPUnit, xdebug, REDIS, Composer, NPM.
FROM php:5-apache

## Update apt-get
RUN apt-get update

RUN apt-get install -y figlet

RUN figlet Docker_Build

## UTILITIES
RUN figlet vim
RUN apt-get install -y vim
RUN figlet wget
RUN apt-get install -y wget
RUN figlet CURL
RUN apt-get install -y curl

##===================================================== > ffmpeg stufs

## NOTE: Debian Jessie and later no longer include the ffmpeg, however you have 3 options for installing ffmpeg // https://superuser.com/questions/286675/how-to-install-ffmpeg-on-debian

## list of installed library packages only =>  https://askubuntu.com/questions/434154/how-to-get-the-list-of-installed-library-packages-only
#ldconfig -v                # -v it will show the libraries versions
#ldconfig -v | grep libname # Use grep to find a specific library by name.
#RUN /sbin/ldconfig -p

## Installed
#RUN figlet
#RUN apt-get install -y libav-tools

## https://superuser.com/questions/286675/how-to-install-ffmpeg-on-debian
#root@b6a73f142787:/var/www/html# apt-cache search ffmpeg => List all plugins associated with ffmpeg

#cmus-plugin-ffmpeg - lightweight ncurses audio player (FFmpeg plugin)
RUN figlet cmus
RUN apt-get install -y cmus

#ffmpeg2theora - Theora video encoder using ffmpeg
RUN figlet ffmpeg2theora
RUN apt-get install -y ffmpeg2theora

#ffmpegthumbnailer - fast and lightweight video thumbnailer
RUN figlet ffmpegthumbnailer
RUN apt-get install -y ffmpegthumbnailer

#ffmpegthumbnailer-dbg - debugging informations for ffmpegthumbnailer
RUN figlet ffmpegthumbnailer
RUN apt-get install -y ffmpegthumbnailer-dbg

#libffmpegthumbnailer-dev - development files for ffmpegthumbnailer
RUN figlet libffmpegthumbnailer
RUN apt-get install -y libffmpegthumbnailer-dev

#libffmpegthumbnailer4 - shared library for ffmpegthumbnailer
RUN figlet libffmpegthumbnailer4
RUN apt-get install -y libffmpegthumbnailer4

#ffmpegthumbs - video thumbnail generator using ffmpeg
RUN figlet ffmpegthumbs
RUN apt-get install -y ffmpegthumbs

#libffms2-3 - Cross platform ffmpeg wrapper library
RUN figlet libffms2
RUN apt-get install -y libffms2-3

#gmerlin-encoders-ffmpeg - ffmpeg encoders for Gmerlin
RUN figlet
RUN apt-get install -y gmerlin-encoders-ffmpeg

#libpostproc-dev - FFmpeg derived postprocessing library - development headers
RUN figlet libpostproc
RUN apt-get install -y libpostproc-dev

#libpostproc52 - FFmpeg derived postprocessing library
RUN figlet libpostproc52
RUN apt-get install -y libpostproc52

#moc-ffmpeg-plugin - ncurses based console audio player - ffmpeg plugin
RUN figlet moc-ffmpeg-plugin
RUN apt-get install -y moc-ffmpeg-plugin

#libtaoframework-ffmpeg-cil-dev - Tao CLI binding for FFmpeg - development files
RUN figlet libtaoframework
RUN apt-get install -y libtaoframework-ffmpeg-cil-dev

#libtaoframework-ffmpeg0.4-cil - Tao CLI binding for FFmpeg
RUN figlet libtaoframework
RUN apt-get install -y libtaoframework-ffmpeg0.4-cil

#winff - graphical video and audio batch converter using ffmpeg or avconv
RUN figlet winff
RUN apt-get install -y winff

#libxine2-ffmpeg - MPEG-related plugins for libxine2
RUN figlet libxine2
RUN apt-get install -y libxine2-ffmpeg

## ListInstalledPackages => https://wiki.debian.org/ListInstalledPackages
#RUN dpkg-query -l

## NOTE:
##need setup php variables date and maxupload file and others variables. ==> https://howto.biapy.com/en/debian-gnu-linux/servers/php/manage-php-ini-options-from-command-line-on-debian

##Install FFmpeg on Debian  => https://superuser.com/questions/286675/how-to-install-ffmpeg-on-debian
#https://www.johnvansickle.com/ffmpeg/
## System modules

#RUN apt-get install deb-multimedia-keyring
#RUN apt-get update
#RUN apt-get install -y ffmpeg

## ====================================================================== > End of ffmpeg stufs

## APACHE2  basic installation
RUN figlet APACHE2
RUN apachectl -M
RUN a2enmod rewrite
RUN a2enmod expires
RUN service apache2 restart
RUN apachectl -M

## ====================================================================== > PHP modules

## Note: when installing from php5 for some modules we need to copy from php5/mods-available to local/etc/php/conf.d and create a simbolic link
RUN figlet PHP_MODULES
RUN php -m

RUN apt-get install -y php5-common

RUN apt-get install -y php-calendar
#RUN cp /etc/php5/mods-available/calendar.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/calendar.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/calendar.so

#RUN docker-php-ext-install calendar

RUN docker-php-ext-install bcmath

RUN apt-get install -y php5-mhash
#RUN cp /etc/php5/mods-available/mhash.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mhash.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mhash.so

RUN apt-get install -y php5-intl
RUN cp /etc/php5/mods-available/intl.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/intl.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/intl.so

RUN apt-get install -y php5-mcrypt
RUN cp /etc/php5/mods-available/mcrypt.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mcrypt.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mcrypt.so

RUN apt-get install -y php5-redis
RUN cp /etc/php5/mods-available/redis.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/redis.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/redis.so

RUN apt-get install -y php5-mysql
RUN cp /etc/php5/mods-available/mysql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mysql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mysql.so

RUN cp /etc/php5/mods-available/opcache.ini /usr/local/etc/php/conf.d

RUN apt-get install -y php5-gd
RUN cp /etc/php5/mods-available/gd.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/gd.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/gd.so

RUN apt-get install -y php5-gdcm
RUN cp /etc/php5/mods-available/gdcm.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/gdcm.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/gdcm.so

RUN apt-get install -y php5-vtkgdcm
RUN cp /etc/php5/mods-available/vtkgdcm.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/vtkgdcm.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/vtkgdcm.so

RUN apt-get install -y php5-ldap
RUN cp /etc/php5/mods-available/ldap.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/ldap.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/ldap.so

RUN apt-get install -y php5-xsl
RUN cp /etc/php5/mods-available/xsl.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/xsl.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/xsl.so

RUN apt-get install -y php5-tidy
RUN cp /etc/php5/mods-available/tidy.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/tidy.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/tidy.so

RUN apt-get install -y php5-xmlrpc
RUN cp /etc/php5/mods-available/xmlrpc.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/xmlrpc.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/xmlrpc.so

RUN apt-get install -y php5-pgsql
RUN cp /etc/php5/mods-available/pgsql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pgsql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pgsql.so

RUN cp /etc/php5/mods-available/mysqli.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mysqli.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mysqli.so
RUN cp /etc/php5/mods-available/pdo.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pdo.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pdo.so
RUN cp /etc/php5/mods-available/pdo_mysql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pdo_mysql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pdo_mysql.so
RUN cp /etc/php5/mods-available/pdo_pgsql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pdo_pgsql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pdo_pgsql.so
RUN cp /etc/php5/mods-available/readline.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/readline.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/readline.so

#RUN apt-get install -y php5-snmp
#RUN cp /etc/php5/mods-available/snmp.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/snmp.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/snmp.so

RUN figlet PHP_MODULES
RUN php -m

## PHP extra modules
#RUN apt-get install -y php-horde-date-parser  ##The command '/bin/sh -c apt-get install -y php-horde-date-parser' returned a non-zero code: 100
#RUN apt-get install -y php-horde-date
#RUN apt-get install -y php-horde-timezone
#RUN apt-get install -y php-horde-timeobjects
#RUN apt-get install -y php-timer

#RUN apt-get install -y php-horde-icalendar
#RUN apt-get install -y php-horde-kronolith
#RUN apt-get install -y php-doctrine-dbal
#RUN apt-get install -y phpldapadmin
#RUN apt-get install -y php-horde-ldap
#RUN apt-get install -y php-net-ldap
#RUN apt-get install -y php-net-ldap2
#RUN apt-get install -y php-mdb2-driver-pgsql
#RUN apt-get install -y libnusoap-php
#RUN apt-get install -y php-soap
#RUN apt-get install -y php-fxsl
#RUN apt-get install -y php-horde-text-filter-csstidy
#RUN apt-get install -y php-pclzip
#RUN apt-get install -y libphp-pclzip

#RUN apt-get update

#RUN cp /etc/php5/mods-available/json.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/json.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/json.so

#Manage PHP ini options from command line on Debian => https://howto.biapy.com/en/debian-gnu-linux/servers/php/manage-php-ini-options-from-command-line-on-debian
#RUN apt-get install -y php5-cli

### Note: Compare content

#PHP5
#cd /usr/local/etc/php/conf.d
#cd /etc/php5/mods-available/

#PHP
#cd /usr/local/lib/php/extensions/no-debug-non-zts-20131226
#cd /usr/lib/php5/20131226/

## Note: when module is php5 need to make it available inside php/extensions (create a simbolic link)
#RUN cp /etc/php5/mods-available/MODULE.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/MODULE.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/MODULE.so

## ====================================================================== > End of PHP modules

## ====================================================================== > REDIS
RUN figlet REDIS
RUN apt-get install -y telnet redis-server
RUN apt-get install -y redis-server

## ====================================================================== > NPM
RUN figlet NPM
RUN apt-get install -y npm

## ====================================================================== > COPYING php.ini
RUN figlet COPYING__php.ini
RUN cp /etc/php5/cli/php.ini /usr/local/etc/php/
RUN ls -l /usr/local/etc/

## ====================================================================== > XDEBUG
# XDEBUG EXTENSION FOR PHP | DOCUMENTATION => https://xdebug.org/docs/remote
#
# install xdebug and enable it. This block of code goes through the installion from source and compiling steps found
# on the xdebug website
# https://xdebug.org/docs/install
RUN figlet INSTALLING__XDEBUG
RUN cd /tmp \
    && wget http://xdebug.org/files/xdebug-2.5.4.tgz \
    && tar -xvzf xdebug-2.5.4.tgz \
    && cd xdebug-2.5.4 \
    && phpize \
    && ./configure  \
    && make \
    && cp modules/xdebug.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/

RUN figlet INSIDE_no-debug-non-zts-20131226/
RUN ls -l /usr/local/lib/php/extensions/no-debug-non-zts-20131226/

#https://stackoverflow.com/questions/47596381/how-to-setup-an-variable-env-inside-dockerfile-to-be-overriden-in-a-docker-conta?noredirect=1#comment82150863_47596381
# ADD xdebug configurations
RUN figlet SETTING__XDEBUG__php.ini
RUN { \
        echo '[xdebug]'; \
        echo 'zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20131226/xdebug.so'; \
        echo 'xdebug.remote_enable=1'; \
        echo 'xdebug.remote_port=9000'; \
        echo 'xdebug.remote_autostart=1'; \
        echo 'xdebug.remote_handler=dbgp'; \
        echo 'xdebug.idekey=dockerdebug'; \
        echo 'xdebug.profiler_output_dir="/var/www/html"'; \
        echo 'xdebug.remote_connect_back=0'; \
        echo 'xdebug.remote_host=$REMOTE_HOST'; \
    } >> /usr/local/etc/php/php.ini

RUN figlet XDEGUB__IN__php.ini
RUN cat /usr/local/etc/php/php.ini

#With an unknown IP/multiple developers
#xdebug.remote_host
#Type: string, Default value: localhost
#Selects the host where the debug client is running, you can either use a host name, IP address,
#or 'unix:///path/to/sock' for a Unix domain socket.
#This setting is ignored if xdebug.remote_connect_back is enabled.

#https://stackoverflow.com/questions/4421633/who-is-listening-on-a-given-tcp-port-on-mac-os-x
#lsof -i :9001
#netstat -anv | grep 9001

#https://www.wikihow.com/Find-Your-IP-Address-on-a-Mac
#ifconfig | grep "inet " | grep -v 127.0.0.1
#   inet 10.20.1.210 netmask 0xfffffe00 broadcast 10.20.1.255

#https://apple.stackexchange.com/questions/20547/how-do-i-find-my-ip-address-from-the-command-line
#ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'

#https://serversforhackers.com/c/getting-xdebug-working

#Debug your PHP in Docker with Intellij/PHPStorm and Xdebug
#https://gist.github.com/chadrien/c90927ec2d160ffea9c4

#https://github.com/laradock/laradock/issues/102
#Pointing 9000 to php-fpm with xdebug enabled
#https://forums.docker.com/t/ip-address-for-xdebug/10460/22

## ====================================================================== > COMPOSER

RUN figlet Escape_SUDO
RUN exit

RUN figlet Install__COMPOSER
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \
    && php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" \
    && php composer-setup.php \
    && php -r "unlink('composer-setup.php');" \
    && mv composer.phar /usr/bin/composer

RUN composer

## ====================================================================== > PhpUnit

RUN figlet PhpUnit
RUN curl https://phar.phpunit.de/phpunit-5.6.0.phar -L -o phpunit.phar
RUN chmod +x phpunit.phar
RUN mv phpunit.phar /usr/local/bin/phpunit

RUN figlet COPYING_entrypoint.sh
COPY entrypoint.sh /usr/local/bin/
RUN figlet Permission_entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

ENTRYPOINT [ "entrypoint.sh" ]

# EXPOSE - PORTS
RUN figlet EXPOSE_PORTS
EXPOSE 80
#EXPOSE 6379
EXPOSE 9000
CMD ["apache2-foreground"]

## ====================================================================== > Extra notes

## Clean up Docker
#docker rm $(docker ps -a)
#docker rmi $(docker images)
#docker build -t my_img .

## RUN REDIS
#Open up another terminal
#docker  exec -it  xxxxxCOntainerId bash
#root@bxxxxxCOntainerId:/var/www/html# redis-server

#If another terminal is needed to get acces to the container:
#Open up another terminal
#docker  exec -it  xxxxxCOntainerId bash

## ============================         Export the desired image
## Exit the container and commit in order to save the last state
#docker commit e4a01807684f my_new_name_img

## Check the created image my_new_name_img is there
#docker images
#REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
#my_new_name_img           latest              cc49bbaafd2d        15 seconds ago      771MB

## Tag the image // https://www.youtube.com/watch?v=svs-_9SAYz0
#docker tag my_new_name_img  my_account_docker_hub/my_new_name_img:v001

## Login.
#docker login
#myusername
#mypassword

## Publish the image
#docker push my_account_docker_hub/my_new_name_img:v001

#Remove all images and all containers
#docker rmi -f $(docker images -q)
#docker rm $(docker ps -a -q)

#Using the image just created and stored in the cloud
##docker run -p 80:80  -v path_to_your_project_folder:/var/www/html -e REMOTE_HOST=192.67.10.0 my_account_docker_hub/my_new_name_img:v001 apache2-foreground
## ou
##docker run -p 80:80  -v path_to_your_project_folder:/var/www/html -e REMOTE_HOST=$REMOTE_HOST my_account_docker_hub/my_new_name_img:v001 apache2-foreground

#Note: REMOTE_HOST is your local IP. That value will be used inside xdebug.remote_host.
#Esse valor é importante para permitir uma conexão entre o xdebug e o IDE, principalmente o Intellij ou o PHPstrom.
#No primeiro exemplo a variável $REMOTE_HOST pode ser usada em um script BASH
#REMOTE_HOST=`ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'`
#para carregar o container automaticamente sem necessidade de passar o IP

# Documentation
#    https://docs.docker.com/engine/reference/commandline/pull/#proxy-configuration
#    https://docs.docker.com/docker-hub/orgs/
#    https://docs.docker.com/engine/reference/commandline/commit/
#    https://docs.docker.com/get-started/part2/#run-the-app
#    http://jasani.org/2014/11/19/docker-now-supports-adding-host-mappings/
#    https://docs.docker.com/engine/reference/commandline/push/#parent-command
#    https://docs.docker.com/docker-cloud/orgs/#convert-a-user-to-an-organization
#    http://www.tldp.org/LDP/Bash-Beginners-Guide/html/Bash-Beginners-Guide.html#chap_07
#    https://medium.com/ihme-tech/using-xdebug-with-intellij-inside-a-docker-container-dc8cbd844dc5
#    https://www.npmjs.com/package/redis-commander
#    https://www.youtube.com/watch?v=kQ3H_jhyW2w
#    https://docs.docker.com/samples/library/redis/
#    https://docs.docker.com/engine/reference/run/#network-settings
#    https://docs.docker.com/engine/reference/run/
#    http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_04_02.html
#    https://stackoverflow.com/questions/6207573/how-to-append-output-to-the-end-of-text-file-in-shell-script-bash
#    http://www.linuxfromscratch.org/lfs/view/6.1/chapter07/hosts.html
#    http://www.linfo.org/cat.html
#    https://redislabs.com/blog/so-youre-looking-for-the-redis-gui/

#http://tarunlalwani.com/post/debugging-php-xdebug-docker/
#https://medium.com/ihme-tech/using-xdebug-with-intellij-inside-a-docker-container-dc8cbd844dc5
#https://stackoverflow.com/questions/47357783/xdebug-with-intellij-and-docker-is-not-working-how-to-solve-it?noredirect=1#comment81686964_47357783
#https://xdebug.org/docs/remote
#https://stackoverflow.com/questions/46263043/how-to-setup-docker-phpstorm-xdebug-on-ubuntu-16-04/46265103#46265103
#http://www.mysolutions.it/phpstorm-server-xdebug-configuration/

# How could I ping my docker container from my host // https://stackoverflow.com/questions/39216830/how-could-i-ping-my-docker-container-from-my-host
# docker inspect 64ad351e115f give me "IPAddress": "172.17.0.2",
# How to get a Docker container's IP address from the host? docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' 64ad351e115f 172.17.0.2

Esse é o entrypoint.sh que vai injetar o Ip dinamicamente no php.ini passando para o xdebug.remote_host :
#!/bin/bash
set -e

# Check if our environment variable has been passed.
if [ -z "${REMOTE_HOST}" ]
then
  echo "REMOTE_HOST has not been set."
  exit 1
else
  sed -i.bak "s/\$REMOTE_HOST/${REMOTE_HOST}/g" /usr/local/etc/php/php.ini
fi

exec "$@"


text:
Q: Flash Builder 4.5 Standard License in 4.7 I have Flash Buider 4.5 Standard licence, and I would like to know if I can use my serial number with the newest version of FB (4.7)?

A: Per Adobe Flash Builder product page:
How do I get Flash Builder 4.7 if I already have Flash Builder 4.5?

Existing Flash Builder 4.5 customers will not be prompted to upgrade
  automatically. Flash Builder 4.5 customers can download the trial
  version of Flash Builder 4.7 and request a Flash Builder 4.7 serial key.
Flash Builder 4.7 is a complimentary update from version 4.5.

Historically premium versions of Flash Builder and AIR for iOS could be installed as a complimentary update.  With Creative Suite, awkwardly uninstalling the old version then installing the new product as a trial to enable the Adobe Application Manager to register the license.  As a standalone product, I believe Flash Builder 4.6 accepted a Flash Builder 4.5 serial key.
With Flash Builder 4.7, you need to request a serial key.


text:
Q: java android send Serializable data object to USB I have a serializable data object that I want to send as packets thru USB.  It will have to be sent in 64 byte packets.  In C I would set a pointer to my object and send byte by byte for the sizeof the object.  I can't find a "sizeof" capability in java?  I have a 64 byte buffer that I can already send a packet of data with.  How can I load portions of fdata into my usb buffer?
FileDataFormat fdata;

public class FileDataFormat implements Serializable {

    public static final Integer numofswitches = 8;  //use 1-7
    // set for 10 channels for future
    byte switchesEnabled = 0; //switchesEnabled

    String[][] switch_name = new String[numofswitches][20];  //auxLabels's
    int[] configurableMaxCurrentTenths = new int[numofswitches];                    //configurableMaxCurrentTenths
    byte softStartByte = 0;         //softStartByte
    byte delayedButtonPressEnable = 0;      //delayedButtonPressEnable
    byte[] delayedButtonPressTimeDelayTenths = new byte[numofswitches];
    byte currentReadingSelectedChannels = 0;
    byte threshholdEnabled = 0; //threshholdEnabled
    byte[] triggerChannel = new byte[numofswitches]; //triggerChannel
    boolean[] expressionType = new boolean[numofswitches]; //expression type > or <
    float[] hysteresis = new float[numofswitches];
    float[] threshhold = new float[numofswitches];

    public FileDataFormat() {

    }
}


text:
Q: Return custom type in Promise I had some JSON array like below and I got these JSON from service.
[{
    "id": 3,
    "name": "Arun"
}, {
    "id": 5,
    "name": "Barun"
}, {
    "id": 1,
    "name": "Joy"
}, {
    "id": 8,
    "name": "Suman"
}]

Now, I made a like below
class Person{
  id:number
  name:string

    deserialize(input) {
      this.id = input.id;
      this.name = input.name
      return this;
   }
}

Now, I had a service class from where I am getting JSON(Array/dictionary) with Promise and I send this Promise to my parsing function. My Parsing function is below
 private  parse(response:Promise<{}>):Promise<{}>{

    return new Promise((success,failure) =>{
        response.then((result) => {
            if (result instanceof Array || Array.isArray(result)){
                let rs1 = result.map((val) => new Person().deserialize(val))
                success(rs1);
            }else{
                success(new Person().deserialize(result))
            }
        },(err) => {
            failure(err)
        });
    });
}

Now, I have two function
  expectingObjectOfPerson(){
    //get the promise from service class
    let result = servicePromise//Promise from service class with JSON

    //now call parse function
    this.parse(result)
    .then((response) => {

        //I knew that response is an object of Person in run time.
        let person = response as Person

        //log name of this person
        console.log(person.name) //no run time exception

        //log name of this person
        console.log(person.nam) //Error thrown by compiler

        //now if I do this
        console.log(response.name) //no run time exception

        //if this
        console.log(response.nam) //run time exception, also no error thrown from compiler

        /* Main problem is on here.
        * Is there any way that response could automatically inferred to Person */
    }, (error) => {
        Console.log(error);
    })

}

expectingArrayOfPerson(){
     //get the promise from service class
     let result = servicePromise//Promise from service class with JSON

     //now call parse function
     this.parse(result)
     .then((response) => {

         //I knew that response is an object of Person in run time.
         let persons = response as Person[]

         //log name of this person
         console.log(persons.map((val) => val.name)) //no run time exception

         //log name of this person
         console.log(persons.map((val) => val.name)) //Error thrown by compiler

         //now if I do this
         console.log(response.map((val) => val.name)) //no run time exception

         //if this
         console.log(persons.map((val) => val.name)) //run time exception , also no error thrown from compiler

         /* Main problem is on here.
         * Is there any way that response could automatically inferred to array of Person */
     }, (error) => {
         Console.log(error);
     })
}

Is there any way that response could automatically inferred to Person object or array of Person depends on response ?
I am new in Angular, any help will be appreciated.
I am using latest version of Typescript.

A: First, let's go over your service : you're creating a Promise, to handle another promise. That's repeating yourself.
Furthermore, you should use Observables, which are upgraded promises.
Finally, you're creating a new Person object everytime. Consider using a static method to deserialize.
This gives you :
export function parse(response: Promise<{}>): Observable<{}> {
  // Rx 6 : return fromPromise(response)
  return Observable.fromPromise(response)
    .map(result => {
      if (result instanceof Array || Array.isArray(result)) {
        return result.map((val) => Person.deserialize(val))
      } else {
        return Person.deserialize(result);
      }
    })
}

export class Person {
  id: number;
  name: string;

  public static deserialize(input: any): Person {
    const person = new Person();
    person.id = input.id;
    person.name = input.name;
    return person;
  }
}

Now you can use your two functions like this :
expectingObjectOfPerson(){
  this.parse(servicePromise) // Whatever it is
    .subscribe(personInstance => {
      console.log(personInstance);
      console.log(personInstance instanceof Person);
    }, error => console.log(error));
}

expectingArrayOfPerson(){
  this.parse(servicePromise) // Whatever it is
  .subscribe(persons => {
    for (const personInstance of persons) {
      console.log(personInstance);
      console.log(personInstance instanceof Person);
    }
  }, error => console.log(error));
}


text:
Q: C++ auto cannot deduce type with default template parameter I notice that if I write:
template<typename T = int> void Test(T t) {};

then the following code does not compile:
auto x = Test;

However, this code does, and deduces x to be void (*x)(int t):
auto x = Test<int>;

I'm just wondering why it does not just assume the type parameter is int in the first case and treat it the same as the second one?

A: If you have a function with a default parameter, for example:
int f(int n=0);

Calling this function with this parameter defaulted is done by doing this:
int g=f();

and not this:
int g=f;

Same principle applies to template instantiations:
auto x = Test<>;


text:
Q: Webkit border colour text colour bug I have some HTML emulating the Mac OS X dock app context menu, and have run into a problem in both Chrome and Safari.
Have a look at this example here (http://jsfiddle.net/HenXL/1/) in both Chrome and then Firefox. In Chrome, for some reason the text colour of the siblings elements to the hr element become the same colour as the hr elements border colour.

I am not sure why this is happening, I may have made an obvious mistake (it is late) but I cannot see a problem with the code.
Can anyone tell me why this is happening, or shed any light on the situation?

A: This seems to be a bug with the current stable version of Chrome (13), at least on Mac. Strangely, if you select the text, it changes color to become white as it should.
It seems to be fixed in 14 onward.
This is being caused by border: transparent; in your .content hr rule. Here it is, removed: http://jsfiddle.net/AJfcQ/
Could be related to this issue: http://crbug.com/68371


text:
Q: How to upgrade the hibernate-validator 4.3.0.Final to the Glassfish 3.1.2? At the moment, the Hibernate Validator has released the latest version as 4.3.0.Final here. I have tried to upgrade it to my Glassfish 3.1.2 as the following step: -
1. Remove the GLASSFISH/glassfish/modules/bean-validator.jar
2. Copying the hibernate-validator-4.3.0.Final.jar to GLASSFISH/glassfish/modules
3. Restart the Glassfish
4. The Glassfish cannot start. It seems hang.

After searching via the Google, I've found that the file named "bean-validator.jar" was created by the Glassfish team as an OSGi version. Sadly, I cannot find how to create it. Could you please help to advise further? Thank you very much for your help in advance. I'm looking forward to hearing from you soon.

A: A (slightly outdated) description of how to build Glassfish's bean-validator.jar can be found here.
What's needed in general is an OSGi bundle which includes Hibernate Validator itself and the Bean Validation API. With this bundle you should be able to replace the original bean-validator.jar. Additionally you need the JBoss Logging bundle, which is used since release 4.3 by Hibernate Validator as logging API and already comes in form of an OSGi bundle.
If you're building a web application, you could also package HV 4.3 within your WAR and turn off class loader delegation by providing the file WEB-INF/glassfish-web.xml with the following contents:
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <class-loader delegate="false" />
</glassfish-web-app>

That way the HV classes will be loaded from your application instead of from the module provided by Glassfish.
You might also be interested in the issue GLASSFISH-15648 which aims to provide a dedicated Glassfish update package for HV.

A: As my case was ear, rather than war, based on suggestion of Gunnar, I did a patched version of the module, that is deployable to Glassfish (My version is 3.1.1 OSE).
Someone might find it still useful, see my blog for my solution (including step-by-step approach): http://peter-butkovic.blogspot.de/2012/11/glassfish-311-oss-with-hibernate.html


text:
Q: AT&T DSL 2701HG-B Modem, port forwarding to RealVNC Our old cable modem could easily be set up to forward an "incoming port request" to the RealVNC software.  Allowing us to log into our home computer from any location.
We don't see any such configuration possiblity with our new AT&T DSL 2Wire 2701HG-B modem.
(And it appears to have 2 entirely different 'set up screens'. Why?)
Where is the screen that allows "forward incoming request for a certain port", to a certain computer, and direct it towards RealVNC"?

A: Head over to your Router setup page, Click on Firewall section:

Click the Firewall Settings button.

Use the Select a computer box to choose a computer to forward ports to. Click the Add a new user-defined application link. RealVNC requires you to forward the 5900 ports. Enter port range as 5900 in From & To Boxes, for TCP & UDP protocols in Edit Application menu and then click Add Definition.

Click the Back button. Select the applications you just created in the Applications list, then click the Add button to move them to the Hosted Applications box.
When you are finished, click the Done button at the bottom of your screen.
Save the page, port forwarding is active now
Screens via PortForward.com


text:
Q: How to appear an emoji in TinyMCE version 5.06? I am trying to insert an emoji by using TinyMCE 5.06 version, but there is an error about this inserting. An emoji does not appear when I use Html.Raw() in Asp.Net MVC. It looks like this " ????". How can I fix this ?
  //tinymce plugin and toolbar options
        $scope.tinymceOptions = {
            selector: '#post',
            plugins: [
               "advlist autolink autoresize link image fullscreen  lists charmap paste print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking wordcount  ",
                "table contextmenu directionality emoticons paste template spellchecker searchreplace help imagetools media "
            ],
            mobile: {
                theme: "mobile",
                plugins: [ 'autosave', 'lists', 'autolink' ],
                toolbar: [ 'undo', 'bold', 'italic', 'styleselect' ]
            },
            toolbar: "insertfile undo redo | styleselect | bold italic underline left aligncenter alignright alignjustify | forecolor  backcolor | fontselect fontsizeselect| bullist numlist outdent indent | link image media  preview |  emoticons | searchreplace  help ",
            toolbar_items_size: 'small',
            file_picker_types: 'file image media',
            image_title: true,
            automatic_uploads: true,
            file_picker_types: 'image',
            relative_urls: false,
            file_picker_callback: function (cb, value, meta) {
                var input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', 'image/*');
                input.onchange = function () {
                    var file = this.files[0];

                    var reader = new FileReader();
                    reader.onload = function () {

                        var id = 'blobid' + (new Date()).getTime();
                        var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                        var base64 = reader.result.split(',')[1];
                        var blobInfo = blobCache.create(id, file, base64);
                        blobCache.add(blobInfo);
                        cb(blobInfo.blobUri(), { title: file.name });
                    };
                    reader.readAsDataURL(file);
                };
                input.click();
            },

            media_url_resolver: function (data, resolve/*, reject*/) {
                if (data.url.indexOf('YOUR_SPECIAL_VIDEO_URL') !== -1) {
                    var embedHtml = '<iframe src="' + data.url +
                    '" width="400" height="400" ></iframe>';
                    resolve({html: embedHtml});
                } else {
                    resolve({html: ''});
                }
            },
            width: "98%",
        };

I expect the output to be  or  as examples, but the actual output is ?? .

A: Had this problem.
entity_encoding: "numeric"

This will send the emoticon to your DB as HTML Dec code, then when you display them as HTML dec code, your browser will convert them to emoticons.

A: Check which character set you're using to process the HTML string. This can happen when you accidentally convert a string from a complex character set (required for emoji) such as Unicode or UTF-8 into something simpler like ASCII.


text:
Q: What type of position embedding is used in Distilbert? In Distilbert config files, there is a option that is "sinusoidal_pos_embds", and is set to be "true". Is that means distilbert utilize the sinusoidal position embeddings in practice?

A: When it is set to True, it indeed means that it uses the sinusoidal embedding.
However, when you look at the DistilBERT models that are listed in the documentation, most of them (distilbert-base-uncased, distilbert-base-uncased-distilled-squad, distilbert-base-cased, distilbert-base-cased-distilled-squad, distilbert-base-multilingual-cased, distilbert-base-uncased-finetuned-sst-2-english) do not use sinusoidal embeddings and use learned embeddings.
The only one from the standard DistilBERT models with sinusoidal embeddings is distilbert-base-german-cased.


text:
Q: RabbitMQ message lost I use Python api to insert message into the RabbitMQ,and then use go api to get message from the RabbitMQ.
Key 1: RabbitMQ ACK is set false because of performance.
I insert into RabbitMQ about over 100,000,000 message by python api,but when I use go api to  get
message,I find the insert number of message isn't equal to the get number.The insert action and the
get action are concurrent.
Key 2:Lost message rate isn't over 1,000,000 percent 1.
Insert action has log,python api shows that all inserted message is successful.
Get action has log,go api shows that all get message is successful.
But the number isn't equal.
Question1:I don't know how to find the place where the message lost.Could anyone give me a suggestion how to find where the message lost?
Question2:Is there any strategy to insure the message not lose?

A: In order for you to test that all of your messages are published you may do it this way:

*

*Stop consumer.

*Enable acknowledgements in publisher. In python you can do it by adding extra line to your code: channel.confirm_delivery(). This will basically return a boolean if message was published. Optionally you may want to use mandatory flag in basic_publish.

*Send as many messages as you want.

*Make sure that all of the basic_publish() methods returnes True.

*Count number of messages in Rabbit.

*Enable Ack in consumer by doing no_ack = False

*Consume all the messages.

This will give you an idea where your messages are getting lost.


text:
Q: logarithm express $q^{q+2}$ in term of $p$. Given $p=3^q$, express $q^{q+2}$  in terms of $p$.
I only performed until here, but the answer given is $81p^2$. I've no idea how to continue then.
${log_3p}^{log_3p+2}={log_3p^{log_3p}}{{log_3p}^2}$

A: Well $q = \log_3 p$ so ... what more do you need to be able to do this?


text:
Q: "No Such File or Directory" in Python I'm trying to create an encryption program that is also capable of using a username and password to be accessed, alongside the password being able to be changed, however, I am getting the following error when trying to read the password from a file.
Traceback (most recent call last):
  File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 28, in <module>
    password()
  File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 9, in password
    var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Matthew\\AppData\\Local\\Programs\\Python\\Python37-32\\password.txt'

Password is saved in the Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt directory.
Below is the code.
import os
import time
def password():
    while True:
        username = input ("Enter Username: ")
        password = input ("Enter Password: ")

        var1 = "admin"
        var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
        if username == var1 and password == var2:
            time.sleep(1)
            print ("Login successful!")
            answer = input("Do you wish to change your password (Y/N): ")
            if input == "Y" or "y":
                var2 = input("Enter new password: ")
            elif input == "N" or "n":
                break
            logged()
            break

        else:
            print ("Password did not match!")

def logged():
    time.sleep(1)
    print ("Welcome to the encryption program.")

password()

def main():
    result = 'Your message is: '
    message = ''
    choice = 'none'

    while choice != '-1':
        choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")

        if choice == '1':
            message = input("\nEnter the message to encrypt: ")

            for i in range(0, len(message)):
                result = result + chr(ord(message[i]) - 2)

                print (result + '\n\n')
                result = ''

        elif choice == '2':
            message = input("\nEnter the message to decrypt: ")

            for i in range(0, len(message)):
                result = result + chr(ord(message[i]) + 2)

                print (result + '\n\n')
                result = ''

        elif choice != '-1':
            print ("You have entered an invalid choice. Please try again.\n\n")

        elif choice == '-1':
            exit()

main()

Any help is appreciated, thanks!

A: Provide the complete path:
var2 = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/password.txt","r")

Edit:
As you said in the comment that it worked but the password was marked as incorrect, so I have fixed issues with your code.
You cannot read data directly by opening a file. You will have to use the command read to get the data:
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()

Your second code problem is setting new password. The code you made:
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
    var2 = input("Enter new password: ")
elif input == "N" or "n":
    break

Don't use input to see the value, use the variable in which you stored the input data. Also lower the string to make it easy:
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
    var2 = input("Enter new password: ")
elif answer.lower() == "n":
    break

The full code can be like:
import os
import time
def password():
    while True:
        username = input ("Enter Username: ")
        password = input ("Enter Password: ")

        var1 = "admin"
        file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
        var2 = file.read()
        file.close()
        if username == var1 and password == var2:
            time.sleep(1)
            print ("Login successful!")
            answer = input("Do you wish to change your password (Y/N): ")
            if answer.lower() == "y":
                var2 = input("Enter new password: ")
            elif answer.lower() == "n":
                break
            logged()
            break

        else:
            print ("Incorrect Information!")

def logged():
    time.sleep(1)
    print ("Welcome to the Encryption program.")

password()

def main():
    result = 'Your message is: '
    message = ''
    choice = 'none'

    while choice != '-1':
        choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")

        if choice == '1':
            message = input("\nEnter the message to encrypt: ")

            for i in range(0, len(message)):
                result = result + chr(ord(message[i]) - 2)

                print (result + '\n\n')
                result = ''

        elif choice == '2':
            message = input("\nEnter the message to decrypt: ")

            for i in range(0, len(message)):
                result = result + chr(ord(message[i]) + 2)

                print (result + '\n\n')
                result = ''

        elif choice != '-1':
            print ("You have entered an invalid choice. Please try again.\n\n")

        elif choice == '-1':
            exit()

main()


text:
Q: How to reverse axis values when using plotly? Here is the program I used:
library(plotly)

mydata = read.csv("data_to_plot.txt")
df = as.data.frame(mydata)

p <- df %>%
  group_by(X) %>%
  plot_ly(x = ~Y, y = ~X, z = ~Z, type = "scatter3d", mode = "lines")
p

and below is an excerpt of "mydata":

df[1:12,]
     X         Y            Z
  1  1 0.2818017 0.0005993884
  2  1 0.2832173 0.0007896421
  3  1 0.2846330 0.0010293849
  4  1 0.2860487 0.0013282462
  5  1 0.2874643 0.0016969544

I would like to have the X values reversed on the X-axis, but can't find how to modify my program. Details of the plotly syntax are quite obscure to me. Could someone afford some help?
Many thanks.
Data plotted:

A: At the moment reversed axis range in 3d is not supported in plotly. For this reason autorange = "reversed" doesn't work.

A: If you want to reverse one of the axes of 3D plot:
fig.update_layout(
    scene={
        'xaxis': {'autorange': 'reversed'}, # reverse automatically
        'yaxis': {'range': (100, 0)},       # manually set certain range in reverse order
    }
)

See details: scene.YAxis.autorange.
PS: Some guys wrote that it doesn't work for 3D plot in previous versions of Plotly. I just checked in the latest version (3D Surface), it works fine.

A: You are probably looking for
layout(xaxis = list(autorange = "reversed").

A: In case someone reaches here looking for reversing axis for some subplots in python.
fig.update_yaxes(autorange="reversed", row, col)

A: You can solve this by continuing to rotate the plot using turntable rotation. Originally, the axes are oriented with the largest values facing you. As you rotate, one by one they will become oriented the other way, then go back to where they started. This may be why autorange = "reversed" doesn't work in 3d plots.

A: You can rotate the plot by setting x=-x, and/or y=-y. You can then remove the minus sign in the plot by using tickvals = list(-x_ticks) and ticktext = list(x_ticks) in layout. Haven't found a way to remove the minus signal from the hovertext. But I guess I can't have it all =)

A: When using plotly, you can modify the yaxis properties by passing a dictionary. For reversing the y axis use fig.update_layout as shown:
import plotly.graph_objects as go
import numpy as np

N = 1000
t = np.linspace(0, 10, 100)
y = np.sin(t)

fig = go.Figure(data=go.Scatter(x=t, y=y, mode='markers'))

fig.update_layout(
    yaxis = dict(autorange="reversed")
)

fig.show()

You can see the Y-axis is in reverse order.


text:
Q: How can I send a silent notifications using app center push service I am trying to send a silent notification (I mean a notification that will not be shown in the tray) using
this API:
but when I do not set the body key I get this Error:
 {
  "error": {
    "code": 400,
    "message": "body parameter is invalid or empty.: 'Body' cannot be null."
  }
}

so my question is if there is a way to send a silent notification in android (in ios I know there is the content-available flag)
Tnx in advance!

A: Unfortunately silent notification is not yet supported on App Center for Android.

A: I've asked AppCenter support via their live chat and they replied me the following

You can by setting "content-available"  key in the custom data. here is a sample payload you need to set in body:

"notification_content" : {
   "name" : "name of Push",
   "custom_data" : {"content-available" : "1"}
},

A: Indeed,

"notification_content" : {
    "name" : "name of Push",
    "custom_data" : {"content-available" : "1"}
  },

is for silent push notifications in ios

A: Try this for Android and iOS
{
  "notification_target": {
    "type": "devices_target",
    "devices": [
      "43533adc-4133-4121-ad4e-1eb4885b4b98"
    ]
  },
  "notification_content": {
    "name": "edd3-43ef-91f5-276c28a86517",
    "title": "",
    "body": "",
    "custom_data": {
      "content-available": "1",
      "id": "your data"
    }
  }
}


text:
Q: Opposit letters with sed -r? I have a text with random alphabetic characters and I want to change every character to his opposit one.
ex. i have a character z, i change it in to a, b to y etc.
I can't really find a better way to do this unless i do
sed -r -e 's/a/z/' -e 's/b/y/' ... 's/z/a/'

Is there a way to do this in a more simple way?
I just want to use the -r option in sed.
Using the y command maybe?

A: tr is easier,
e.g. for lowercase chars
$ z_a=$(echo {z..a} | tr -d ' '); echo adfa alfja | tr a-z $z_a
zwuz zouqz

the detour to create z-a is required since tr can't handle "reverse collating sequence order".

A: I know this isn't a sed solution, but this seems a simple, straight forward use of perl:
cat input_file | perl -ple 's/(.)/chr(25-ord($1)+ord("a")*2)/eg'

A: sed comes, one way is like this:
sed -r 'y/'"$(echo {a..z})"'/'"$(echo {z..a})"'/' file


text:
Q: How to access an instance variable from a different controller whose page on which I am rendering a partial? I have a User controller, and a Notifications controller. User has_many Notifications through a number of other models. Is there a good way to define @user in my notifications#destroy action so that I can reference it in my javascript?
On my User show page, I have something like this.
users/show.html.erb

    "You have <%= @user.notifications.count %> notifications"

  <%= render @user.notifications %>

notifications/_notification.html.erb
  <div id="notification_<%= @notification.id %>">

Congrats, you have earned XXX badge!

<%= link_to 'X', notification, method: :delete, remote: true %>

users_controller.rb
def show
  @user = User.find(params[:id])
end

notifications_controller.rb
def destroy
  @notification= Notification.find(params[:id])
  @notification.destroy
  respond_to |format|
    format.html { redirect_to :back }
    format.js
  end
end

notifications/destroy.js.erb
$("#notification_<%= @notification.id %>").remove();
$("#user_notifications_count").html("You have <%= @user.notifications.count %> notifications");

In the javascript, the first line with .remove(); works fine. However, the second line doesn't work because I haven't defined @user in my controller destroy action. My user model has_many notifications through multiple other models. Therefore, each notification does NOT have a specific user_id. Is there a way to get the user_id params from the user#show page that I am rendered on?
Sorry if I am not being clear. Please let me know and I will supplement with additional explanation/code.  Thanks!

EDIT: ADDING MODEL CODE
user.rb
attr_accessible :name
has_many :articles
has_many :comments
has_many :badges

def notifications(reload=false)
  @notifications = nil if reload
  @notifications ||= Notification.where("article_id IN (?) OR comment_id IN (?) OR badge_id IN (?)", article_ids, comment_ids, badge_ids)
end

article.rb
attr_accessible :content, :user_id
belongs_to :user
has_many :notifications

comment.rb
attr_accessible :content, :user_id
belongs_to :user
has_many :notifications

badge.rb
attr_accessible :name, :user_id
belongs_to :user
has_many :notifications

notification.rb
attr_accessible :article_id, :comment_id, badge_id
belongs_to :article
belongs_to :comment
belongs_to :badge

A: Setting up a virtual attribute in your Notification model would work:
# app/models/notification.rb
class Notification < ActiveRecord::Base
    belongs_to :article, :comment, :badge

    def user
        if article_id.nil? && comment_id.nil?
            badge.user
        elsif comment_id.nil? && badge_id.nil?
            article.user
        elsif badge_id.nil? && article_id.nil?
            comment.user
        end
    end
end

Then, you could look up the parent in the destroy action of the notifications controller:
# app/controllers/notifications_controller.rb
def destroy
    @notification= Notification.find(params[:id])
    @user = @notification.user
    ...
end

You'll subsequently be able to access the @user instance variable just as you've indicated in your destroy.js.erb snippet above.


text:
Q: React native Как сделать выбор файлов по очереди? Использую react-native-document-picker
Есть кнопка 'add file'. Каждый раз, когда мы нажимаем на кнопку, добавляется новый элемент. В элементе мы выбираем файл, который хотим загрузить.(отображаются две кнопки 'выбрать файл' и 'удалить')
При нажатии на выбор файла открывается document-picker. Мы выбираем файл и после элемент должен обновится и в середине должно появиться название выбранного файла (кнопка 'выбрать файл' и 'удалить' не пропадает). При нажатии на кнопку 'Удалить' файл сбрасывается и можно выбрать его снова.
При нажатии на кнопку 'add file' появляется новый элемент с тем же функционалом.
Проблема, с которой я столкнулся:
Каждый раз, когда я выбираю файл, его имя отображается только при добавлении следующего элемента.(не обновляется выбранный файл)
Каждый раз, когда добавляется новый элемент, имя файла дублируется, а не отображается пустой элемент. (название файла выбранного в первом элементе отображается в каждом новом элементе).
При добавлении нового файла вместо получения элемента с новым именем добавляемого файла строки с именем файла дублируются одна под другой (правда, имена файлов у них разные, как и должно быть)
Вопрос: Как реализовать добавление файла в разные элементы?
Что я делаю :
Есть кнопка, которая добавляет новый элемент и позволяет пользователю выбрать файл:
<View>
      {views.map((item,index) => {
        return (
          <View>
            {item}
          </View>
        );
      })}
      <TouchableOpacity
      style={MapStyle.UploadButton}
      onPress={addItems}
      >
      <Text style={{textAlign: 'center'}}>Add file up to 5 MB</Text>
      </TouchableOpacity>
      </View>

const addItems = () => {
    const arr = [...views];
    arr.push(<FilesView />);

    setViews(arr);
  };

  const deleteItems = () => {
    const arr = [...views];
    arr.push();

    setViews(arr);
  };

Реализация кнопки выбора файла:
const FilesView = () => {
    return (
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity
        style={MapStyle.SelectFileButton}
        activeOpacity={0.5}
        onPress={selectFile}
        >
        <Text style={{textAlign: 'center',color:'blue'}}>Select File</Text>
      </TouchableOpacity>
      <View>
      {/*Showing the data of selected Single file*/}
      {multipleFile.map((file, index) => (
            <View style={MapStyle.inputText2}>
            <Text
              key={index.toString()}
              style={MapStyle.textStyle}
              numberOfLines={1}
              ellipsizeMode={'middle'}>
              {file?.name}
            </Text>
        </View>
      ))}
      </View>
        <TouchableOpacity style={MapStyle.DeleteButtons} onPress={() => { deleteItems(); deleteFile();}}>
                    <Text style={{textAlign: 'center'}}>Delete</Text>
                    </TouchableOpacity>
      </View>
    );
  };

Выбор файла и запись его в массив:
const selectFile = async () => {
    try {
      const res = await DocumentPicker.pickSingle({
        type: [DocumentPicker.types.allFiles],
      });
      console.log('res : ' + JSON.stringify(res));
      const newFile = [...multipleFile];
      newFile.push(res);
      setMultipleFile(newFile);
    } catch (err) {
      setMultipleFile(null);
      if (DocumentPicker.isCancel(err)) {
        alert('Canceled');
      } else {
        alert('Unknown Error: ' + JSON.stringify(err));
        throw err;
      }
    }
  };


text:
Q: A measure Theory problem on lebesgue integral Let $\{f_n\}$ be a sequence of non-negative measurable functions such that $f_n$ converges to $f$ and $ f_n \le f $ for each $n$, prove that $\lim_{n\to \infty} $ $\int f_n = \int f$
any hints will be appreciated, I thought I could use MCT but didn't know how to apply iy

A: The statement of monotone convergence theorem is: "If $\{f_n\}$ is a sequence of non-negative measurable functions such that $f_n \leq f_{n+1}$ for all $n$ and $f = \lim_{n \to \infty} f_n$, then $\int f = \lim_{n \to \infty} f$."
Can you form an increasing sequence of functions from $\{f_n\}$ which increases pointwise to $f$? (Hint: use sup).


text:
Q: Iframe with a submit form in a Fancybox not posting data I'm trying to submit a form inside a fancybox. It is a simple contact us form with name and email and a submit button.
I set the fancybox to iframe and it loads "download.php". This is what "download.php" has:
    <form action="sendmail.php" type="post">
                <fieldset style="width: 300px;">
            <legend>Please fill out completely:</legend>
                * required field

                Name:

                <input type="text" id="txtName" style="width: 200px;" name="txtName">*

                Email:

                <input type="text" id="txtEmail" style="width: 200px;" name="txtEmail">*

                <button id="btnSubmit">Submit</button>
                <input type="text" id="txtH" style="display: none;" name="txtH">
            </fieldset>
    </form>

When it submits it works properly other than "txtName" and "txtEmail" being blank. I can't seem to get the values to send. It sends an email after submitting properly otherwise which is why I need to use PHP and not jQuery. Thanks for any help!
Here is the sendmail.php code.
ini_set('SMTP','mail.######.com' );
ini_set('smtp_port', '25');
ini_set('sendmail_from', 'info@#####.com');

  $name = $_POST["txtName"];
  $email = $_POST["txtEmail"];
  $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

  $msgBody =  'The following information was submitted via the download form.' . PHP_EOL . PHP_EOL .
  'Name: ' . $name . PHP_EOL .
  'Email: ' . $email . PHP_EOL .
  'URL: ' . $url . PHP_EOL;

  $to = "me@me.com";
  $subject = "A White Paper was downloaded";

  $headers = "From: info@me.com" . "\r\n";

  if (mail($to, $subject, $msgBody, $headers)) {
    header('Location: download-success.php');
  }
  else {
    header('Location: same.php');
  }

}

A: You have a mistake here,
<form action="sendmail.php" type="post">

it should be method="post" not type="post"
<form action="sendmail.php" method="post">

and also in your submit button, add type="submit"
<button id="btnSubmit" type="submit">Submit</button>

and here you don't need to set display:none; you can use type="hidden" if you want to hide the input
<input type="hidden" id="txtH" name="txtH">

and In your PHP, use isset
if (isset($_POST['txtName']) {
    $name = $_POST["txtName"];
    //and rest of the code goes here
}

And always
Add error reporting to the top of PHP file which will help find errors.
error_reporting(E_ALL); //Error reporting enable
ini_set('display_errors',1);


text:
Q: Derived fields in Orbeon Is there some way to derive field values from other fields in Orbeon CE with the help of perhaps some xml script?
I would like it to take some fields as in-parameters, do some calculations and then produce an out-parameter to put in a non-editable field.

A: I am assuming that this is for a form you're creating with Form Builder. If this is the case:

*

*Name the "input" field, by clicking on the gear icon and typing a name. Say first-name.

*Create a text output field, click on the validation settings icon next to the field, and in the dialog, in Calculated Value, type an XPath expression, say: concat('Hello ', $first-name, '!'). As you can see from this example, you can use the $gaga variable to refer to the field named gaga.


text:
Q: JQuery ajax GET request to URL fails although HTTP status is 200 OK I apologize if this question has already been answered.
I am trying to retrieve data from a REST web service that exposes a JSON interface using jQuery .ajax call.
When I call the service using the URL, the jQuery call fails although I get a HTTP status code 200 OK.
When I copy the response into a file on the filesystem and retrieve this, the same call works.
Both the file I am accessing and the web service I am calling are on the same machine.
Some notes on the url used in the code below:
Using:
url: "http://localhost:9090/app/user/861",

the call fails, goes into .fail on all browsers.
The URL itself returns the json on all browsers:
{
    "userid": 861,
    "employeeno": "123",
    "jobdesc": "Developer",
    "firstname": "Jasper",
    "lastname": "Fitussi"
}

when using "test.json" in the local filesystem following is the behavior:
url: "ajax/test.json",

On Firefox, the call executes, goes into .done  and displays the result on page.
On Chrome, the call fails with status 404 and the following message -
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I tried different combinations changing dataType:"jsonp", adding a ?callback=? to the end of the URL, and enclosing the data in the test.json with a '(' and a ')' without luck.
Please understand I am new to UI programming, javascript and jQuery.
Please help with what I am doing wrong. Here's the javascript:

The following is the output when I paste the url into the browser (also the contents of ajax/test.json):
{
    "userid": 861,
    "employeeno": "123",
    "jobdesc": "Developer",
    "firstname": "Jasper",
    "lastname": "Fitussi"
}

A: Your problem is not about UI programming, it's about the security model of modern browsers :p
Access-Control-Allow-Origin errors occurs when you call a webservice (ie: load a JSON file) from a domain that is different from the one hosting your HTML page.
In your case, you are opening the html file from your hard drive (file:///) and calling a webservice on localhost.
This is a security feature in all modern browsers that forbid getting data from a foreign webservice without the webservice owners authorizing you (or everyone, wildcards are allowed) to call it.
I recommend reading the following guide from MDN, so that you understand WHY you are having this problem.
It will then be easy to resolve
https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
If you control the source code of the webservice, or the webserver hosting it, you need to add Access-Control-Allow-Origin HTTP headers.

A: Do you make your ajax call using Apache on wamp, lamp, xampp or mamp or not? I think you work directly using some files lets say on your desktop and not from the www file of wamp. If the browser sends a correct url then the backend responds great, your frontend code seems fine so i think chrome complains about your not using localhost. Am i right? Whats your local development setup?

A: If it's a local file on the client-side, use file:/// to prefix the URL:
url: 'file:///ajax/test.json'

The third / in file:/// indicates:

As a special case,  can be the string "localhost" or the empty
  string; this is interpreted as `the machine from which the URL is
  being interpreted'.
  3.10

Reference here

A: Download a tool called fiddler, from http://fiddler2.com/ great way to debug web requests and to see why they are failing.
This will help you narrow down the issue you are experiencing and we can help you further because currently its all guess work.

A: I had the same issue, all worked fine in I.E and FireFox, a had one ajax call to a rest service using jsonp and it worked fine in chrome, however when I tried to load a file using jsonp I got the cross domain error. In short i had to add "file:" to my file path in the url
    $.ajax({
    type : 'GET',
    url : 'file:jsondata/rain_acc_data.json',
    dataType : 'jsonp',
    jsonpCallback : "jsoncallback",
    success : function(data) {
        aler('ok');
    },
    error : function(jqXHR, status) {
        alert("Failed to load list" + status + jqXHR);
    }
});

this worked for me, make sure to wrap your json in the file with jsoncallback("your jason here");


text:
Q: IOS Rich notification handle dismiss event We are in the process of sending rich notification to users of our apps but we had to track 'dismiss' event of notification too. Apple is providing only 'received' event for notification.
How can we track dismiss event with API?
Related document:
https://developer.apple.com/documentation/usernotificationsui/unnotificationcontentextension


text:
Q: iOS Video Recording video is little shorter than sound We have a video recording app which uses AVFoundation.  As we record video on some iPhone devices ex iPhone7 recorded video is shorter than sound. When played the video, video ends before time scrolling bar ends and image freezes till the end meanwhile sound is kept playing till the end.  It seems video is running a little faster than actual time. It does not happen on iPhone13 mini right now(but has happened before on this device).
Even on same device(iPhone) sometimes it happens and sometimes not.
What reason could be thought of?


text:
Q: Actualizar gridview con procedimiento almacenado Esty tratando de actualizar un gridview con un datasource y un procedimiento almacenado que tengo en sql server pero me arroja el siguiete error: Error de servidor en la aplicación '/'.
Procedure or function SP_ACTUALIZARAREA has too many arguments specified.
Viendo los parametros que tengo en el procedimiento que actualiza, coincide con los parametros de envio, sera que me falta algo?
este el codigo del datasource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$

    ConnectionStrings:BibliotecaConnectionString %>" SelectCommand="SP_LISTAREA" SelectCommandType="StoredProcedure" UpdateCommand="SP_ACTUALIZARAREA" UpdateCommandType="StoredProcedure">
                    <UpdateParameters>
                        <asp:Parameter Name="ARECOD" Type="Int32" />
                        <asp:Parameter Name="ARENOMBRE" Type="String" />
                        <asp:Parameter Name="ARETIEMPO" Type="Int32" />
                    </UpdateParameters>
            </asp:SqlDataSource>

y este es el proc que tengo en sqlserver:
IF OBJECT_ID('SP_ACTUALIZARAREA') IS NOT NULL
    DROP PROC SP_ACTUALIZARAREA

GO

CREATE PROC SP_ACTUALIZARAREA(@ARECOD INT,@ARENOMBRE NVARCHAR(50),@ARETIEMPO INT)
AS
 UPDATE dbo.Area SET areCodigo=@ARECOD,areNombre=@ARENOMBRE,areTiempo=@ARETIEMPO WHERE areCodigo=@ARECOD

Agreadezco la ayuda si hay algo que no he podido ver para solucionarlo.


text:
Q: Celery, Flower, Redis results I am using recent versions of Celery and Flower and Redis, but I cannot understand what is happening.  I get all the results to work and the data is coming back correctly, but when I view the Celery Tasks with Flower, I see all the tasks and the results.
My task has the following decorator:
@celery.task(ignore_result=True, bind=True)
def perform_long_task(self, urls):

I've tried calling get(), forget(), etc but when I look at Flower the results are always there.
I've also tried:
CELERY_TASK_RESULT_EXPIRES=10

I launch the task with:
celery worker -l info -B -A test.api.tasks

I've tried:
class CeleryConfig:
    CELERYBEAT_SCHEDULE = {
        'check-every-minute': {
                    'task': 'celery.backend_cleanup',
                    'schedule': crontab(hour="*/1"),
        }
    }

I cannot get the taks to not show in Flower, so I am thinking that the tasks must still be there (taking up memory).
Is this true?  Any thought to get them to disappear?
Thanks!


text:
Q: MySQL SELECT statement doesn't stop when no rows are found I expect this MySQL query to bomb out when it doesn't find the matching ID in the table:
mysql_query("SELECT * FROM table WHERE id='1' LIMIT 1") OR die("Boom!");

It doesn't. It just goes on processing with no error.
What am I missing here?

A: A select statement doesn't fail if it finds no rows - it just returns an empty result set.
You can check mysql_num_rows to see if any rows were found.

A: The sql statement does not fail, it actually returns nothing.
Look here How does "do something OR DIE()" work in PHP?

A: A query only "fails" when you make a syntax or logical error in it.
A query returning no rows is still a valid query. Check the resultset that it returns to see how many results you get: in your case, check for there being '0'.

A: Run the query from the command line using the mysql command line client to make sure the table is not corrupted.


text:
Q: How can I use NuGet with Visual C# Express? How can I use NuGet to add a library package reference, when I have Visual C# 2010 Express?
NuGet doesn't come up when I search for it in Tools > Extension Manager.
I downloaded "NuGet Package Manager" (the .vsix) from the downloads page, but when it prompts me for which versions of Visual studio to integrate into, it only lists Visual Web Developer Express 2010. Visual C# Express isn't shown. So I guess it would work with Silverlight in VWD, but I want to use it with WPF.
One of the documentation pages linked me to the 1.0 CTP download page, which included a command-line version of NuGet (no longer present in the latest version). But the command-line version seems to be crippled -- the only operation it seems to support is building a package for distribution; it doesn't seem to support the commands for adding a reference to a library package.
Is there any way at all to use NuGet with Visual C# Express?

A: Update (9/12/2012): Good news: Visual Studio Express 2012 for Windows Desktop is now available (here), and it supports NuGet out of the box. Generally speaking, every edition of VS2012 now supports NuGet, so this limitation should be a thing of the past!

Original answer:
Microsoft signs NuGet in a way that allows it to work with VWD Express. Ideally, it would also be signed in a way that it works with C# Express (it may have to be a separate build).  Unfortunately, we were not able to do this for the initial release (it's more of a challenge than you might think).
Going forward, we will try to enable this scenario.  Feel free to file a bug on the NuGet site just to let others who are affected a chance to vote it up!

A: If you have VWD Express installed you can work around this as follows:

*

*Save and close your project in c# Express

*Open the project in VWD Express and use Nuget from there to add your packages

*Save your project and go back to c# Express

A: To install a package in visual studio c# express 2010 use the command line tool nuget.exe. Download nuget.exe from  the nuget website add the path to the executable to the windows path environment variable, cd to a place you want you library to be then run it with the library name as an argument.
C:\Code\myprojectdir\myproject>nuget install CommandLineParser
Installing 'CommandLineParser 1.9.71'.
Successfully installed 'CommandLineParser 1.9.71'.

Then just add a reference to the appropriate version of the dll (ie 4.0), in visual studio c# 2010 using project->add reference->browse. Then build the project.

A: Visit this video:
https://youtu.be/8DcANVHLE0o
The way is:
Download .exe file from nuget.org, and make a folder in %appdata% "NuGet", paste the exe file in the folder, after that open cmd, type cd (the folder adress), and type nuget install (package), the go in the package folder, lib, copy the dll file, and put it as Reference in visual basic


text:
Q: JNI ERROR (app bug): accessed stale global reference I am trying to embedd unity android plugin and face an issue
this is the code:
public class Veedi : MonoBehaviour {

private static AndroidJavaObject VeediObject= null;
private static AndroidJavaObject activityContext = null;
public int DeveloperID;
public int gameID;
void Start() {
    print("**********START__________");
    if(VeediObject == null) {
        print("**********VeediObject________");

        using(AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            print("**********AndroidJavaClass_________");
            activityContext = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
        }
        print("*******Before Init________");
        using(AndroidJavaClass pluginClass = new AndroidJavaClass("com.play.im.MainActivity")) {
            if(pluginClass != null) {

                activityContext.Call("runOnUiThread", new AndroidJavaRunnable(() =>
                {
                    print("0");
                    int attach = AndroidJNI.AttachCurrentThread();
                print("1");

                    VeediObject = pluginClass.CallStatic<AndroidJavaObject>("instance");
                print("2");
                    VeediObject.Call("setContext", activityContext);
                print("3");
                    VeediObject.Call("initVeedi",gameID,DeveloperID);
                    print("**********after Init__________");

                }));

            }
        }
    }
}

When the code reach the line:

VeediObject = pluginClass.CallStatic("instance");

It crahes in with a:

JNI ERROR (app bug): accessed stale global reference

Someone suggested to use:

AndroidJNI.NewGlobalRef

Can someone help with a direction to this problem? someone suggested its because the JNI refrence to the java objects changes

A: The C# reference to pluginClass is lost as soon as the enclosing block is finished.
You are calling Java code on the Android UI thread which means that the lambda function you're passing as the 2nd argument in AndroidJavaClass.Call is executed at a later time after the block holding the reference for pluginClass is lost and hence your error.
You should keep a reference to com.play.im.MainActivity outside of the using block. You can keep a reference to it as a member of the MonoBehaviour.
private static AndroidJavaClass pluginClass;

void Start()
{
  ...
  pluginClass = new AndroidJavaClass("com.play.im.MainActivity");

  if(pluginClass != null) {

            activityContext.Call("runOnUiThread", new AndroidJavaRunnable(() =>
            {
                print("0");
                int attach = AndroidJNI.AttachCurrentThread();
            print("1");

                VeediObject = pluginClass.CallStatic<AndroidJavaObject>("instance");
            print("2");
                VeediObject.Call("setContext", activityContext);
            print("3");
                VeediObject.Call("initVeedi",gameID,DeveloperID);
                print("**********after Init__________");

            }));

        }
}


text:
Q: there is problem in importing my class in scrapy spider I am facing problem since one week .I was not able to import my class in the scrapy spider(in shareprice.py).I have tried many ways but not found anywhere please give me the solution .
shareprice.py and my class in the same directory in spiders
import scrapy
import json
import sys
from .myclass import *

The error I get is:

error -attempted relative import with no known parent package

A: To make a directory a real python package place an empty __init__.py file in it.
Also import * something is bad practice most of the time. You should only import functions and classes you really need (explicit is better than implicit).


text:
Q: Test abstract class calls parent method in Python I'm currently refactoring features and I ended up with this abstractions
I have this classes
class AbstractClassA(SomeOtherAbstractClass):
    @abstractmethod
    def some_abstract_method(self):
        pass

    def my_method(self)):
       service.some_method

class AbstractClassB(AbstractClassA):
    @abstractmethod
    def another_abstract_method(self):
        pass

    def some_abstract_method(self):
        some_implementation

    def my_method(self):
        super().my_method()
        do_any_other_stuff

And I need to test if the AbstractClassB.my_method calls super().my_method().
I've tried to test this by creating some ImplementationClass that inherits from AbstractClassB and then mocking the AbstractClassA.my_method and checking if it was called but it didn't work...
class AbstractClassBImplementation(AbstractClassB):
    def some_abstract_method(self):
        calls_service()

class TestAbstractClassB(TestCase):
    @patch('module.submodule.AbstractClassA.my_method')
    def test_class_b_calls_class_a_my_method(self, my_method_mock):
        instance = AbstractClassBImplementation()

        instance.my_method()

        self.assertTrue(my_method_mock.called)

Someone know how to test this?


text:
Q: how to decode QR code - iPhone I am developing an app which reads barcode and QR code using Zbarcode framework. Is there any way to decode the QR code using objective c?

A: You can refer to this library called Zxing.
This has both QRCode Reader and BarCode Reader.
http://code.google.com/p/zxing/
Hope this helps you.


text:
Q: AutoIt: Anyone know what's wrong with this RegRead call? Trying to get the value of this registry key using AutoIt and it keeps failing.
My guess is it's due to the , and/or . in the key name, but I haven't been able to find any good info on this type of issue in the AutoIt docs or other Google searches. I've tried escaping each one individually and together using the usual escape character \, also with no luck.
I've confirmed the key names are correct, and also have tried a completely different reg key without the odd characters in my script just to see if it worked normally, which succeeded.
Dim $VMWare_Path = RegRead("HKLM\SOFTWARE\VMware, Inc.\VMware Workstation", "InstallPath")

A: Update:
Well, the solution turned out to be that I needed to read from a different registry node depending of the OS version. Final code:
Local $VMWPath

if @CPUArch = "X64" Then
   ;x64 Key
   $VMWPath = RegRead("HKLM\SOFTWARE\Wow6432node\VMware, Inc.\VMware Workstation", "InstallPath")
Else
  ;x86 Key
  $VMWPath = RegRead("HKLM\SOFTWARE\VMware, Inc.\VMware Workstation", "InstallPath")
EndIf


text:
Q: Python pool.map with large iteratables I have a quite large table in a database (>20GB). I want to read all rows from the whith python and print them. I am using an SQLite database and Python 2.7
My first approach is quite standard. I can simpyl query all rows and iterate over them:
cur.execute('SELECT * FROM large_table')
for row in cur:
    print row

This works as expected.
Out of curiosity I wanted to use multiprocessing.Pool to do the same job.
def consumer(data):
    print data

cur.execute('SELECT * FROM large_table')
pool = Pool(5)

pool.map(consumer, cur, chunksize=1000)

But this does not work at all. The .map() methods seems to try to load the full iteratable (large database table) into RAM. After a while all of my RAM is in use without any output.
Am I missing anything or is pool.map just the wrong tool for the job?
Cheers,
Tobias

A:
Am I missing anything or is pool.map just the wrong tool for the job?

Yes, you should use pool.imap() instead.  It does not "consume" all the values before dispatching to the worker processes.   It should be a drop-in fix for your code.