text:
Q: Obtener el contacto del propietario del dispositivo en Android En la aplicación Contactos, el primero que muestra es del propietario.
¿Se puede extraer la información del contacto del propietario del dispositivo?
He buscado por todos los contactos disponibles del proveedor ContactsContract.Contacts y no veo en ningún caso que lo indexe.
¿Me pregunto, si se guarda en otro rincón o bien es de solo uso interno de la app contactos del sistema?
Edición
Busancdo por el SDK he econtrado como obtener los datos del propietario del dispositivo
public static SimpleContact TESTgetLocalProfile(Context context) {

    Uri PROFILE_URI = ContactsContract.Profile.CONTENT_URI;
    String[] PROJECTION = new String[]{
            ContactsContract.Profile._ID,
            ContactsContract.Profile.DISPLAY_NAME,
            ContactsContract.Profile.PHOTO_URI,
            ContactsContract.Profile.HAS_PHONE_NUMBER,
            ContactsContract.Profile.LOOKUP_KEY
    };
    final String SELECTION = ContactsContract.CommonDataKinds.Email.CONTACT_ID + "= ?";
    String[] mSelectionArgs = {"10"};
    String sortOrder = ContactsContract.CommonDataKinds.Email.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

    // Build adapter with contact entries
    Cursor c = context.getContentResolver().query(PROFILE_URI, PROJECTION, null, null, null);

    SimpleContact item = null;

    if (c != null && c.moveToFirst()) {
        String contactId = c.getString(c.getColumnIndex(ContactsContract.Profile._ID));
        item = new SimpleContact(contactId);
        item.setDisplayName(c.getString(c.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME)));
        item.setPhoto(c.getString(c.getColumnIndex(ContactsContract.Profile.PHOTO_URI)));
        item.setLookupKey(c.getString(c.getColumnIndex(ContactsContract.Profile.LOOKUP_KEY)));
        if (c.getInt(c.getColumnIndex(ContactsContract.Profile.HAS_PHONE_NUMBER)) > 0) {
            //No ser como obtener el número
        }
        c.close();
    }

    return item;

}

Debug de campos:
D/ContactsHelper: columName: sort_key =Test User
D/ContactsHelper: columName: blocked =0
D/ContactsHelper: columName: photo_uri =content://com.android.contacts/display_photo/9223372034707292161
D/ContactsHelper: columName: status_label =null
D/ContactsHelper: columName: status_ts =null
D/ContactsHelper: columName: status_res_package =null
D/ContactsHelper: columName: display_name =Test User
D/ContactsHelper: columName: last_time_used =null
D/ContactsHelper: columName: mimetype =vnd.android.cursor.item/name
D/ContactsHelper: columName: phonebook_label_alt =U
D/ContactsHelper: columName: data6 =null
D/ContactsHelper: columName: version =7
D/ContactsHelper: columName: photo_id =9223372034707292166
D/ContactsHelper: columName: data3 =User
D/ContactsHelper: columName: custom_ringtone =null
D/ContactsHelper: columName: times_contacted =0
D/ContactsHelper: columName: account_type_and_data_set =com.android.localphone
D/ContactsHelper: columName: dirty =1
D/ContactsHelper: columName: data7 =null
D/ContactsHelper: columName: data15 =null
D/ContactsHelper: columName: raw_contact_is_user_profile =1
D/ContactsHelper: columName: data_set =null
D/ContactsHelper: columName: phonebook_label =T
D/ContactsHelper: columName: data10 =1
D/ContactsHelper: columName: res_package =null
D/ContactsHelper: columName: account_type =com.android.localphone
D/ContactsHelper: columName: data11 =0
D/ContactsHelper: columName: display_name_alt =User, Test
D/ContactsHelper: columName: lookup =profile
D/ContactsHelper: columName: phonetic_name =null
D/ContactsHelper: columName: last_time_contacted =0
D/ContactsHelper: columName: contact_last_updated_timestamp =1505762023483
D/ContactsHelper: columName: data13 =null
D/ContactsHelper: columName: in_visible_group =0
D/ContactsHelper: columName: chat_capability =null
D/ContactsHelper: columName: data9 =null
D/ContactsHelper: columName: carrier_presence =0
D/ContactsHelper: columName: data_sync1 =null
D/ContactsHelper: columName: sort_key_alt =User, Test
D/ContactsHelper: columName: contact_presence =null
D/ContactsHelper: columName: data_version =0
D/ContactsHelper: columName: phonetic_name_style =0
D/ContactsHelper: columName: name_raw_contact_id =9223372034707292163
D/ContactsHelper: columName: raw_contact_id =9223372034707292163
D/ContactsHelper: columName: send_to_voicemail =0
D/ContactsHelper: columName: data4 =null
D/ContactsHelper: columName: data12 =null
D/ContactsHelper: columName: contact_status =null
D/ContactsHelper: columName: contact_status_label =null
D/ContactsHelper: columName: pinned =0
D/ContactsHelper: columName: status_icon =null
D/ContactsHelper: columName: status =null
D/ContactsHelper: columName: data1 =Test User
D/ContactsHelper: columName: phonebook_bucket =21
D/ContactsHelper: columName: data_sync2 =null
D/ContactsHelper: columName: contact_status_res_package =null
D/ContactsHelper: columName: in_default_directory =1
D/ContactsHelper: columName: _id =9223372034707292163
D/ContactsHelper: columName: hash_id =null
D/ContactsHelper: columName: is_super_primary =0
D/ContactsHelper: columName: data5 =null
D/ContactsHelper: columName: contact_id =9223372034707292162
D/ContactsHelper: columName: data8 =null
D/ContactsHelper: columName: is_primary =0
D/ContactsHelper: columName: data_sync4 =null
D/ContactsHelper: columName: has_phone_number =1
D/ContactsHelper: columName: display_name_source =40
D/ContactsHelper: columName: photo_file_id =9223372034707292161
D/ContactsHelper: columName: custom_vibration =0
D/ContactsHelper: columName: data_sync3 =null
D/ContactsHelper: columName: backup_id =null
D/ContactsHelper: columName: data14 =null
D/ContactsHelper: columName: contact_status_ts =null
D/ContactsHelper: columName: phonebook_bucket_alt =22
D/ContactsHelper: columName: mode =null
D/ContactsHelper: columName: data2 =Test
D/ContactsHelper: columName: group_sourceid =null
D/ContactsHelper: columName: starred =0
D/ContactsHelper: columName: photo_thumb_uri =content://com.android.contacts/contacts/9223372034707292162/photo
D/ContactsHelper: columName: times_used =null
D/ContactsHelper: columName: contact_status_icon =null
D/ContactsHelper: columName: contact_chat_capability =null
D/ContactsHelper: columName: account_name =PHONE
D/ContactsHelper: columName: sourceid =null

Lo que me falta es obtener el número de teléfono asociado, pero como que el contacto no está dentro del proveedor de contactos ni de rawcontacts, no lo puedo obtener.

A: Mediante ContactsContract no existe una forma de obtener los datos del cliente, el dueño del dispositivo generalmente agrega su cuenta gmail, pero regularmente no su teléfono en los contactos, además no existe un indicador para determinar que contacto es el propietario.
Como opción para obtener la (o las) cuenta(s) del propietario:
final AccountManager manager = AccountManager.get(this);
final Account[] accounts = manager.getAccountsByType("com.google");

String[] emails = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
    emails[i] = accounts[i].name;
}

A: En construcción...
Mas o menos he encontrado como obtenerlos, pero falta pulir...
public static SimpleContact TESTgetLocalProfile(Context context) {

    Uri PROFILE_URI = ContactsContract.Profile.CONTENT_URI;
    String[] PROJECTION = new String[]{
            ContactsContract.Profile._ID,
            ContactsContract.Profile.DISPLAY_NAME,
            ContactsContract.Profile.PHOTO_URI,
            ContactsContract.Profile.HAS_PHONE_NUMBER,
            ContactsContract.Profile.LOOKUP_KEY
    };

    Cursor c = context.getContentResolver().query(PROFILE_URI, PROJECTION, null, null, null);

    SimpleContact item = null;

    if (c != null && c.moveToFirst()) {
        String contactId = c.getString(c.getColumnIndex(ContactsContract.Profile._ID));
        item = new SimpleContact(contactId);
        item.setDisplayName(c.getString(c.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME)));
        item.setPhoto(c.getString(c.getColumnIndex(ContactsContract.Profile.PHOTO_URI)));
        item.setLookupKey(c.getString(c.getColumnIndex(ContactsContract.Profile.LOOKUP_KEY)));

        if (c.getInt(c.getColumnIndex(ContactsContract.Profile.HAS_PHONE_NUMBER)) > 0) {

            Cursor pCur = context.getContentResolver().query(
                    // Retrieves data rows for the device user's 'profile' contact
                    Uri.withAppendedPath(
                            ContactsContract.Profile.CONTENT_URI,
                            ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
                    new String[]{
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                            ContactsContract.CommonDataKinds.Phone.IS_PRIMARY,
                            ContactsContract.Contacts.Data.MIMETYPE
                    },

                    // Selects only email addresses or names
                    ContactsContract.Contacts.Data.MIMETYPE + "=? ",
                    new String[]{
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
                    },

                    // Show primary rows first. Note that there won't be a primary email address if the
                    // user hasn't specified one.
                    ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"
            );

            if (pCur != null && pCur.moveToFirst()) {
                item.setPhoneNumber(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                pCur.close();
            }

        }
        c.close();
    }

    return item;

}

Código adaptado de AccountUtils.java


text:
Q: Filtrar CSV desde ComboBox primero que nada estoy iniciando en la programación.
Tengo un archivo CSV que tiene una base de datos delimitada por (,):
Ej:
Dato1, Dato2, Dato3, Dato4, Dato5, Etc....
Dato1, Dato2, Dato3, Dato4, Dato5, Etc....
Dato1, Dato2, Dato3, Dato4, Dato5, Etc....
Dato1, Dato2, Dato3, Dato4, Dato5, Etc....
La idea es que los Datos 1,2 aparezcan en un ComboBox para filtrar la informacion y que los demas datos aparezcan en diferentes TextBox. Hasta ahora solo he conseguido que aparezcan los datos 1 y 2 en el ComboBox con el siguiente codigo:
       string[] Datos = File.ReadAllLines("./Hoja4.csv");
        foreach (var Data in Datos)
        {
            var valores = Data.Split(',');
            CbLocalidad.Items.Add(valores[0] + " " + valores[1]);

                 }

Quiero filtrar la fila por el ComboBox y que los textbox se llenen con la demas informacion de esa fila.
Gracias de antemano por la ayuda.

A: Hice un ejemplo:

CSV utilizado para el ejemplo:

A, Dato2, ADato3, ADato4, ADato5
B, Dato2, BDato3, BDato4, BDato5
C, Dato2, CDato3, CDato4, CDato5
D, Dato2, DDato3, DDato4, DDato5

Cree un objeto para pasar los datos del CSV

public class CsvDatos
{
    public int Renglon { get; set; }
    public string ComboDisplayMember { get; set; }
    public string Columna3 { get; set; }
    public string Columna4 { get; set; }
    public string Columna5 { get; set; }
}

Para pasar los datos del CSV al combo, primero habia que convertir CSV al objeto que cree

        string[] datos = File.ReadAllLines(this.textBox1.Text);
        List<CsvDatos> csvDatos = new List<CsvDatos>();
        int i = 0;
        foreach (var renglon in datos)
        {
            i++;
            var valores = renglon.Split(',');
            csvDatos.Add(new CsvDatos()
            {
                Renglon = i,
                ComboDisplayMember = valores[0] + " " + valores[1],
                Columna3 = valores[2],
                Columna4 = valores[3],
                Columna5 = valores[4]
            });
        }

        this.comboBox1.DataSource = csvDatos;
        this.comboBox1.ValueMember = nameof(CsvDatos.Renglon);
        this.comboBox1.DisplayMember = nameof(CsvDatos.ComboDisplayMember);

Este es el diseño del formulario

Es necesario agregar un evento al Combo

En el evento del combo solo hay que tomar el objeto actual seleccionado y tomar de este objeto los datos que serán mostrados en los textbox

        var csvRenglon = (this.comboBox1.SelectedItem as CsvDatos);
        MostrarDato(csvRenglon);

Este seria el código  del form

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace CsvDatos
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] datos = File.ReadAllLines(this.textBox1.Text);
            List<CsvDatos> csvDatos = new List<CsvDatos>();
            int i = 0;
            foreach (var renglon in datos)
            {
                i++;
                var valores = renglon.Split(',');
                csvDatos.Add(new CsvDatos()
                {
                    Renglon = i,
                    ComboDisplayMember = valores[0] + " " + valores[1],
                    Columna3 = valores[2],
                    Columna4 = valores[3],
                    Columna5 = valores[4]
                });
            }

            this.comboBox1.DataSource = csvDatos;
            this.comboBox1.ValueMember = nameof(CsvDatos.Renglon);
            this.comboBox1.DisplayMember = nameof(CsvDatos.ComboDisplayMember);
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            LimpiarDatos();
            var csvRenglon = (this.comboBox1.SelectedItem as CsvDatos);
            MostrarDato(csvRenglon);
        }

        private void MostrarDato(CsvDatos csvDato)
        {
            this.txtDato3.Text = csvDato.Columna3;
            this.txtDato4.Text = csvDato.Columna4;
            this.txtDato5.Text = csvDato.Columna5;
        }

        private void LimpiarDatos()
        {
            this.txtDato3.Text = string.Empty;
            this.txtDato4.Text = string.Empty;
            this.txtDato5.Text = string.Empty;
        }
    }
}

El resultado se vería algo así:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handling x86 IRQs from secondary PIC: EOI order important? I recently added a part to an application of mine which is meant to allow it to operate with an IRQ belonging to the secondary PIC. In particular, the interrupt handler needs to signal an End Of Interrupt condition to both PICs then instead of only the primary one. This is my code:
  push cs
  pop ds
  mov al, 20h   ; acknowledge interrupt
  cmp byte [serial_use_irqmask + 1], 0
  je @F
  out 0A0h, al  ; to secondary PIC
@@:
  out 20h, al   ; to primary PIC

Now, while adding this part I considered whether to signal the EOI to the secondary PIC first, or to the primary PIC. Searching for that did not yield any statements either way. However, I found that some examples seem to choose the order I ended up implementing; that is the secondary PIC first, then the primary.
My question is, does this matter at all? Is there an actual reason to prefer either order?
Examples of secondary PIC first
bootlib interrupt handlers:
                movb $0x20, %al # end of interrupt command
                outb %al, $0xA0 # PIC2 command port
                outb %al, $0x20 # PIC1 command port

osdev.org wiki's article on Interrupts:
mov al, 20h
out A0h, al
out 20h, al

Pure64 interrupt handlers:
        mov al, 0x20        ; Acknowledge the IRQ
        out 0xA0, al
        out 0x20, al

Dos64-stub interrupt handlers:
Irq0007_1:
    mov al,20h
    out 20h,al
    pop rax
swint:
    iretq
;--- IRQs 8-F
Irq080F:
    push rax
    mov al,20h
    out 0A0h,al
    jmp Irq0007_1

Example of primary PIC first
Example in the German Wikipedia article "Softwarebremse" ("Bremse" means "Brake"):
   mov al, 20h
   out 020h, al
   out 0a0h, al
   sti

A: I don't think it matters.
The 8259A datasheet doesn't shed any more light, only stating (twice):

An EOI command must be issued twice: once for the master and once for the corresponding slave.

No order is stated explicitly.
Sending the EOI to the slave first still won't allow any IRQ from the slave (until the EOI to the master), because the master won't serve any of the slave requests.
When the master receives the EOI, all IRQs will be allowed.
Sending the EOI to the master first will allow new master IRQs but no slave IRQs, until the slave receives the EOI too.
So sending the EOI to the slave first won't change the "interruptability" of the system while the master is still waiting for its EOI.
This allows finer control of the moment the system is ready to accept lower-priority interrupts.
Assuming the IF flag is set before iret.

As far as the PICs are concerned, there is no technical requirement to use a specific order.
I don't think there a difference in the risk of losing slave IRQs:
The PIC will set the IRR bit immediately upon the assertion of the relative IRQ pin but the ISR bit is set only after receiving the ACK from the CPU (and the IRR bit is cleared).
The IRR-ISR pair form a mini-queue, with the IRR buffering a request while an interrupt is still being served.
When the slave receives the EOI first and the master doesn't, it's the master that prevents the slave from setting the ISR and clearing the IRR by not issuing an interrupt request to the CPU. When the master receives the EOI first and the slave doesn't, it's the slave itself that won't issue an interrupt request.
In any case, the IRR is never cleared and only one IRQ request can be buffered.
Sending the EOI to the master first may unlock its (high-priority) IRQs earlier but we are talking about the timing of a few instructions.
Again assuming the IF flag is set before iret.
I don't see any reason to prefer any of the two ordering.


text:
Q: How does the z transform work in practice? What I've found
I've implemented a PID controller using the equations 7 and 9 of this article, which states that:
$$\frac{U(s)}{E(s)}=K_p+\frac{K_i}{s}+K_ds$$
Translates to $$\frac{U(z)}{E(z)}=K_p+\frac{K_i}{1-z^{-1}}+K_d(1-z^{-1})$$
Meaning that I had to implement:
$$u(k)=u(k-1)+(K_p+K_i+K_d)e(k)-(K_p+2K_d)e(k-1)+K_de(k-2)$$
It looks like it's working fine, so I wanted to understand how they got this equation but I don't end up with the same results.
What I've done
Apparently the z-transform is linear so I just have to find the z-transform of the integrator $\frac{1}{s}$ and the derivative $s$. Tables give the z transform of the integrator as $\frac{1}{1-z^{-1}}$ but do not give that of the derivative (why?) so I tried to do both this way:
$$\text{integral}(k)=\text{integral}(k-1)+\frac{\text{input}(k)+\text{input}(k-1)}{2}T$$
$$\text{derivative}(k)=\frac{\text{input}(k)-\text{input}(k-1)}{T}$$
Which, if previous values are multiplied by $z^{-1}$, yields:
$$\text{integral}(z)=\text{integral}(z)z^{-1}+\frac{\text{input}(z)+\text{input}(z)z^{-1}}{2}T$$
$$\text{derivative}(k)=\frac{\text{input}(k)-\text{input}(k)z^{-1}}{T}$$
Rearranged:
$$\frac{\text{integral}}{\text{input}}(z)=\frac{T}{2}\frac{1+z^{-1}}{1-z^{-1}}$$
$$\frac{\text{derivative}}{\text{input}}(z)=\frac{1-z^{-1}}{T}$$
Question
Why don't they give the same answer? How does the z-transform work in practice (including how to get from the z transfer function to discrete time)? I could not find anything well explained online.

A: The formula for $U(z)/E(z)$ cannot be right - it makes no reference to sample time. There are many good references with correct formulas for discrete PID controllers. They are not unique - there are several slightly different constructions that implement the idea of PID control.
It is not completely clear what a $z$-transform of a function of $s$ would be. One of the reasons why an exact differentiator cannot be built in discrete time has to do with causality.


text:
Q: Redirect user to specific page when user is inactive for a specified time I want to program my servlet to block the session without closing if the user is inactive for 10 minutes and redirect the user to the page sessionlocked.jsp.
I tested this code, but it does not work.
session.setMaxInactiveInterval(10*60);
if (request.getSession(false) == null) {
    response.sendRedirect(url);
}

How can I achieve this?

A: As documentation;

setMaxInactiveInterval(int interval)
Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

So setMaxInactiveInterval method does not meet your needs, it invalidates the session.
To show a locked page to the users, you have two options;
First;

Use filters to check session time and if time is over redirect to
  lockedpage otherwise reset time.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession(false);
    if (session == null) {
        // ((HttpServletRequest) request).getSession(true);
        // redirect to logout or anywhere you want, to create a session
        return;
    }
    // Check if filter also work for sessionlocked.jsp
    if (((HttpServletRequest) request).getRequestURL().toString().contains("sessionlocked")) {
        chain.doFilter(request, response); // no need to check sessionlocked
        return;
    }
    long lastAccessTime = session.getLastAccessedTime();
    long tenMinuteAsMilisecond = 10 * 60 * 1000;
    if (lastAccessTime + tenMinuteAsMilisecond > (new Date()).getTime()) {
        chain.doFilter(request, response); // session still not locked
    } else {
        ((HttpServletResponse) response).sendRedirect("sessionlocked.jsp");
    }
}

Second(In addition to First because First attempt is controlled on server side);

Use javascript to count down and when time is over, redirect user to
  the locked page.

 window.onload = function() {
        setInterval(function() {
            window.location.replace("/sessionlocked.jsp");
              }, 600000);
    }

if only need servlet; (when user interaction with servlet)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    if (session == null) {
        request.getSession(true);
        // redirect to logout or anywhere you want, to create a session
        return;
    }
    long lastAccessTime = session.getLastAccessedTime();
    long tenMinuteAsMilisecond = 10 * 1000;// to test lock time set to 10 seconds
    if (lastAccessTime + tenMinuteAsMilisecond > (new Date()).getTime()) {
        response.getOutputStream().print("Session not locked" + i++);
        // TODO for not locked code
    } else {
        response.getOutputStream().print("Session locked");
         //redirect to sessionlocked.jsp
    }
}

Servlet Output (lock time set to 10 seconds);


text:
Q: Javascript to validate only Numeric after predefined text in a textbox I'm trying to use Javascript to make a textbox that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. I need to allow only 10 digit numeric after the readonly text and need to validate for the numeric digits. The following is the Javascript code for having the readonly in textbox
var readOnlyLength = $('#field').val().length;
 $('#output').text(readOnlyLength);enter code here
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
    && ((this.selectionStart < readOnlyLength)
    || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
    return false;
}
});

A: If you looking for solution with script then here is plain js and RegExp:

var fixedText = function(textbox, label) {
  var num = textbox.value.replace(/\D/g, ''); //non numeric
  num = num.substr(0, 10); //max 10 digits
  textbox.value = label + num;
};
<input type="text" onkeyup="fixedText(this, 'Postal Code: ')" autofocus='' value="Postal Code: " />
<input type="text" onkeyup="fixedText(this, 'Contact No: ')" value='Contact No: ' />

With simple label ,input and script:

var numeric = function(textbox) {
  var num = textbox.value.replace(/\D/g, '');
  num = num.substr(0, 10);
  textbox.value = num;
};
label.partial,
input.partial {
  border: 1px ridge grey;
  margin-bottom: 3px;
}
label.partial {
  border-right: none;
  cursor: text;
}
input.partial {
  border-left: none;
  margin-left: -4px;
  top: -1px;
  position: relative;
}
Postal Code
<input type="text" onkeyup="numeric(this)" autofocus='' id='PostalCode' class='partial' />

Contact No
<input type="text" onkeyup="numeric(this)" id='ContactNo' class='partial' />


text:
Q: Testing Directives in Angular This is my first time testing directives.  Does anyone know how I should get started on this or know of any good resources for finding out how to test directives? The angular docs where not a great help
 angular.module('pb.campaigns.directives')
        .directive('pbImagePicker', ['$window', '$document', function ($window, $document) {
            return {
                restrict: "E",
                template: '',
                scope: {
                    fileId: '=pbFileId',
                    accountId: '=pbAccountId',
                    defaultSrc: '@pbDefaultSrc',
                    width: '@pbWidth',
                    height: '@pbHeight'
                },
                controller: 'pbImagePickerController',
                link: function (scope, element, attrs) {
                    scope.$watch('defaultSrc', function (value) {
                        if (value !== undefined) {
                            scope.imageSource = value;
                        }
                    });
                    element.click(function () {
                        scope.pickImage(scope.accountId).then(function (image) {
                            scope.imageSource = image.storageUrl;
                            scope.fileId = image.fileId;
                        }, function () {
                            console.log('Modal dismissed at: ' + new Date());
                        });
                    });
                }
            };
        }]);

I was trying to do something like the following but im not sure if im on the right track or how to proceed.
describe('pbImagePicker', function () {
    beforeEach(module('pb.campaigns.directives'));
    beforeEach(module('ui.router'));
    beforeEach(module('ui.bootstrap'));
    var $compile;
    var $rootScope;
    beforeEach(inject(function (_$compile_, _$rootScope_, _$document_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $document = _$document_;
    }));
    describe('', function () {
        it('Replaces the element with the appropriate content', function () {
            // Compile a piece of HTML containing the directive
            var element = $compile("<pb-image-picker></pb-image-picker>")($rootScope);
            // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
            $rootScope.$digest();
            // Check that the compiled element contains the templated content
            expect(element.html()).toEqual('');
        });
    });
    describe('element.click()', function () {
        beforeEach(function () {
            element = angular.element('');
            compiled = $compile(element)($rootScope);
            compiled.triggerHandler('click');
            expect().toEqual();
        });
        it('should resolve a promise when clicked', function () {
            spyOn($rootScope, 'pickImage');
            $rootScope.$digest();
            expect($rootScope.pickImage).toHaveBeenCalled();
        });
        it('should assign data from resolved promise when clicked', function () {
            $rootScope.$digest();
            expect($rootScope.imageSource).toEqual();
            expect($rootScope.fileId).toEqual();
        });
    });
});

A: Use the AngularJS tests specs as a reference. For example:
'use strict';

describe('style', function()
{
  var element;

  afterEach(function()
  {
dealoc(element);
  });

  it('should compile style element without binding', inject(function($compile, $rootScope)
  {
element = jqLite('');
$compile(element)($rootScope);
$rootScope.$digest();

// read innerHTML and trim to pass on IE8
expect(trim(element[0].innerHTML)).toBe('.header{font-size:1.5em; h3{font-size:1.5em}}');
  }));

  it('should compile style element with one simple bind', inject(function($compile, $rootScope)
  {
element = jqLite('');
$compile(element)($rootScope);
$rootScope.$digest();

// read innerHTML and trim to pass on IE8
expect(trim(element[0].innerHTML)).toBe('.some-container{ width: px; }');

$rootScope.$apply(function()
{
  $rootScope.elementWidth = 200;
});

// read innerHTML and trim to pass on IE8
expect(trim(element[0].innerHTML)).toBe('.some-container{ width: 200px; }');
  }));

  it('should compile style element with one bind', inject(function($compile, $rootScope)
  {
element = jqLite('');
$compile(element)($rootScope);
$rootScope.$digest();

// read innerHTML and trim to pass on IE8
expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size: em }}');

$rootScope.$apply(function()
{
  $rootScope.fontSize = 1.5;
});

// read innerHTML and trim to pass on IE8
expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size: 1.5em }}');
  }));

  it('should compile style element with two binds', inject(function($compile, $rootScope)
  {
element = jqLite('');
$compile(element)($rootScope);
$rootScope.$digest();

// read innerHTML and trim to pass on IE8
expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size:  }}');

$rootScope.$apply(function()
{
  $rootScope.fontSize = 1.5;
  $rootScope.unit = 'em';
});

// read innerHTML and trim to pass on IE8
expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size: 1.5em }}');
  }));

  it('should compile content of element with style attr', inject(function($compile, $rootScope)
  {
element = jqLite('
{{bind}}
');
$compile(element)($rootScope);
$rootScope.$apply(function()
{
  $rootScope.bind = 'value';
});

expect(element.text()).toBe('value');
  }));
});

References

*

*AngularJS source: ngStyleSpec

*AngularJS test helpers: testabilityPatch.js


text:
Q: Compiler error for .resx file with reference to Enum and TypeConverter of its own assembly First approach: Assembly A refers to assembly B. For this constellation, I found out how to create a .resx file for assembly A that contains an enum defined in assembly B. In the same way, I made the .resx file contain an object for which a TypeConverter exists in assembly B.
The real goal, however, is that I do without assembly B. Both Enum and the TypeConverter should be in assembly A. However, Visual Studio reports a compile error when attempting this. I suspect the problem is circular: resgen.exe can only access my Enum and my TypeConverter after assembly A has been created, assembly A can only be created once the .resx file has been compiled.
Does somebody has any idea?
Edit
1. My enum ESecurityContextAttributes
a. ESecurityContextAttributes implementation:
<Flags>
Public Enum ESecurityContextAttributes As Int32
    None = 0
    ' other values
End Enum

b. ESecurityContextAttributes value in .resx file:
<assembly alias="NDToolsCommon0" name="NDToolsCommon0, Version=5.2.0.1, Culture=neutral, PublicKeyToken=null" />
<data name="TlsStreamInContextAttributes" type="NDTools.Common.WindowsAndInteroperability.ESecurityContextAttributes, NDToolsCommon0">
    <value>ReplayDetect, SequenceDetect, Confidentiality, InitStream, AcceptStream</value>
</data>

c. Error for ESecurityContextAttributes value:

error MSB3103. Ungültige ResX-Datei. Der Typ NDTools.Common.WindowsAndInteroperability.ESecurityContextAttributes, NDToolsCommon0, Version=5.2.0.1, Culture=neutral, PublicKeyToken=null in den Daten in Zeile 401, Position 4, kann nicht gefunden werden. [english: Not valid Resx file. Type ... cannot be found.]

2. My object ConfigStringList
a. ConfigStringList implementation:
<Serializable>
<TypeConverter(GetType(ConfigListTypeConverter(Of String, ConfigStringList)))>
Public NotInheritable Class ConfigStringList
Inherits ConfigBaseList(Of String, ConfigStringList)
    Public Sub New()
        MyBase.New
    End Sub
    Public Sub New(ByVal valValues As IEnumerable(Of String))
        MyBase.New(valValues)
    End Sub
    Private Sub New(serializationInfo As SerializationInfo, streamingContext As StreamingContext)
        MyBase.New(serializationInfo, streamingContext)
    End Sub
End Class

b. ConfigBaseList implementation:
<Serializable>
Public MustInherit Class ConfigBaseList(Of TItem As {IConvertible, IEquatable(Of TItem)}, TList As {New, Class, IList(Of TItem)})
Inherits List(Of TItem)
Implements ISerializable
    Protected Sub New()
        MyBase.New()
    End Sub
    Protected Sub New(ByVal valValues As IEnumerable(Of TItem))
        MyBase.New(valValues)
    End Sub
    Protected Sub New(ByVal valInfo As SerializationInfo, ByVal valContext As StreamingContext)
        AddRange(DirectCast((New ConfigListTypeConverter(Of TItem, TList)).ConvertFrom(DirectCast(valInfo.GetValue("Values", GetType(String)), String)), ConfigBaseList(Of TItem, TList)))
    End Sub
    Friend Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
        info.AddValue("Values", (New ConfigListTypeConverter(Of TItem, TList)).ConvertTo(Me, GetType(String)))
    End Sub
End Class

c. ConfigListTypeConverter implementation:
Public NotInheritable Class ConfigListTypeConverter(Of TItem As {IConvertible, IEquatable(Of TItem)}, TList As {New, Class, IList(Of TItem)})
Inherits TypeConverter
    Private ReadOnly _converter As New ConvertibleConverter
    Public Sub New()
        MyBase.New
    End Sub
    Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
        If destinationType.GetType = GetType(Design.Serialization.InstanceDescriptor) Then
            Return True
        Else
            Return MyBase.CanConvertTo(context, destinationType)
        End If
    End Function
    Public Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
        Return sourceType = GetType(String)
    End Function
    Public Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object
        Dim valuesString As String
        valuesString = TryCast(value, String)
        If valuesString IsNot Nothing Then
            Return _ParseValueString(valuesString)
        Else
            Return MyBase.ConvertFrom(context, culture, value)
        End If
    End Function
    Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object
        Dim values As TList
        Dim ctor As ConstructorInfo
        values = TryCast(value, TList)
        If values IsNot Nothing AndAlso destinationType = GetType(String) Then
            Return String.Join(",", values.Select(Function(dlgValue As TItem) _converter.Write(dlgValue, CultureInfo.InvariantCulture).Replace("\", "\\").Replace(",", "\,")))
        ElseIf destinationType = GetType(Design.Serialization.InstanceDescriptor) AndAlso values IsNot Nothing Then
            ctor = GetType(TList).GetConstructor({GetType(IEnumerable(Of TItem))})
            Return New Design.Serialization.InstanceDescriptor(ctor, {values})
        Else
            Return MyBase.ConvertTo(context, culture, value, destinationType)
        End If
    End Function

    Public Overrides Function GetProperties(context As ITypeDescriptorContext, value As Object, attributes() As Attribute) As PropertyDescriptorCollection
        Return Nothing
    End Function
    Public Overrides Function GetPropertiesSupported(context As ITypeDescriptorContext) As Boolean
        Return False
    End Function
    Private Function _ParseValueString(ByVal valValues As String) As TList
        Dim isSingleBackslash As Boolean
        Dim currentPosCtr As Int32
        Dim previousPosCtr As Int32
        Dim length As Int32
        Dim values As TList
        values = New TList
        Do While currentPosCtr < valValues.Length
            If (Not isSingleBackslash AndAlso valValues(currentPosCtr).Equals(","c)) OrElse currentPosCtr = valValues.Length - 1 Then
                If currentPosCtr = valValues.Length - 1 Then
                    length = currentPosCtr - previousPosCtr + 1
                Else
                    length = currentPosCtr - previousPosCtr
                End If
                values.Add(_converter.ReadAs(Of TItem)(valValues.Substring(previousPosCtr, length).Replace("\,", ",").Replace("\\", "\"), CultureInfo.InvariantCulture))
                previousPosCtr = currentPosCtr + 1
            End If
            If valValues(currentPosCtr).Equals("\"c) Then
                isSingleBackslash = Not isSingleBackslash
            ElseIf isSingleBackslash Then
                isSingleBackslash = False
            End If
            currentPosCtr += 1
        Loop
        Return values
    End Function
End Class

d. ConfigStringList in .resx file:
<assembly alias="NDToolsCommon0" name="NDToolsCommon0, Version=5.2.0.1, Culture=neutral, PublicKeyToken=null" />
<data name="FtpResponseDateTimeFormats" type="NDTools.Common.Programming.ConfigStringList, NDToolsCommon0">
    <value>yyyyMMddHHmm,yyyyMMddHHmmss</value>
</data>

e. Error for ConfigStringList value:

error MSB3103: Ungültige ResX-Datei. Der Typ NDTools.Common.Programming.ConfigStringList, NDToolsCommon0, Version=5.2.0.1, Culture=neutral, PublicKeyToken=null in den Daten in Zeile 401, Position 4, kann nicht gefunden werden. [english: Not valid Resx file. Type ... cannot be found.]

I've checked all namespaces. They are set correct. Same for assembly version.


text:
Q: Woocommerce function to display this custom field value on the order edit page we add option to add VAT number to checkout page, it shows ok on checkout page, in admin and in emails, but it don't save to custom fields.
Here is code:
/**
* VAT Number in WooCommerce Checkout
*/
function wpdesk_vat_field( $checkout ) {
    echo '

' . __('Nakup na podjetje') . '
';

    woocommerce_form_field( 'vat_number', array(
        'type'          => 'text',
        'class'         => array( 'vat-number-field form-row-wide') ,
        'label'         => __( 'V kolikor nakupujete kot podjetje, vnesite ID za DDV' ),
        'placeholder'   => __( 'Vnesite ID za DDV' ),
    ), $checkout->get_value( 'vat_number' ));

    echo '
';
}
add_action( 'woocommerce_checkout_update_order_meta', 'wpdesk_checkout_vat_number_update_order_meta' );
/**
* Save VAT Number in the order meta
*/
function wpdesk_checkout_vat_number_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['vat_number'] ) ) {
        update_post_meta( $order_id, '_vat_number', sanitize_text_field( $_POST['vat_number'] ) );
    }
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wpdesk_vat_number_display_admin_order_meta', 10, 1 );
/**
 * Display VAT Number in order edit screen
 */
function wpdesk_vat_number_display_admin_order_meta( $order ) {
    echo '
' . __( 'ID za DDV', 'woocommerce' ) . ': ' . get_post_meta( $order->id, '_vat_number', true ) . '
';
}
add_filter( 'woocommerce_email_order_meta_keys', 'wpdesk_vat_number_display_email' );
/**
* VAT Number in emails
*/
function wpdesk_vat_number_display_email( $keys ) {
     $keys['ID za DDV'] = '_vat_number';
     return $keys;
}

A: I add this code to functions.php, but VAT number is not saved to custom fields on order page.
/**
* VAT Number in WooCommerce Checkout
*/
function wpdesk_vat_field( $checkout ) {
    echo '

' . __('Nakup na podjetje') . '
';

    woocommerce_form_field( 'vat_number', array(
        'type'          => 'text',
        'class'         => array( 'vat-number-field form-row-wide') ,
        'label'         => __( 'V kolikor nakupujete kot podjetje, vnesite ID za DDV' ),
        'placeholder'   => __( 'Vnesite ID za DDV' ),
    ), $checkout->get_value( 'vat_number' ));

    echo '
';
}
add_action( 'woocommerce_checkout_update_order_meta', 'wpdesk_checkout_vat_number_update_order_meta' );
/**
* Save VAT Number in the order meta
*/
function wpdesk_checkout_vat_number_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['vat_number'] ) ) {
        update_post_meta( $order_id, '_vat_number', sanitize_text_field( $_POST['vat_number'] ) );
    }
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wpdesk_vat_number_display_admin_order_meta', 10, 1 );
/**
 * Display VAT Number in order edit screen
 */
function wpdesk_vat_number_display_admin_order_meta( $order ) {
    echo '
' . __( 'ID za DDV', 'woocommerce' ) . ': ' . get_post_meta( $order->id, '_vat_number', true ) . '
';
}
add_filter( 'woocommerce_email_order_meta_keys', 'wpdesk_vat_number_display_email' );
/**
* VAT Number in emails
*/
function wpdesk_vat_number_display_email( $keys ) {
     $keys['ID za DDV'] = '_vat_number';
     return $keys;
}

A: I am using your code in addition I used the woocommerce_before_order_notes hook to add files and working fine for me.
/**
 *
* VAT Number in WooCommerce Checkout
*/
add_action( 'woocommerce_before_order_notes', 'wpdesk_vat_field' );

function wpdesk_vat_field( $checkout ) {
    echo '

' . __('Nakup na podjetje') . '
';

    woocommerce_form_field( 'vat_number', array(
        'type'          => 'text',
        'class'         => array( 'vat-number-field form-row-wide') ,
        'label'         => __( 'V kolikor nakupujete kot podjetje, vnesite ID za DDV' ),
        'placeholder'   => __( 'Vnesite ID za DDV' ),
    ), $checkout->get_value( 'vat_number' ));

    echo '
';
}
add_action( 'woocommerce_checkout_update_order_meta', 'wpdesk_checkout_vat_number_update_order_meta' );
/**
* Save VAT Number in the order meta
*/
function wpdesk_checkout_vat_number_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['vat_number'] ) ) {
        update_post_meta( $order_id, '_vat_number', sanitize_text_field( $_POST['vat_number'] ) );
    }
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wpdesk_vat_number_display_admin_order_meta', 10, 1 );
/**
 * Display VAT Number in order edit screen
 */
function wpdesk_vat_number_display_admin_order_meta( $order ) {
    echo '
' . __( 'ID za DDV', 'woocommerce' ) . ': ' . get_post_meta( $order->id, '_vat_number', true ) . '
';
}
add_filter( 'woocommerce_email_order_meta_keys', 'wpdesk_vat_number_display_email' );
/**
* VAT Number in emails
*/
function wpdesk_vat_number_display_email( $keys ) {
     $keys['ID za DDV'] = '_vat_number';
     return $keys;
}

Tested and works.
Checkout

Edit Order

Mail


text:
Q: Java: ClassNotFoundException on class from external jar being instantiated in a thread I have made a library and exported it to a jar file that I am trying to import into my eclipse project and use. Eclipse says there's no problems but when I debug the application, it enters the new thread and goes to instantiate the object but then throws a ClassNotFoundException

ClassNotFoundException(Throwable).(String, Throwable) line: 217
  ClassNotFoundException(Exception).(String, Throwable) line: not
  available  ClassNotFoundException.(String) line: not available
  URLClassLoader$1.run() line: not available
  AccessController.doPrivileged(PrivilegedExceptionAction,
  AccessControlContext) line: not available [native method]
  Launcher$ExtClassLoader(URLClassLoader).findClass(String) line: not
  available  Launcher$ExtClassLoader.findClass(String) line: not
  available  Launcher$ExtClassLoader(ClassLoader).loadClass(String,
  boolean) line: not available
  Launcher$AppClassLoader(ClassLoader).loadClass(String, boolean) line:
  not available  Launcher$AppClassLoader.loadClass(String, boolean)
  line: not available
  Launcher$AppClassLoader(ClassLoader).loadClass(String) line: not
  available  HKServiceListener.run() line: 33    Thread.run() line: not
  available

The class it's not finding is com.snow.IO.SnowTcpServer. I have included the external jar in my class path and have no compile errors. It only throws at runtime. I even have import com.snow.IO.SnowTcpServer at the top of the file like it should.
Why is it not recognizing my class and how do I get it to do so?

A: You have problems with your classpath there is no other reason why classload can't find file with your class, try to run your class (compiled class) manually  without eclipse using command line
java -cp [your jars separated with ";" - widows or ":" - *nix] com.your.Class

For example:
java -cp /libs/lib1.jar:/libs2/* com.your.Class

A: If you are running a Enterprise application, please make sure, the Jar is available for deployment also. This needs to be configured additionally.
In case of J2SE application, please check if your jar is visible in run_configuration properties, classpath tab.
If this does not work, then try including the jar file in class path option in the run_configurations option explicitly.

A: As it turns out, the error was only caused when using the debugger. It had to do with the fact that the code I was stepping into was in an external jar file and not in my source.


text:
Q: α-LMS algorithm setback issue I'm using α-LMS algorithm to make a classifier for MNIST dataset.
I only update the weights when predicted output does not match the desired output and here's how the weights are updated:

I expect the residual error to go down (and accuracy to go up) on each iteration (shouldn't I?).
Although the overall accuracy seems to be going upward, on some iterations the algorithm sets back.

I need to know if it is normal for the setbacks to happen in this algorithm and if it is why so?

A: If the data could be represented by a formula, it would be feasible to find that formula.
When an algorithm is needed (no formula), the speed of convergence and accuracy depends strongly on data. If you are able to use several datasets you'll see different graphs.


text:
Q: Android local notification does not fire after system reboot I implemented some notifications that fire on specific date and time. My code works if phone is not rebooted after app installation, but if I reboot the phone the notifiction does not fire. I tried many methods proposed by other developers, but nothing changed. Is it possible to restart notification service automatically on system reboot?

BootService.java

package com.example.is2_app.utility;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;

import java.util.Calendar;

import static java.util.Calendar.APRIL;

public class BootService extends JobIntentService {

    @Override
    public void onCreate() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        intent = new Intent(this, ReminderBroadcast.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
        calendar.add(Calendar.DAY_OF_YEAR,-1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 9);
        calendar.set(Calendar.SECOND, 40);

        if(calendar.getTimeInMillis()>System.currentTimeMillis()) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

        }

        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {

    }
}

ReminderBroadcast.java

package com.example.is2_app.utility;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.core.app.NotificationCompat;

import com.example.is2_app.MainActivity;
import com.example.is2_app.R;

public class ReminderBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        showNotification(context);
    }

    void showNotification(Context context) {
        String CHANNEL_ID = "your_name";// The id of the channel.
        CharSequence name = context.getResources().getString(R.string.app_name);// The user-visible name of the channel.
        NotificationCompat.Builder mBuilder;
        Intent notificationIntent = new Intent(context, MainActivity.class);

        long when = System.currentTimeMillis();
        Bundle bundle = new Bundle();
        notificationIntent.putExtras(bundle);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startService(notificationIntent);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= 26) {
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
            mNotificationManager.createNotificationChannel(mChannel);
            mBuilder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher_candida)
                    .setLights(Color.RED, 300, 300)
                    .setChannelId(CHANNEL_ID);
        } else {
            mBuilder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher_candida)
                    .setPriority(Notification.PRIORITY_DEFAULT);
        }
        mBuilder.setContentTitle(context.getString(R.string.spazzatura));
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.spazzatura_residuo)));
        mBuilder.setContentText(context.getString(R.string.spazzatura_residuo));
        mBuilder.setAutoCancel(true).setWhen(when);
        mNotificationManager.notify(1, mBuilder.build());
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.is2_app">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:name=".global.Global"
        android:allowBackup="true"
        android:configChanges="locale|orientation|keyboardHidden|screenSize"
        android:icon="@mipmap/ic_launcher_candida"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_candida_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <service
            android:name=".utility.BootService"
            android:enabled="true"
            android:exported="true" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".utility.ReminderBroadcast"
            android:permission = "android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>


text:
Q: Define MYSQL query according to values sent from another page I am trying to set a MYSQL query based on the presence (or absence) of values sent across from a parent page via the URL. The variables are the following:
        $startdate = $_GET["selectstartdate"];
        $enddate = $_GET["selectenddate"];
        $ensemble = $_GET["selectensemble"];
        $venue = $_GET["selectvenue"];
        $city = $_GET["selectcity"];

The first two will ALWAYS be non-NULL, but the remaining three have a default value of NULL, which may or may not be redefined on the parent page. So, what I need to do is to restructure my SQL query, according to which of these variables I receive.
IF only the first two variables are sent (and all others are NULL), then the following query is correct:
        $sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map
                FROM Concert, Ensemble, Venue
                WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
                AND Concert.date BETWEEN '$startdate' AND '$enddate'";

However, if for example $ensemble is not NULL, then I would need an extra line added to my query:
                AND Ensemble.short_name='$ensemble';

Similarly, if $venue is not NULL, then I would need:
                AND Venue.name='$venue';

...and, of course, if $city is not NULL, then I would need:
                AND Venue.city='$city';

I am really what the best way to go about this is. Many thanks in advance for your help!

A: Here is your answer to manage your where conditions in simpler way:
<?php
// note that this mysqli_real_escape_string will prevent sql injection and $con is your connection variable
$startdate = mysqli_real_escape_string($con, $_GET["selectstartdate"]);
$enddate = mysqli_real_escape_string($con, $_GET["selectenddate"]);
$ensemble = mysqli_real_escape_string($con, $_GET["selectensemble"]);
$venue = mysqli_real_escape_string($con, $_GET["selectvenue"]);
$city = mysqli_real_escape_string($con, $_GET["selectcity"]);

$sql = "SELECT Concert.date, Ensemble.long_name, Concert.title, ensemble_web, Concert.info, Concert.repertoire, Venue.name, venue_web, Venue.address, Venue.city, Venue.map
        FROM Concert, Ensemble, Venue
        WHERE Concert.ensemble_id = Ensemble.id AND Concert.venue_id = Venue.id
        AND Concert.date BETWEEN '$startdate' AND '$enddate'";
$where_clause = ["Concert.ensemble_id = Ensemble.id", "Concert.venue_id = Venue.id", "Concert.date BETWEEN '$startdate' AND '$enddate'"];

if(!empty($ensemble)) {
    $where_clause[] = "Ensemble.short_name='$ensemble'";
}

if(!empty($venue)) {
    $where_clause[] = "Venue.name='$venue'";
}

if(!empty($city)) {
    $where_clause[] = "Venue.city='$city'";
}

$sql .= " WHERE " . implode(" AND ", $where_clause);


text:
Q: Transforming matrix element for Coulomb interaction from position to momentum space I'm stuck with the Dirac notation in this calculation. I have the Coulomb interaction given by the matrix $$\langle x|V|x' \rangle = V(|x-x'|) = \frac{1}{|x-x'|}$$
and I want to go to the momentum representation, i.e. calculate $\langle k|V|k' \rangle$. I wrote
$$\langle k|V|k' \rangle= \iint d^3x d^3x' \langle k | x \rangle \langle x | V | x' \rangle \langle x'|k' \rangle$$
where I know that $\langle k | x \rangle = e^{-ik\cdot x}$, but this doesn't get me anywhere. I don't know how to simplify the double integral. I'm supposed to get $\langle k|V|k' \rangle = 4\pi\delta(k-k')/k^2$, but I can't proceed.

A: Take the equation that defines the Green's function for the 3-dimensional negative Laplace operator:$$-\nabla^2 G(\mathbf{x}, \mathbf{x}') = \delta(\mathbf{x}-\mathbf{x}'),$$ Fourier transform both sides with respect to both $\mathbf{x}$ and $\mathbf{x}'$ to get:
$$\mathbf{k}^2 G(\mathbf{k}, \mathbf{k}') = \delta(\mathbf{k}-\mathbf{k}'),$$ and note that in this case $$G(\mathbf{x},\mathbf{x}') = \frac{1}{4\pi|\mathbf{x}-\mathbf{x}'|}.$$ You also need to note that $\mathbf{x}$ and $\mathbf{x}'$ Fourier transform with opposite senses, as implied by your second equation.

A: Yes, this is a very heavy calculation that I once struggled through myself...
If you want to arrive at the desired result from your definitions and notations above, you must do the following:
First normalize your plane-waves properly... Note the translation-invariance of the Coulomb-potential in position space and make use of it by shifting the intregrand in your expression. Performing one integral over position-space will give you the desired Kronecker-delta. After that, you are left with one three-dimensional integral, and all you have to do is follow the lines of this calculation (i.e. disturbing the integrand a little bit to perform the integral to arrive at the final result...)


text:
Q: Downgrade Angular route component Bit of an odd question. I have a massive AngularJS directive that should be entirely re-written. The challenge is too great to do it all at once. I was wondering if there is a way to downgrade a route component in AngularX to load in this AngularJS directive without refactoring it yet. I cannot find any details on this.
Downgrading the angular component allows me to use something called projections which is the equivelant to AngularJS' transclusion.
I have tried many approaches, but my best shot was the following:
// component
@Component({
    selector: "some-component",
    templateUrl: "./some.component.html",
})
export class SomeComponent{}

// routes
{ path: "some-route", component: SomeComponent}

// downgrades
import { downgradeComponent } from "@angular/upgrade/static";
import {SomeComponent} from "./some-location"

angular.module("somemodule").directive(
    "someComponent",
    downgradeComponent({ component: SomeComponent })
)

So far no luck. Since the Application is pretty big. This would make perfect little commits to work towards a migrated system. If the names do not match. The application will break because it cannot find the directive name.
If the downgrade worked, one would expect angularjs components to work on the route.

A: After some more digging, this would never work. I ended up just upgrading the directive using the UpgradeComponent class: https://angular.io/api/upgrade/static/UpgradeComponent
downside is that it added a lot of boilerplate by creating a wrapper.


text:
Q: Foreach loop does not compare I am somewhat of a programming noob, and i was stuck with an issue trying to echo out only a few items of my array instead of all the items in the array.
So what i have is a products.php file that contains my array $products, i am now trying to call this array from my index page, and i want to not only call the array, but to have the products in the array to list the last 4 products instead of all of them.
so now in my index.php i have created this code:
$total_products = count($products);
$position = 0;
$list_view_html = "";
foreach($products as $product_id => $product) {
$position = $position + 1;
if($total_product - $position < 4){
$list_view_html = $list_view_html . get_list_view_html($product_id,$product);
}
}
echo $list_view_html;

now when i save and load the webpage, i still see all the products listed and not the 4 i should be seeing.
from what i understand, i am counting the products in the array, starting the loop at 0, looping through the array and then increment up the count +1. i then am stating that if the products in the loops position is less than the 4 items i want to be shown.
i know the code might not be the best way efficiency wise, or that it has certain critiques. I appreciate all the help, but i just need to figure out why i cant get this to work.
any help is appreciated, the less condescending the better.
thanks guys

A: That seems a very complicated way to get the last 4 items.
I would recommend using array_slice:
$last_four = array_slice($products, 0, -4);

and a simple foreach loop.

A: This is a typo. Change the if to:
if($total_products - $position < 4){

Note that the var's name is $total_products . You are using $total_product without the 's' and the end.


text:
Q: How can I make the viewport size change when the user pinch zooms on the mobile screen? I have a responsive website which behaves properly on different screen sizes. On a desktop browser, when I zoom in (making the viewport smaller) or out (making the viewport larger), the layout renders properly on the adjusted viewport.
However, when I pinch zoom in on the mobile device, it seems that the viewport size doesn't change, that I still need to scroll horizontally to view the content, and I can't pinch zoom out to increase the viewport size at all.
What should I write in my HTML or CSS in order to make the viewport size change while pinch zooming in or out on the mobile screen, such that the physical viewport is always equals to the screen size no matter the zoom ratio?


text:
Q: How to scrub a dynamic python dictionary of specific keys? This one is just obtuse enough that no typical answer is bubbling to the top.
The nature of the tool I'm working on dictates we use MongoDB to store 'settings' for about 25 different tools.  Each tool has it's own settings schema, so each document is different, but they're all stored in the same collection and edited on the same edit page which is drawn by json schema.
Not knowing the schema of the dictionary, I'm struggling to figure out how to iterate and sanitize the data, specifically removing passwords.
Given the following dictionary, and knowing that other dicts may have different schemas, how could I traverse every single item in the dict and create a copy, identical except with any key == "password" removed?
So:
{
  "_enabled": true,
  "instances": [
    {
      "isdefault": true,
      "name": "dev",
      "password": "abc123",
      "url": "http://dev.example.com",
      "user": "buffy"
    },
    {
      "isdefault": false,
      "name": "prod",
      "password": "xxxxx",
      "url": "http://prod.example.com",
      "user": "spike"
    },
    {
      "isdefault": false,
      "name": "qa",
      "password": "dasddf",
      "url": "http://prod.example.com",
      "user": "willow"
    }
  ],
  "label": "MyServers"
}

Should result in:
{
  "_enabled": true,
  "instances": [
    {
      "isdefault": true,
      "name": "dev",
      "url": "http://dev.example.com",
      "user": "buffy"
    },
    {
      "isdefault": false,
      "name": "prod",
      "url": "http://prod.example.com",
      "user": "spike"
    },
    {
      "isdefault": false,
      "name": "qa",
      "url": "http://prod.example.com",
      "user": "willow"
    }
  ],
  "label": "MyServers"
}

A: deepcopy the dict first, then catch all the dictionaries and remove the password keys:
from copy import deepcopy

def remove_pass(v):
    if isinstance(v, dict):
        if "password" in v:
            del v["password"]
        for ele in v.values():
            remove_pass(ele)
    elif isinstance(v, Iterable) and not isinstance(v, basestring):
        for ele in v:
            remove_pass(ele)

from pprint import pprint as pp
d = deepcopy(d)
for v in d.values():
   remove_pass(v)

Input:
{'_enabled': 'true',
 'foo': {'isdefault': 'false',
         'name': 'qa',
         'nested': {'password': 'nested'},
         'password': 'dasddf',
         'url': 'http://prod.example.com',
         'user': 'willow'},
 'instances': [{'isdefault': 'true',
                'name': 'dev',
                'password': 'abc123',
                'url': 'http://dev.example.com',
                'user': 'buffy'},
               {'isdefault': 'false',
                'name': 'prod',
                nested': {'more_nesting': {'even_more_nesting': ({'password': 'foobar'},
                                       {'password': 'foob'}),
                                        'password': 'bar'},
                'password': 'xxxxx',
                'url': 'http://prod.example.com',
                'user': 'spike'},
               {'isdefault': 'false',
                'name': 'qa',
                'password': 'dasddf',
                'url': 'http://prod.example.com',
                'user': 'willow'}],
 'label': 'MyServers'}

Output:
{'_enabled': 'true',
 'foo': {'isdefault': 'false',
         'name': 'qa',
         'nested': {},
         'url': 'http://prod.example.com',
         'user': 'willow'},
 'instances': [{'isdefault': 'true',
                'name': 'dev',
                'url': 'http://dev.example.com',
                'user': 'buffy'},
               {'isdefault': 'false',
                'name': 'prod',
                'nested': {'more_nesting': {'even_more_nesting': ({}, {})}},
                'url': 'http://prod.example.com',
                'user': 'spike'},
               {'isdefault': 'false',
                'name': 'qa',
                'url': 'http://prod.example.com',
                'user': 'willow'}],
 'label': 'MyServers'}

A: Assuming you only want to check containers which are lists or dictionaries and remove key value pairs from dictionary entries which have the key = "password"
#first copy the structure
new_data = copy.deepcopy(data)

#this is a recursive function.
#Heavily nested structures may fail due to recursion limit
def clean_hierarchy(ele):
    #lists may contain dictionaries, so clean theses entries
    if isinstance(ele,list):
        for val in ele:
            clean_hierarchy(val)
    if isinstance(ele,dict):
        #remove possible password entry
        if "password" in ele:
            ele.pop("password",None)
        #dictionary may contain more dictionaries. Rinse and repeat!
        for val in ele.values():
            clean_hierarchy(val)

clean_hierarchy(new_data)

A: If you knew the structure of each of your data (i.e., at what depth of an array/dictionary to expect the "password" key), this would be simple. You'd simply need to loop through your list items and dictionaries to find the "password" key.
If the structure of each settings dictionary is truly unpredictable, you'll have to hack together a solution. What I've done in cases like this is dump my JSON to a string, use regex to remove/isolate the data I'm interested in and then load the string back to structured JSON.
Something like this:
import json, re
raw_data = """{
  "_enabled": true,
  "instances": [
    {
      "isdefault": true,
      "name": "dev",
      "password": "abc123",
      "url": "http://dev.example.com",
      "user": "buffy"
    },
    {
      "isdefault": false,
      "name": "prod",
      "password": "xxxxx",
      "url": "http://prod.example.com",
      "user": "spike"
    },
    {
      "isdefault": false,
      "name": "qa",
      "password": "dasddf",
      "url": "http://prod.example.com",
      "user": "willow"
    }
  ],
  "label": "MyServers"
}"""

# I load and then dump my raw_data just to iron out any inconsistencies
# in formatting before applying regex. i.e., inconsistent use of " instead of '
structured_data = json.loads(raw_data)
dumped_data = json.dumps(structured_data)

scrubbed = re.sub(r'"password": ".*?",', '', dumped_data)
structured_scrubbed = json.loads(scrubbed)

Results in:
structured_scrubbed = {'_enabled': True,
 'instances': [{'isdefault': True,
                'name': 'dev',
                'url': 'http://dev.example.com',
                'user': 'buffy'},
               {'isdefault': False,
                'name': 'prod',
                'url': 'http://prod.example.com',
                'user': 'spike'},
               {'isdefault': False,
                'name': 'qa',
                'url': 'http://prod.example.com',
                'user': 'willow'}],
 'label': 'MyServers'}

A: I use a general function getPaths to find the path of a specific key in a nested dictionary. You can use that to go ahead and find all the paths to your "password" key and then change it, or delete it. This works for all formats/schemas of the json string.
def getPaths(dictionary, searchKey):
    '''
    generator to get all paths for the key in the nested dictionary

    '''
    for k, v in dictionary.items():
        if k == searchKey :
            yield []
        elif isinstance(v, dict):
            # if the value if dict, go in recursively and yield the path
            for subkey in getPaths(v, searchKey):
                yield [k]+subkey
        elif isinstance(v, list):
            # if value is a list, for each element in the list, go in recursively and yield the path
            for i, item in enumerate(v):
                if isinstance(item, dict):
                    for subkey in getPaths(item, searchKey):
                        yield [k]+[i]+subkey

jsonstring = """{
  "_enabled": true,
  "instances": [
    {
      "isdefault": true,
      "name": "dev",
      "password": "abc123",
      "url": "http://dev.example.com",
      "user": "buffy"
    },
    {
      "isdefault": false,
      "name": "prod",
      "password": "xxxxx",
      "url": "http://prod.example.com",
      "user": "spike"
    },
    {
        "instance2": {
                      "isdefault": false,
                      "name": "qa",
                      "password": "dasddf",
                      "url": "http://prod.example.com",
                      "user": "willow"
                      }
    }
  ],
  "label": "MyServers"
}"""
import json
jsonObj = json.loads(jsonstring)

paths = getPaths(jsonObj , "password")
for path in paths:
    print('path:', path)

Result:
>>> path: ['instances', 0]
>>> path: ['instances', 1]
>>> path: ['instances', 2, 'instance2']


text:
Q: where can I find the official virtual box for ubuntu 13.10? where can I find the official virtual box for ubuntu 13.10?
I would like to run windows XP on it as the application I want to run needs .net 2.0

A: If you want to download the latest version 4.3.0, just as Babin said in his answer, you can download it from the VirtualBox site.  Make sure you download the right file for your architecture (32bit or 64bit).  Once downloaded, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, navigate to where the file was downloaded, probably the downloads folder, and run the command(s) below:
sudo dpkg -i <file_name>.deb

If you don't mind verison 4.2.16, then just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below:
sudo apt-get install virtualbox

A: At https://www.virtualbox.org/wiki/Linux_Downloads
-->> Ubuntu 13.04 ("Raring Ringtail")  i386 |  AMD64 Works Fine with 13.10
Ubuntu 12.10 ("Quantal Quetzal")  i386 |  AMD64 Doesn't, had some networks configuration problems in my case.

A: Install the dependency packages:
sudo apt-get install dkms

Add the Oracle PPA and public key:
wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add -

Add the VirtualBox repo on Ubuntu 13.10 Saucy Salamander and Linux Mint 16 Petra:
sudo sh -c 'echo "deb http://download.virtualbox.org/virtualbox/debian saucy contrib" >> /etc/apt/sources.list.d/virtualbox.list'

Install VirtualBox on Ubuntu and Linux Mint:
sudo apt-get update
sudo apt-get install virtualbox-4.3

A: Here u can Download the latest Virtualbox
Virtual Box official Download
Are u can get it from the Ubuntu software center too
Instead of using Virtual box use KVM its better than virtual box and good in speed


text:
Q: Xamarin Native Views in XAML doesn't show on IOS I tried to add a native view in a xamarin forms xaml file.
I have downloaded the example code from this page:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/native-views/xaml
Everything works file for Android and UWP. But for IOS, it can't display the native view, just a blank view.
I tried every example I can find on that page , turning out to the same result.
I'm using the latest version of VS 2017 and Xamarin.
Thanks for any suggestion.

A: This issue was caused by using Xamarin.forms 3.0.0, and a service release will be available for this soon.
Refer to here.


text:
Q: findViewById returning null CustomSource cadslib I've been trying to use the cardslib lirary in a project I'm working on. I'm trying to use Thumbnail with CustomSource. Everything works as expected. However, when I call findViewById in setupInnerViewElements method on my class that extends Card to find R.id.textview_oferta_preco, it returns null.
Bellow follow my classs and my layouts.
Activity:
public class MenuOpcoes extends AppCompatActivity implements OfertasFragment.OnFragmentInteractionListener, NoticiasFragment.OnFragmentInteractionListener{

private Drawer.Result result = null;
private AccountHeader.Result headerResult = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu_opcoes);

    headerResult = new AccountHeader()
            .withActivity(this)
            .withHeaderBackground(R.drawable.header)
            .addProfiles(
                    new ProfileDrawerItem().withName("Oswaldo Roberto Marques").withEmail("oswaldormarques@gmail.com").withIcon(getResources().getDrawable(R.drawable.profile))
            )
            .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                @Override
                public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
                    return false;
                }
            })
            .build();

    result = new Drawer()
            .withActivity(this)
            .withTranslucentStatusBar(false)
            .withActionBarDrawerToggle(true)
            .withAccountHeader(headerResult)
            .addDrawerItems(
                    new PrimaryDrawerItem().withName(R.string.drawer_item_listas).withIcon(FontAwesome.Icon.faw_list),
                    new PrimaryDrawerItem().withName(R.string.drawer_item_ofertas).withIcon(FontAwesome.Icon.faw_dollar),
                    new PrimaryDrawerItem().withName(R.string.drawer_item_noticias).withIcon(FontAwesome.Icon.faw_newspaper_o),
                    new SectionDrawerItem().withName(R.string.drawer_item_section_header),
                    new SecondaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog)
            )
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) {
                    if (drawerItem instanceof Nameable) {
                        String opcaoSelecionada = MenuOpcoes.this.getString(((Nameable) drawerItem).getNameRes());
                        FragmentTransaction transaction = getFragmentManager().beginTransaction();
                        if (opcaoSelecionada.equals("Ofertas")) {
                            Toast.makeText(MenuOpcoes.this, MenuOpcoes.this.getString(((Nameable) drawerItem).getNameRes()), Toast.LENGTH_SHORT).show();
                            OfertasFragment ofertasFragment = new OfertasFragment();
                            transaction.replace(R.id.home_layout_container, ofertasFragment);
                            transaction.addToBackStack("ofertas");
                        }
                        if (opcaoSelecionada.equals(R.string.drawer_item_noticias)) {
                            Toast.makeText(MenuOpcoes.this, MenuOpcoes.this.getString(((Nameable) drawerItem).getNameRes()), Toast.LENGTH_SHORT).show();
                            NoticiasFragment noticiasFragment = new NoticiasFragment();
                            transaction.replace(R.id.home_layout_container, noticiasFragment);
                            transaction.addToBackStack("noticias");
                        }
                        transaction.commit();
                    }
                }
            }).build();

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_menu_opcoes, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    //int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    //if (id == R.id.action_settings) {
    //    return true;
    //}

    //return super.onOptionsItemSelected(item);

    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onBackPressed() {
    //handle the back press :D close the drawer first and if the drawer is closed close the activity
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        this.finish();
    }
}

@Override
public void onFragmentInteraction(Uri uri) {

}

CustomSource:
public class OfertasCardCustomSource extends Card {

public OfertasCardCustomSource(Context context) {
    super(context);
    init();
}

public OfertasCardCustomSource(Context context, int innerLayout) {
    super(context, innerLayout);
    init();
}

private void init() {
    CardHeader header = new CardHeader(getContext());
    header.setButtonOverflowVisible(true);
    header.setTitle("Coca Cola 2,5L");
    addCardHeader(header);

    CardThumbnail thumbnail = new CardThumbnail(getContext());
    thumbnail.setDrawableResource(R.drawable.coca_cola_25l);
    addCardThumbnail(thumbnail);
}

@Override
public void setupInnerViewElements(ViewGroup parent, View view) {

    TextView title = (TextView) parent.findViewById(R.id.textview_oferta_preco);
    title.setText("R$ 4,25");

    TextView subtitle = (TextView) parent.findViewById(R.id.textview_oferta_mercado);
    subtitle.setText("Mercado Exemplo");

    RatingBar mRatingBar = (RatingBar) parent.findViewById(R.id.carddemo_gplay_main_inner_ratingBar);

    mRatingBar.setNumStars(5);
    mRatingBar.setMax(5);
    mRatingBar.setStepSize(0.5f);
    mRatingBar.setRating(4.7f);
}
}

Fragment Layout:

<ScrollView
    android:id="@+id/card_scrollview"
    style="@style/carddemo_default_container_padding"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Custom Source Thumbnail-->
        <TextView
            style="@style/Theme.Carddemo.TitleText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/secao_ofertas"/>

        <it.gmariotti.cardslib.library.view.CardViewNative
            android:id="@+id/carddemo_thumb_customsource"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/card_external"
            card:card_layout_resourceID="@layout/native_card_thumbnail_layout"/>
        <!-- Empty view-->
        <View
            android:layout_width="match_parent"
            android:layout_height="15dp"/>

    </LinearLayout>
</ScrollView>

CustomSource Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
>

<RatingBar
    android:id="@+id/carddemo_gplay_main_inner_ratingBar"
    style="@style/carddemo_myapps_main_inner_ratingbar"
    android:numStars="5"
    android:stepSize="1.0"
    android:layout_alignParentLeft="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/textview_oferta_preco"
    android:layout_width="wrap_content"
    android:textSize="12sp"
    android:textColor="@android:color/holo_green_light"
    android:layout_alignParentRight="true"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/textview_oferta_mercado"
    android:textSize="12sp"
    android:textColor="#BBB"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

I don't know what to do. I'm using Android Studio. Thank you.

A: When extending Card, you have to call super by passing the layout reference you want to inflate.
I see in your OfertasCardCustomSource class that you have two constructors, one of them receiving a variable innerLayout which is correctly passed to the super class and another constructor that does not set the layout.
Your problem is probably one of the following:

*

*You are not setting the layout in that constructor: you should do something like calling super(context, R.layout.the_layout_of_your_card) - check this reference for a more detailed example

*You are not calling the constructor that receives innerLayout anywhere

What I recommend you to do is either delete the constructor that does not receive a layout to be inflated or to pass a default value exactly as it is done in the link I left above.


text:
Q: iPhone 6 shows charging icon but not charging Recently my iPhone stopped charging at all. I took it to a local mobile shop in Pakistan; they changed my charger and it started charging, then all of a sudden it stopped. It shows the charging icon but the battery percentage was not increasing, rather decreasing.
They told me to change the port, so I did and now it is charging from only one side of the USB cable. I have tried different other cables as well and different other chargers too.

A: Maybe, the problem is that there is dirt/dust inside the connector (lightning) port.
Try cleaning with a toothpick (plastic is the best) to remove possible dirt from the port.

A: This is most likely the problem with the battery.Just get a new battery and it should be fine, no need to replace ic port


text:
Q: PHP DateInterval and modify does not advance time I have a series of seconds between events.
I want to calculate the time of the current event.
So I get the time when the process starts and add the seconds.
But this does not advance the minutes for some reason.
I have the following code:
$time = '2016-03-10 10:03:07';
$date_obj = new DateTime($time);

for ($i = 0; $i < 10; $i ++) {
    $date_obj->add(new DateInterval("PT20S"));
    // I also tried $date_obj->modify('+ 20 second");
    // but the result is the same.
    $time = $date_obj->format("H:m:s");
    echo $time . "<br>";
}

Which outputs:
10:03:27
10:03:47
10:03:07
10:03:27
etc
How can I add seconds so that it advances the minutes instead?
Tried this on my server and this PHP Fiddle, same result:
https://3v4l.org/oSCsk

A: You are echo'ing the month instead of the minute in this line:
$date_obj->format("H:m:s");

Try changing it to:
$date_obj->format("H:i:s");

More info about the accepted date format:
http://php.net/manual/en/function.date.php


text: Q: subscription based billing support in AWS How can I add subscription based billing support to an app running in the AWS. I know there are third party service providers, but could not find a service from AWS it self.


text:
Q: Kinematics problem regarding motion of a particle A particle of mass m moves on the $x$-axis as follows: it starts from rest at $t = 0$ from the point $x = 0$, and comes to rest at $t = 1$ at the point $x = 1$. No other information is available about its motion at intermediate times ( $0 < t < 1$).
If α denotes the magnitude of instantaneous acceleration of the particle, then which of the following is/are true?
(a) α cannot remain positive throughout
(b) α cannot exceed 2 at any point in its path
(c) α must be equal to 4 at some point or points in its path
(d) α must change sign during the motion, but no other assertion can be made with the information given
Obviously the a part is correct because the the particle has to deaccelerate to come to a stop.
i think one can do this by shm also but please give me the solution with the help of kinematics also. I dont understand why the c part is correct.

A: The answer is correct is you do not take into account the sign. Suppose that the acceleration were constant then $x=1/2 a t^2$, and to reach $x=1$ at $t=1$ then  $a=2$. Of course, in this example the mass did not stop, If it stops, it needs to descelerate. In the symmetrical case of constant accekeration and constant desceleration it is easy to see that the mass will need to accelerate on half of the time, so $a=4$ to get to the middle point in half a second and then $a=-4$ to make it stop. The same will happen if the motion is not uniform, a smaller acceleration forward for a longer time (let say a slightly larger than two until the last millisecond, must be compensated by a much larger desceleration at the last millisecond. Same for any other combination of acceleration/decelerations you could imagine, at some point either the acceleration of the deceleration must be at least 4.


text:
Q: How to convert from power signal received by Antenna to voltage signal? I am considering wireless transmission.
Let us define a cosine signal with frequency 2.4 GHz, i.e.
$$s(t) = A\cos(2\pi ft),$$ where $$f=2.4\times10^9.$$

Let us assume that when TX transmits the signal s(t) of power 50 W, RX receives the signal of power 0.5 W (that is, 49.5 W is attenuated in the air.)
Saying more detail, transmitted signal and received signal are, respectively,
$$s_{TX}(t)=10\cos(2\pi ft)$$ and $$s_{RX}(t) = \cos(2\pi ft).$$
Does the received signal represent voltage for load?
I mean, if load is 1 Ohm resistor, is the power for resistor $$P_{Load}=\int_{T}\frac{s_{RX}(t)^2}{1}dt=\frac{1}{2}=0.5 W\quad?$$
If so, if I use 0.1 ohm, the power will be 5 W? (Received power is just 0.5...)
Please someone teach me where I have misunderstanding

A: The antenna has a design output impedance, usually 50 ohms, it is NOT a voltage source, but appears to be a voltage source in series with a resistor equal to its designed output impedance.... All RF work is better thought of as power transfer rather then voltage transfer as impedance is so easy to change.
For maximum power transfer you need to have a load that matches the output impedance of the antenna (Graph the power in a load for a voltage source in series with a resistor driving a variable load and you will find that maximum power transfer occurs when the source and load impedance are equal, seriously worth taking the time to do this).
For sources having a complex source impedance the maximum power transfer occurs when the load is the complex conjugate of the source impedance.
Now one probably could design an antenna to match into 1 ohm, or 0.1 ohm, or 0.01 ohm (But things are getting VERY lossy because of secondary effects), but in all cases the power delivered will be equal (apart from the losses due to poor antenna efficiency), you will see much less voltage and more current as the system impedance drops.
Consider an antenna with a design output impedance of 1 ohm (Unlikely for all sorts of reasons, but go with it), model it as say a 1.414V voltage source in series with a 1 ohm resistor. Into a matched load (1 ohm) you get 0.707V (Voltage divider) and 0.707A, multiplying these gives you your 0.5W.
If you load this up into 0.1 ohms you get ~0.13V @ 1.3A = 0.169W, hardly an improvement.
Now a free space path loss of only 20dB seems unlikely to me, with a 1m separation and isotropic antennas for example you have ~40dB of path loss at 2.4GHz, and you can add 20dB for every decade of path length, so you might want to look at your numbers.

A: If your transmitting antenna has low losses and is driven at the right frequency it will emit power efficiently. A straightforward simple antenna like a dipole will emit power evenly in all directions in one plane and, it will emit zero power in other directions. I mention this to set the scene.
The electromagnetic power emitted is made from two fields and those two fields are an electric field and a magnetic field measured in volts per metre and amps per metre respectively. The power of these two fields is simply volt.amps per square metre i.e. we talk about power in watts per square metre and the square metre part does represent the watts that flow through the air per square metre.
However, as you get further from the transmit antenna the power per square metre drops with distance squared. Think of a light bulb emitting light in all directions - your eyes have a certain area with which to capture that power and if you move away from the light the power per square metre reduces.
So a transmit antenna transmits a fixed amount of power and the further you are away, you receive less of that power because it is spreading out. It isn't attenuating, it is spreading out.
Now think about your receive antenna and importantly, don't think of it as a wire, think of it as a collector of power with a certain area - this is called the aperture of the antenna and is measured in square metres. Up close to the transmit antenna the energy density is greater and more watts are packed into a given area. Further away there are fewer watts per square metre so your receiver (with a fixed aperture) cannot receive the same power.
If your receive antenna's aperture "collects" 0.5 watts at position A it will collect one quarter of that power at position 2A.
There is no trade off with load resistance - you get the power that is collected by the receive antennas aperture. If of course your receive antenna is up really close to the transmit antenna you are in, what is called, the "near field" and this is much less predictable - you get induction and electric coupling effects and you can, under the right situation "load" the transmit antenna and produce much more difficult to understand relationships.
So, if you are just talking about EM radiation from an antenna you are in, what is called, the far-field. This nominally begins about 1 wavelength from the transmit antenna so, at 2.4 GHz this is round about 10 cm.
So, what I've largely said above, is about far-field power transfer and not near-field stuff. In the far-field the power you get is immutable by impedances - the receive antenna can only "collect" what is delivered and that is nearly the end of the story however, if you don't provide the correct impedance to the antenna you won't maximize the power potential. Any antenna has an impedance and this is vastly frequency dependent so, you are limited even more.
In short, in the far-field you get what power you are given and, you have to match impedances to maximize that power.


text:
Q: Grails include custom script I have two script in my grails application, how can I need a target of a script into another one, how can I do it?
I tried doing:
includeTargets << grailsScript("FirstScript")

but grails throws an Exception...I tried also with:
includeTargets << FirstScript

but this one says that grails can't find the class...
How can I do?
Thanks

A: You need to shift in a file handle to the script:
includeTargets << new File("${basedir}/scripts/_FirstScript.groovy)


text:
Q: Pass a row record to Oracle procedure using System.Data.OracleClient I would like to pass 51 plus parameter to an oracle stored procedure, i would like to pass them as a collection/array or custom object. I know its possible using assiative arrays using ODP driver but I am using OracleClient. How will I be able to achieve this, would not like to pass 50 plus fields as individual parameters.

A: Pass a record as a string with values separated by a pipe (|) or any character of your choice.
On database end split the passed string values.
Not the optimal solution but it works.


text:
Q: Prove $\lim_{x\to\infty} \left( \sqrt{x+1} - \sqrt{x} \right) = 0$ My attempt: I tried manipulating the formula, but I couldn't do anything useful. I tried to find another function $f(x)$ such that $\lim_{x\to\infty} f(x) = 0$ and $f(x) \geq  \sqrt{x+1} - \sqrt{x} $ for all $x$. $f(x) = \frac1x$ fails but I think $f(x) = \frac{1}{\sqrt{x}}$ would work (not sure how to verify this). I'm not sure how to proceed.

A: Try multiplying your expression by $\frac{\sqrt{x + 1} + \sqrt{x}}{\sqrt{x + 1} + \sqrt{x}}$ and then simplify the numerator and take the limit of this new expression as $x \to \infty$.  What do you get?
Note that this is a common method for solving a problem like this.  We say $\sqrt{x + 1} + \sqrt{x}$ is the conjugate of $\sqrt{x + 1} - \sqrt{x}$.  The purpose of multiplying by this is that the numerator becomes the factored form of the difference of squares (recall: $(a + b)(a - b)= a^{2} - b^{2}$).  This gets rid of the square roots in the numerator and allows us to cancel the $x$'s.

A: For $x\ge 0$:
$\sqrt{1+x}-\sqrt{x}\le \dfrac{1}{\sqrt{x}}$
if and only if
$\sqrt{1+x}\le\sqrt{x}+\dfrac{1}{\sqrt{x}}$
if and only if
$1+x\le x+2+\dfrac{1}{x}$
if and only if
$0\le 1+\dfrac{1}{x}$
True.

A: Any differentiable function $f$ satisfying $\lim_{x\to \infty}f'(x)=0$ will also satisfy $\lim_{x\to \infty}(f(x+1)-f(x))=0.$ Proof: MVT

A: $$
0 < \sqrt{x+1} - \sqrt{x} = \int_x^{x+1} \frac1{2\sqrt{t}}dt \le \int_x^{x+1} \frac1{2\sqrt{x}}dt = \frac1{2\sqrt{x}} \rightarrow 0
$$
We have $\frac1{2\sqrt{t}} \le \frac1{2\sqrt{x}}$ because $\frac1{2\sqrt{t}}$ is a decreasing function on the interval.

A: $(x+\frac1{2x})^2
=x^2+1+\frac1{4x^2}
\gt x^2+1
$
so
$x+\frac1{2x}
\gt \sqrt{x^2+1}
$
so
$\sqrt{x^2+1}-x
\lt \frac1{2x}
$
so
$\sqrt{x+1}-\sqrt{x}
\lt \frac1{2\sqrt{x}}
$.


text:
Q: Parse error: syntax error, unexpected end of file in php file could you please tell what`s wrong with the end of this code and why it says: "Parse error: syntax error, unexpected end of file in php file":
<?php

define("DB_SERVER" , "localhost");
define("DB_USER" , "root");
define("DB_PASS" , "root");
define("DB_NAME" , "widget_corp");
?>
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <title> CMS MANAGEMENT </title>
    <link rel="stylesheet" type="text/css" href="stylesheets/style.css">

 widget Corp

<?php
require("constants.php");

// mysql connection
    $connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
    if (!$connection){
        die("Database Connection failed:". mysql_error());
    }

// select database
    $db_select = mysqli_select_db($connection , DB_NAME);
    if (!$db_select) {
        die("Database selection failed:" . mysql_error());
        }
    ?>

<?php

    $subject_set = mysqli_query($connection, "SELECT * FROM subjects" );
    if (!$subject_set){
        die("mysql failed" . mysql_error());
    }
        while ($subject = mysql_fetch_array($subject_set)){
        echo "
{$subject["menu_name"]}
";
    }
        $page_set = mysqli_query($connection, "SELECT * FROM pages WHERE subject_id = {$subject["id"]}");
            if (!$page_set){
                die("Database query failed: " . mysql_error);

        echo "
";
        while ($page = mysqli_fetch_array($page_set)){
            echo "
{$page["menu_name"]}
";
    }
    echo "
";

?>
    <?php echo "
"; ?>

    <?php mysqli_close($connection);?>

A: EDIT
I've also updated the code a little for formatting and you were missing a  tag.  Also, there's no point in echoing out the
 tag if you're not in the middle of a php block.

You are missing a bracket }.  I've added it after:
if (!$page_set){
                die("Database query failed: " . mysql_error);

<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/constants.php"); ?>
<?php include("includes/header.php"); ?>
<?php include("includes/connection.php"); ?>

            <?php
                $subject_set = mysqli_query($connection, "SELECT * FROM subjects" );
                if (!$subject_set){
                    die("mysql failed" . mysql_error());
                }

                while ($subject = mysql_fetch_array($subject_set)){
                    echo "
{$subject["menu_name"]}
";
                }

                $page_set = mysqli_query($connection, "SELECT * FROM pages WHERE subject_id = {$subject["id"]}");

                if (!$page_set){
                    die("Database query failed: " . mysql_error);
                }

                echo "
";
                while ($page = mysqli_fetch_array($page_set)){
                    echo "
{$page["menu_name"]}
";
                }
                echo "
";
            ?>

<?php mysqli_close($connection);?>


text:
Q: c++ array default parameter, while making function overloaded Lauguage : C++
I have to make function 'add' overloaded.
'add' function has array a[] as parameter.
I wrote my code but it doesn't work.
There is no error or caution but it doesn't start.
What is the problem on my code?
int add(int a[], int n, int b[])
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += (a[i] + b[i]);
    return sum;
}

int add(int a[], int n=5)
{
    return add(a, n, NULL);
}

A: When you declare arguments like array in the way you do (e.g. int a[]) then the compiler actually declares the argument to be a pointer.
And in the three-argument overload of the add function the third argument (b) could be a null pointer which you don't check for. Attempting to dereference a null pointer leads to undefined behavior and a probable crash.
Don't access b if it's a null pointer.

int add(int* a, int n, int* b)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        if (b == nullptr)
            sum += a[i];
        else
            sum += a[i] + b[i];
    }
    return sum;
}

A: sum += (a[i] + b[i]);

indexes b, which can be NULL. That's Undefined Behavior.
A good way to avoid that pitfall is to use std::vector.