text:
Q: How to show a request only one time if it repeat in every 200 milliseconds? I have some data in PHP which has been encoded in JSON format. I have used that data by using getJSON of jQuery. My code looks like this:
$(document).ready(function(){
    setTimeout(done,200);
});

function done() {
    setTimeout(updates, 200); // Call updates in 200ms
}

function updates(){
    $.getJSON("phpdata.php", function(data) {
        //some action..
    });
}

phpdata.php is the file which holds JSON encoded data. Now as you can see I have some functions which update my $.getJSON every 200 milliseconds. I did that to get changes to the data on the site from my database without a page refresh/reload. I know it does my work fine, but I have only one thing which I want to change if possible.
As I make a request using getJSON every 200 milliseconds, when I check on the 'Network' tab of 'Developer Tools', I can see the request repeating every 200 milliseconds which I feel is a little odd.
I don't know if it's bad for the site or browser. If it won't hamper on site and user browser then it's fine, but if it does then how? And if it is the case, can I remove the old requests automatically after the new one been created?

A: I don't really understand why every 200ms?! Bit excessive perhaps? However, something like an FX tracker would make a plausible use-case.
I suggest you use different technology though: WebSockets
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
http://socket.io/
P.s. the network tab is showing exactly what you are doing - i.e. a request every 200ms. You can't minify this into 1 entry.


text:
Q: C program in Windows to access the contents on the bus I have a zigbee usb dongle that plugs into the usb port on my Windows laptop. I need to be able to capture the incoming packets.
I am trying to write a c program that will capture the incoming packets by monitoring the bus associated with the corresponding usb port.
Are there some c libraries that facilitate this monitoring? If not how can I access the contents of the bus?

A: This is what a hardware driver does for you: it monitors low-level hardware directly, and then processes and exposes that data to user-level programs in a more convenient interface.
I think Telegesis and Adaptive offer Windows drivers for download; whoever manufactured your Zigbee should provide drivers of their own, if those aren't compatible.
Or you could write your own driver, but that is a very difficult and tricky piece of work not for the faint of heart.

A: You can easily read and write USB packets using libusb.  Normally I use libusb via the python wrappers pyUSB
However, do you actually have documentation on how to encode/decode the packet formats coming from your particular dongle?  The actual zigbee packets may be wrapped up in some proprietary protocol that you would need to be able to decode.
I am also assuming your USB dongle is actually communicating via raw USB, and not using an FTDI chip to create a virtual serial port over USB.  If that was the case, then you don't need to muck with USB, just use the virtual COM port for serial data.

A: It would be useful to open case of the dongle and take a look at the chips used (only do so if it's easy to open and you're comfortable with the idea).
You say it's Texas Instruments based: then it's probably running TI's Z-Stack firmware. If that's the case there is a good chance it's running the Z-Stack Monitor and Test API (search for document code SWRA198). You can easily write C/C++ to interact with that.
However your first hurdle is to be able to read/write to the device. If it has a FTDI chip then that's going to be easy: it should appear as a virtual comm port as mentioned in a previous post. A chip like the CC2531 is capable of connecting directly to the USB bus. I'm not familiar with that configuration. I've got one such dongle and they use some weird Texas Instruments serial-over-USB protocol. But if you get the right Windows driver it should appear as a regular comm port for applications to use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Não consigo realizar um RedirectToAction para uma Area Print do que já realizei, porém não funcionou, este é meu LoginController.

Minha estrutura, e estou tentando apontar para o PacienteController/Index:

Uma das outras opções que tentei, foi adicionar rotas em startups.cs.
app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Paciente}/{action=Index}/{id?}"
                );
            });

A: Vou mostrar o que eu fiz para funcionar, verifique no seu projeto:
Primeiro adicionar a rota no startup:
  app.UseMvc(routes =>
        {

            routes.MapRoute(
                    name: "MinhasAreas",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

Atribuir os controllers dentro de suas respectivas areas:
[Area("Paciente")]
public class PacienteController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        return View();
    }
}

Realizar o redirecionamento normalmente:
public class LoginController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult GravarCadastro(string perfil) {
        return RedirectToAction("Index", perfil, new { area = perfil });
    }
}

Adicionei o projeto no github para consulta, basta clicar em login e escolher o perfil para ser redirecionado:

Link do projeto:
https://github.com/superrfm/aspnetcore_areas


text: Q: Laravel Sancrum/Airlock I'm trying to host a Laravel API (Sever) project on Heruko along with Vue js project separately, 2 individual project. Is it possible to use laravel airlock/sanctum to authenticate user on the heruko free given domain?


text:
Q: Add to Lookup Column Values During Form Lifespan Has anyone ever successfully added a new item to a list which is used as the source for a lookup column while using an EditForm (or NewForm, same mechanism) and been able to save the form successfully with the new value?
Here's what I mean:

*

*I have a list called Regions with a lookup column called Country

*Country is a lookup into Countries.Title

*In my Regions EditForm, I've got a call to UpdateListItems using SPServices which adds a new value to Countries

*I add the new option to the Country dropdown (select) using the new ID and innerHTML and set it as "selected"

*When I save the Regions EditForm with the new value selected I get the dread "An unexpected error has occurred."

I've checked with Firebug and the correct ID for the newly created lookup value is what is sent with the POST, so I believe that my script is doing what it should.
I can still save the form with no problem if I select any of the previously existing lookup values. Only the new value throws the error.
I've fiddled with this too much. I'm wondering if SharePoint's trying to be "smart" here by only allowing values which existed when the form was originally loaded.
Any ideas?

A: After considerable work on this, testing over and over, and having a really interesting discussion (see the comments above), I am thoroughly convinced that this is not possible.
My current belief (I'd love it if someone could confirm or deny) is that something in the viewstate "tells" SharePoint something about the state things were in when the form loaded which prevents the new value from being acceptable.
I've moved on to other approaches to solve the particular client requirement which triggered this question, but if you have other ideas, please add them!

A: I have been successful doing this for most forms with the following code. This code is after you have done the mods to the lookup list and you are ready to save the form.

function PreSaveAction() {
    var qv = $().SPServices.SPGetQueryString();
    if (qv["PreSave"] == "skip") {
        return true;
    }
    else {
        var loc = new String(window.location);
        loc = loc.split("?");
        var formpage = loc[0];
        formpage += "?PreSave=skip";
        $("#aspnetForm").append("");
        $("#iframea").attr("src", formpage);
        setTimeout("copyfields()", 4000);
    }
}

function copyfields() {
    try
    {
        var i = 1;
        $("td.ms-formbody").each(function() {
            $(this).attr("id", "tdelement_" + i);
            i += 1;
        });
        i = 1;
        $("#iframea").contents().find("td.ms-formbody").each(function() {
            $(this).attr("id", "tdelement_" + i);
            i += 1;
        });
        for (var z = 1; z < i; z++) {
            var tid = "tdelement_" + z;
            $("#iframea").contents().find("td[id='" + tid + "']").html($("td[id='" + tid + "']").html());
        }
    }
    catch(e) {alert("Error " + e);}
    // Once copied submit the form and then redirect to the original source page.
    $("#iframea").contents().find("input[name*='SaveItem']").trigger('click');
    setTimeout("refreshpage()", 3000);
}

function refreshpage() {
    var qv = $().SPServices.SPGetQueryString();
    var source = new String(qv["Source"]);
    window.location = source;
}

This uses the presave action to create a hidden iframe. A new copy of the form is added to the frame and your selections are then copied to this hidden form. The code will then submit this form and reloads the page after a few seconds. I have tested this several times and it has worked each time. It is not perfect and I would like to find a way to make it cleaner, but it does work.

A: I believe that an out of box list form will have the issues described and it will not work because viewstate is enabled. Viewstate does store the valid values of a select and when you post back it will not accept an updated item. However, you can do this using SPDesigner and a custom form for the list. I created a list of categories and a list that used the categories list for a lookup fittingly called category. The list was called DataSourceTest and is just a custom list. In Designer I copied the NewForm.aspx page into a new file called NewFormTest.aspx and then removed the default listform. I added a SharePoint:SPDataSource element and an SharePoint:DVDropDownList to the form. The DataSource was set to the categories list and the DVDropDownList was bound to the category field and its EnableViewState property was set to FALSE (This is important!). I added a dummy dropdown that had some data that using SPServices would update the category list with a new category and return the new ID back to the form and then add this new item to the DVDropDownList. I could then save the form and it would post the changes including the updated value back to the list with no errors. This is not the most ideal solution I know, but it does work!

A: I solved this by adding a hidden ASP button on the form. I set UseSubmitBehavior="False" for that button but it still causes postback which in turn reloads the lookup list (which is what we want) while retaining form data. I invoke that button's click event with javascript after successfully adding a record to target lookup list with ajax. It causes validation as well so I set all fields to optional and made sure to validate their values using javascript in PreSaveAction() function. Quick and easy.


text:
Q: cannot load api descriptions from ../android-sdk/platform-tools/api/api-versions.xml java.io.IOException: Stream closed After I update android studio to v2020.3.1 (Arctic Fox). I can't run my project because I always get this error message.
cannot load api descriptions from ../Android/android-sdk/platform-tools/api/api-versions.xml java.io.IOException: Stream closed
I've tried to revert to v4.2.2, still getting the same error.
Note: I am using Ubuntu 20.04

A: I have encountered this problem recently as well and I have further investigated the issue, since I couldn't downgrade the platform-tools version (since it occurred on the build server, where I dont control the platform-tools version, its controlled by Microsoft).
Here are my findings:
This issue only arises in large Android projects, probably when there are multiple modules involved.
The cause of the issues are related to class SdkUtils (see the source file). The SdkUtils class has a hard reference to the file platform-tools/api/api-versions.xml, but with the latest platform-tools (31.0.3), this file is no longer there.
The fallback implemented in the SdkUtils class is that it will read the api-versions from the resources (by doing getClass().getClassLoader().getResource("api-versions.xml").openStream();). For small Android projects this is fine. But what I noticed is that with larger Android projects, with multiple modules / tasks being built in parallel, some of these streams get closed (hence the Stream Closed exception).
I raised an issue with google, and they're on it trying to fix it (see the issuetracker link here).
While Google is solving this issue the appropriate way, the easiest solution is to just downgrade your platform-tools 1 version (as stated in another answer).
However, if you, like me, do not control the platform-tools version (since it is managed by AzureDevops in my case), I created a temporary workaround. I added a bash task to my CI/CD pipeline where I copy the api-versions.xml file to platform-tools, so it will use that file instead of the resources.
It looks like so:
steps:
  - bash: |
    echo Android sdk location: $ANDROID_SDK_ROOT
    mkdir $ANDROID_SDK_ROOT/platform-tools/api/
    cp $ANDROID_SDK_ROOT/platforms/android-30/data/api-versions.xml $ANDROID_SDK_ROOT/platform-tools/api/

I copy from platforms/android-30/data/api-versions.xml, since that is file they will use in official fix by google as well (but then maybe not hardcoded android-30, but dynamically based on your build settings).

A: I found a solution! Turns out, I just need to downgrade the platform-tools in the SDK folder to v31.0.2.
We can download it on https://androidsdkmanager.azurewebsites.net/Platformtools.

A: I copied the contents of the file of this snippet:
https://gitlab.com/-/snippets/2164806
in the platform-tools directory it complains it can not load the /api/api-versions.xml and the error did not show up anymore.
There is no need to downgrade the platform-tools.

A: I am really not sure what caused this issue but Invalidating the caches and restarting AS has fixed the issue for me.
My wild guess is that AS Arctic Fox relies on JDK 11 to run and maybe the IDE was looking in the wrong jdk version


text:
Q: transform into if/else statement somehow this doesn't work:
if(direction != 'leftnav') direction = 'leftnav';
if(direction == 'leftnav') direction = 'rightie';

this always comes out as "rightie"
I tend to believe this is because they kind of overwrite. Can this be done with an if else statement?
thanks :)

A: !== and === are strict equality checks.
You probably just want !=, like the following:
if (direction != 'leftnav') {
  direction = 'leftnav';
}
else {
  direction = 'rightie';
}

Or better yet for these simple assignments, using a ternary operator:
direction = direction == 'leftnav' ? 'rightie' : 'leftnav';

A: Of course they overwrite, look at what you're doing there:
if(direction !== 'leftnav') direction = 'leftnav';
if(direction == 'leftnav') direction = 'rightie';

The first statement sets direction to 'leftnav' if it is anything else. So by the time you get to the second statement, direction will always be 'leftnav'. Did you mean to say else if rather than just if for the second?

A: Think about the logic you are asking for:
If it is not leftnav, then make it leftnav.
[Next statement -- after it has already been reassigned]
If it is leftnav, make it rightie.
You're looking for
if(direction !== 'leftnav') direction = 'leftnav';
else if(direction == 'leftnav') direction = 'rightie'; // can just be "else"


text:
Q: Obtener todos los valores 0 en consulta mysql estimados,
tengo un problema con una consulta porque no me muestra algunos datos con la consulta que tengo me muestra esta tabla

y esa tabla no me mustra id_pregunta 2,6,16,17 tipo 3,3,3,3 cantidad_respuesta 0,0,0,0
la consulta que genera eso es la siguiente:
SELECT p.id_pregunta, tr.tipo, COUNT(r.id_respuesta) as cantidad_respuestas
FROM preguntas p
LEFT JOIN tipo_respuesta tr on p.id_pregunta = tr.id_pregunta
LEFT JOIN respuesta r on tr.id_tipo = r.id_tipo
LEFT JOIN form_alumnos f on r.id_form_alumno_fk = f.id_form_alumno
WHERE (f.cod_curso_alumno = '354945' AND f.anio = '2016' AND f.semestre = 'Primer' or cod_curso_alumno IS NULL or anio IS NULL or semestre IS NULL)
AND (tr.tipo = '3')
GROUP BY p.id_pregunta, tr.tipo

y necesito que muestre esos datos para poder crear un arreglo de 21 y poder crear un grafico con esos datos.
Adjuntare la relación de la tablas

alguien me puede orientar o ayudar como poder obtener esos datos.

CREATE TABLE `form_alumnos` (
  `id_form_alumno` int(11) NOT NULL,
  `cod_curso_alumno` int(11) NOT NULL,
  `anio_ingreso` int(4) NOT NULL,
  `ua` int(3) NOT NULL,
  `cursos` varchar(50) CHARACTER SET ucs2 COLLATE ucs2_spanish_ci NOT NULL,
  `seccion` int(11) NOT NULL,
  `anio` set('2015','2016','2017','2018','2019') NOT NULL,
  `semestre` set('Primer','Segundo') NOT NULL,
  `id_encuesta_for` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `form_alumnos`
--

INSERT INTO `form_alumnos` (`id_form_alumno`, `cod_curso_alumno`, `anio_ingreso`, `ua`, `cursos`, `seccion`, `anio`, `semestre`, `id_encuesta_for`) VALUES
(1, 342139, 2012, 53, 'IN1083C', 1, '2016', 'Primer', 1),
(2, 342139, 2011, 53, 'IN1083C', 1, '2016', 'Primer', 1),
(3, 342139, 2011, 53, 'IN1083C', 1, '2016', 'Primer', 1),
(4, 342139, 2011, 53, 'IN1083C', 1, '2016', 'Primer', 1),
(5, 342139, 2011, 53, 'IN1083C', 1, '2016', 'Primer', 1),
(6, 342139, 2011, 53, 'IN1083C', 1, '2016', 'Primer', 1),
(7, 354945, 2012, 54, 'IN1228C', 1, '2016', 'Primer', 1),
(8, 354945, 2012, 54, 'IN1228C', 1, '2016', 'Primer', 1),
(9, 354945, 2012, 54, 'IN1228C', 1, '2016', 'Primer', 1),
(10, 354945, 2012, 54, 'IN1228C', 1, '2016', 'Primer', 1),
(11, 354945, 2012, 54, 'IN1228C', 1, '2016', 'Primer', 1),
(12, 354945, 2012, 54, 'IN1228C', 1, '2016', 'Primer', 1),
(14, 354945, 2012, 54, 'IN1228C', 1, '2016', 'Primer', 1);

CREATE TABLE `preguntas` (
  `id_pregunta` int(11) NOT NULL,
  `nombre` varchar(200) COLLATE utf8_spanish_ci NOT NULL,
  `id_dimension_p` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;

--
-- Volcado de datos para la tabla `preguntas`
--

INSERT INTO `preguntas` (`id_pregunta`, `nombre`, `id_dimension_p`) VALUES
(1, 'Trabajar en esta actividad me permitió poner en práctica conceptos teóricos vistos en clases en ésta u otras asignaturas.', 1),
(2, 'Pude apreciar la importancia de utilizar métodos y/o herramientas de la disciplina en el desarrollo de la actividad.', 1),
(3, 'Para entender el problema y proponer una solución tuve que buscar y analizar información de diferentes fuentes.', 2),
(4, 'Tuve la posibilidad de tomar decisiones y defenderlas ante mi equipo de trabajo.', 2),
(5, 'Para el éxito de la actividad de aprendizaje servicio tuve que trabajar de forma permanente y perseverar en el logro de los objetivos. ', 2),
(6, 'Esta actividad me ayudó a ser flexible y mejorar mi capacidad para adaptarme a los cambios.', 2),
(7, 'Trabajar en esta actividad me permitió identificar las fortalezas y debilidades de mis conocimientos técnicos.', 2),
(8, 'Esta actividad permitió darme cuenta de la importancia del autoaprendizaje en mi desarrollo profesional.', 2),
(9, 'Para el logro de los objetivos de la actividad  requerí gestionar de forma adecuada el tiempo y los recursos.', 2),
(10, 'Trabajar con la comunidad me permitió valorar la importancia del comportamiento ético en mi profesión.', 2),
(11, 'El desarrollo de esta actividad me fomentó mi compromiso con el respeto hacia los otros participantes.', 2),
(12, 'Trabajar con el socio comunitario me permitió vincularme con profesionales o personas de otras áreas y realidades.', 2),
(13, 'A través de esta actividad pude darme cuenta de la importancia de poder trabajar en equipo.', 3),
(14, 'A través de esta actividad pude mejorar mis competencias en comunicación oral y escrita.', 3),
(15, 'El uso de las tecnologías de información y comunicación (TIC's) favoreció el logro de los objetivos de la actividad.', 3),
(16, 'Tener definidos roles y responsabilidades de los integrantes del equipo de trabajo, fue fundamental para el desarrollo de la actividad.', 4),
(17, 'El desarrollo de esta actividad permitió darme cuenta del impacto de mi disciplina en la sociedad y medioambiente.', 4),
(18, 'A través de esta actividad pude conocer diferentes culturas organizacionales.', 4),
(19, 'Pude entender las necesidades del socio comunitario y a partir de ellas definir metas.', 4),
(20, 'La planificación, control y evaluación del desarrollo de la actividad favoreció el logro de los objetivos.', 4),
(21, 'Esta actividad permitió desarrollar mi capacidad de emprender e innovar.', 4);

CREATE TABLE `tipo_respuesta` (
  `id_tipo` int(11) NOT NULL,
  `id_pregunta` int(11) NOT NULL,
  `tipo` set('1','2','3','4','5') NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `tipo_respuesta`
--

INSERT INTO `tipo_respuesta` (`id_tipo`, `id_pregunta`, `tipo`) VALUES
(100, 20, '5'),
(99, 20, '4'),
(98, 20, '3'),
(97, 20, '2'),
(96, 20, '1'),
(95, 19, '5'),
(94, 19, '4'),
(93, 19, '3'),
(92, 19, '2'),
(91, 19, '1'),
(90, 18, '5'),
(89, 18, '4'),
(88, 18, '3'),
(87, 18, '2'),
(86, 18, '1'),
(85, 17, '5'),
(84, 17, '4'),
(83, 17, '3'),
(82, 17, '2'),
(81, 17, '1'),
(80, 16, '5'),
(79, 16, '4'),
(78, 16, '3'),
(77, 16, '2'),
(76, 16, '1'),
(75, 15, '5'),
(74, 15, '4'),
(73, 15, '3'),
(72, 15, '2'),
(71, 15, '1'),
(70, 14, '5'),
(69, 14, '4'),
(68, 14, '3'),
(67, 14, '2'),
(66, 14, '1'),
(65, 13, '5'),
(64, 13, '4'),
(63, 13, '3'),
(62, 13, '2'),
(61, 13, '1'),
(60, 12, '5'),
(59, 12, '4'),
(58, 12, '3'),
(57, 12, '2'),
(56, 12, '1'),
(55, 11, '5'),
(54, 11, '4'),
(53, 11, '3'),
(52, 11, '2'),
(51, 11, '1'),
(50, 10, '5'),
(49, 10, '4'),
(48, 10, '3'),
(47, 10, '2'),
(46, 10, '1'),
(45, 9, '5'),
(44, 9, '4'),
(43, 9, '3'),
(42, 9, '2'),
(41, 9, '1'),
(40, 8, '5'),
(39, 8, '4'),
(38, 8, '3'),
(37, 8, '2'),
(36, 8, '1'),
(35, 7, '5'),
(34, 7, '4'),
(33, 7, '3'),
(32, 7, '2'),
(31, 7, '1'),
(30, 6, '5'),
(29, 6, '4'),
(28, 6, '3'),
(27, 6, '2'),
(26, 6, '1'),
(25, 5, '5'),
(24, 5, '4'),
(23, 5, '3'),
(22, 5, '2'),
(21, 5, '1'),
(20, 4, '5'),
(19, 4, '4'),
(18, 4, '3'),
(17, 4, '2'),
(16, 4, '1'),
(15, 3, '5'),
(14, 3, '4'),
(13, 3, '3'),
(12, 3, '2'),
(11, 3, '1'),
(10, 2, '5'),
(9, 2, '4'),
(8, 2, '3'),
(7, 2, '2'),
(6, 2, '1'),
(5, 1, '5'),
(4, 1, '4'),
(3, 1, '3'),
(2, 1, '2'),
(1, 1, '1'),
(105, 21, '5'),
(104, 21, '4'),
(103, 21, '3'),
(102, 21, '2'),
(101, 21, '1');

CREATE TABLE `respuesta` (
  `id_respuesta` int(11) NOT NULL,
  `id_tipo` int(11) NOT NULL,
  `id_form_alumno_fk` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `respuesta`
--

INSERT INTO `respuesta` (`id_respuesta`, `id_tipo`, `id_form_alumno_fk`) VALUES
(1, 4, 1),
(2, 9, 1),
(3, 14, 1),
(4, 19, 1),
(5, 21, 1),
(6, 29, 1),
(7, 34, 1),
(8, 39, 1),
(9, 43, 1),
(10, 49, 1),
(11, 54, 1),
(12, 56, 1),
(13, 64, 1),
(14, 69, 1),
(15, 75, 1),
(16, 78, 1),
(17, 85, 1),
(18, 89, 1),
(19, 94, 1),
(20, 99, 1),
(21, 103, 1),
(22, 4, 2),
(23, 8, 2),
(24, 14, 2),
(25, 19, 2),
(26, 23, 2),
(27, 28, 2),
(28, 34, 2),
(29, 39, 2),
(30, 44, 2),
(31, 49, 2),
(32, 54, 2),
(33, 58, 2),
(34, 64, 2),
(35, 69, 2),
(36, 74, 2),
(37, 79, 2),
(38, 83, 2),
(39, 88, 2),
(40, 93, 2),
(41, 99, 2),
(42, 103, 2),
(43, 5, 3),
(44, 10, 3),
(45, 15, 3),
(46, 20, 3),
(47, 24, 3),
(48, 30, 3),
(49, 34, 3),
(50, 40, 3),
(51, 45, 3),
(52, 50, 3),
(53, 55, 3),
(54, 60, 3),
(55, 65, 3),
(56, 70, 3),
(57, 75, 3),
(58, 80, 3),
(59, 85, 3),
(60, 90, 3),
(61, 95, 3),
(62, 100, 3),
(63, 105, 3),
(64, 4, 4),
(65, 10, 4),
(66, 14, 4),
(67, 20, 4),
(68, 25, 4),
(69, 30, 4),
(70, 35, 4),
(71, 39, 4),
(72, 44, 4),
(73, 50, 4),
(74, 55, 4),
(75, 59, 4),
(76, 65, 4),
(77, 69, 4),
(78, 74, 4),
(79, 79, 4),
(80, 84, 4),
(81, 89, 4),
(82, 95, 4),
(83, 100, 4),
(84, 105, 4),
(85, 5, 5),
(86, 10, 5),
(87, 14, 5),
(88, 20, 5),
(89, 25, 5),
(90, 29, 5),
(91, 34, 5),
(92, 39, 5),
(93, 44, 5),
(94, 50, 5),
(95, 54, 5),
(96, 59, 5),
(97, 64, 5),
(98, 69, 5),
(99, 75, 5),
(100, 79, 5),
(101, 84, 5),
(102, 90, 5),
(103, 94, 5),
(104, 99, 5),
(105, 105, 5),
(106, 5, 6),
(107, 10, 6),
(108, 15, 6),
(109, 20, 6),
(110, 25, 6),
(111, 30, 6),
(112, 35, 6),
(113, 40, 6),
(114, 45, 6),
(115, 50, 6),
(116, 55, 6),
(117, 60, 6),
(118, 65, 6),
(119, 70, 6),
(120, 75, 6),
(121, 80, 6),
(122, 85, 6),
(123, 89, 6),
(124, 94, 6),
(125, 99, 6),
(126, 104, 6),
(127, 4, 7),
(128, 9, 7),
(129, 14, 7),
(130, 19, 7),
(131, 24, 7),
(132, 29, 7),
(133, 34, 7),
(134, 39, 7),
(135, 43, 7),
(136, 49, 7),
(137, 54, 7),
(138, 58, 7),
(139, 64, 7),
(140, 69, 7),
(141, 74, 7),
(142, 79, 7),
(143, 84, 7),
(144, 89, 7),
(145, 94, 7),
(146, 99, 7),
(147, 103, 7),
(148, 5, 8),
(149, 10, 8),
(150, 15, 8),
(151, 20, 8),
(152, 25, 8),
(153, 30, 8),
(154, 35, 8),
(155, 40, 8),
(156, 45, 8),
(157, 50, 8),
(158, 55, 8),
(159, 60, 8),
(160, 65, 8),
(161, 70, 8),
(162, 75, 8),
(163, 80, 8),
(164, 84, 8),
(165, 89, 8),
(166, 95, 8),
(167, 100, 8),
(168, 105, 8),
(169, 4, 9),
(170, 9, 9),
(171, 14, 9),
(172, 18, 9),
(173, 24, 9),
(174, 29, 9),
(175, 34, 9),
(176, 39, 9),
(177, 44, 9),
(178, 49, 9),
(179, 55, 9),
(180, 59, 9),
(181, 65, 9),
(182, 69, 9),
(183, 74, 9),
(184, 79, 9),
(185, 84, 9),
(186, 89, 9),
(187, 95, 9),
(188, 99, 9),
(189, 104, 9),
(190, 4, 10),
(191, 10, 10),
(192, 14, 10),
(193, 20, 10),
(194, 25, 10),
(195, 29, 10),
(196, 35, 10),
(197, 39, 10),
(198, 44, 10),
(199, 49, 10),
(200, 54, 10),
(201, 58, 10),
(202, 64, 10),
(203, 70, 10),
(204, 75, 10),
(205, 80, 10),
(206, 84, 10),
(207, 88, 10),
(208, 93, 10),
(209, 99, 10),
(210, 104, 10),
(211, 5, 11),
(212, 10, 11),
(213, 14, 11),
(214, 19, 11),
(215, 25, 11),
(216, 30, 11),
(217, 34, 11),
(218, 39, 11),
(219, 45, 11),
(220, 49, 11),
(221, 55, 11),
(222, 59, 11),
(223, 65, 11),
(224, 69, 11),
(225, 74, 11),
(226, 80, 11),
(227, 84, 11),
(228, 88, 11),
(229, 94, 11),
(230, 99, 11),
(231, 103, 11),
(232, 5, 12),
(233, 10, 12),
(234, 14, 12),
(235, 19, 12),
(236, 23, 12),
(237, 29, 12),
(238, 33, 12),
(239, 40, 12),
(240, 44, 12),
(241, 50, 12),
(242, 55, 12),
(243, 59, 12),
(244, 64, 12),
(245, 68, 12),
(246, 74, 12),
(247, 79, 12),
(248, 84, 12),
(249, 87, 12),
(250, 95, 12),
(251, 99, 12),
(252, 102, 12),
(253, 5, 14),
(254, 10, 14),
(255, 15, 14),
(256, 20, 14),
(257, 25, 14),
(258, 30, 14),
(259, 35, 14),
(260, 40, 14),
(261, 45, 14),
(262, 50, 14),
(263, 55, 14),
(264, 60, 14),
(265, 65, 14),
(266, 69, 14),
(267, 75, 14),
(268, 80, 14),
(269, 84, 14),
(270, 89, 14),
(271, 95, 14),
(272, 100, 14),
(273, 105, 14);

A: La consulta parece menos ficticia si aplicamos las relaciones como las tienes en la imagen compartida.
La veracidad o no de los resultados dependerá de los datos que tengas.
Yo he creado las tablas que faltaban:  encuesta, dimension y he agregado datos ad libitum.
Al final te dejo el enlace para que hagas pruebas.
En la consulta he quitado los NULL forzados que tú querías evaluar. Si el diseño está bien, el uso de LEFT JOIN te dará NULL si alguna condición del JOIN no se cumple.
Si esto no resuelve tu problema, entonces debes explicar con claridad qué pretende tu programa y se podría revisar el diseño.
La consulta escrita así:
SELECT
p.id_pregunta,
tr.tipo,
f.cod_curso_alumno,
COUNT(r.id_respuesta) as cantidad_respuestas
FROM form_alumnos f
LEFT JOIN encuesta e ON f.id_encuesta_for=e.id_encuesta
LEFT JOIN dimension d ON e.id_encuesta = e.id_encuesta
LEFT JOIN preguntas p ON d.id_dimension = p.id_dimension_p
LEFT JOIN tipo_respuesta tr on p.id_pregunta = tr.id_pregunta
LEFT JOIN respuesta r on tr.id_tipo = r.id_tipo
WHERE  (f.cod_curso_alumno = '354945' AND f.anio = '2016' AND f.semestre = 'Primer')
AND (tr.tipo = '3')
GROUP BY p.id_pregunta, r.id_tipo;

Arroja este resultado:
id_pregunta     tipo    cod_curso_alumno    cantidad_respuestas
1               3       354945              0
2               3       354945              7
3               3       354945              0
4               3       354945              7
5               3       354945              14
6               3       354945              7
7               3       354945              7
8               3       354945              0
9               3       354945              14
10              3       354945              0
11              3       354945              0
12              3       354945              21
13              3       354945              0
14              3       354945              7
15              3       354945              0
16              3       354945              7
17              3       354945              7
18              3       354945              21
19              3       354945              14
20              3       354945              0
21              3       354945              28

Desde el siguiente enlace puedes hacer pruebas si lo deseas: VER DEMO DEL CÓDIGO


text:
Q: What's the difference between the Old and New GIL (before/after Python 3.2) if you set Check Interval to 100,000? I'm trying to find differences between the Old and New GIL, using Python 2.6.4 and Python 3.2, based on David Beazley's talk. I ran the threaded codes below.
import time
import threading
import dis

def f(a, N):
    for i in range(N):
        a[i%3]+= i

def main():
    a1= [1, 2, 3]
    a2= [4, 5, 6]
    m= 1000*1000
    N= 50

    for i in range(5, N + 1, 5):
        t1= threading.Thread(target=f, args=(a1, i * m))
        t2= threading.Thread(target=f, args=(a2, i * m))

        start_time = time.time()

        t1.start()
        t2.start()
        t1.join()
        t2.join()

        end_time = time.time()
        print(2 * i * m, end_time - start_time)

main()

And got some results as in the graphs below. (The sequential code mentioned the the graphs are just like the threaded code above but its one-threaded, so I don't include it here).
Graphs of Python 2.6.4
Graphs of Python 3.2
When you run sys.setcheckinterval(100000) on Python 2, the check interval is changed from the default value of 100 to 100,000. With that change, the performance of the threaded code on multi-core CPU on 2.6.4 is better. In fact it is no different from running on 3.2.
If that is the case, why is the new GIL in 3.2 better? What's really different about it?
Thank you.

A: Why new GIL is better
The new GIL was designed to overcome the issue of starvation of IO-bound threads by the CPU-bound threads. Old GIL tends to favor CPU-bound threads over IO-bound on multi-core environment by allowing the CPU-bound threads to acquire the GIL consecutively. In the new GIL, one thread can't execute in a consecutive fashion even if it happens to acquire the GIL(it would have to release it eventually). A thread would not be able to run its bytecode until it waits for a certain duration(which in-turn would let the other thread grab the GIL).
In a nutshell, if you want to see if the new GIL is better than the old one: use IO-bound threads. You would find the responsiveness has gone up.
Typically Python applications perform IO-bound tasks. If you want to run CPU-bound code, go for running a separate thread via a C-extension(you need to release the GIL and reacquire it once done with C code).
Regarding the performance boost when interval is increased from 100 to 100000 in old GIL
As per my analysis, the thread would release the old GIL after every 100 ticks which means there would be a switch from user space to kernel space after every 100 ticks and it would continue till the thread finishes its time-slice allocated by the OS scheduler. When you increase the tick to 100000, the thread would not release the GIL(hence no user to kernel switch) rather it would utilize the CPU thoroughly(during its time-slice) and hence you might find a performance boost since the other thread is also CPU-bound(it would also utilize the CPU fully over its time-slice).
But if the other thread happens to be an IO-bound thread, it would suffer and its responsiveness would go down.


text:
Q: Responding HTML and JSON from php at the same time Imagine a page on a website, this page has many elements printed in html directly from server backend and others being printed throught JS with data based on JSON. With the first load of the page it comes all the HTML layout and his elements printed by php in the response in the same request some JSON is printed in the  section in order to being parsed by a JS funcions and templates..After that that JSON can be updated over another request to a JSON rest api
Is a good practice to do that?? The main reason to do that is to avoid make two request in the first page load... Imagine $data_array is a enormous data object
echo $entire_page_html;
echo '<script>'.'var data_source = '.json_enconde($data_array);.'</script>';

Thanks in advide!

A: There's nothing wrong with that.
Although currently your code is invalid, from a PHP and JavaScript perspective:

*

*json_encode() has only 1 n.

*Don't add a semi-colon mid concatenation

*You are echoing a JSON string, which'll be something like {"a":"b"}. This won't have quotes around it, which will produce a JavaScript error.

echo $entire_page_html;
echo "<script> var data_source = '" . json_encode($data_array) . "'</script>";
// Quotes have been added ---Here^------------------------and-Here^


text:
Q: Loading images in cloud ml This is main code which works on CPU machine. It loads all images and masks from folders, resizes them, and save as 2 numpy arrays.
from skimage.transform import resize as imresize
from skimage.io import imread

def create_data(dir_input, img_size):

    img_files = sorted(glob(dir_input + '/images/*.jpg'))
    mask_files = sorted(glob(dir_input + '/masks/*.png'))

    X = []
    Y = []

    for img_path, mask_path in zip(img_files, mask_files):

        img = imread(img_path)
        img = imresize(img, (img_size, img_size), mode='reflect', anti_aliasing=True)

        mask = imread(mask_path)
        mask = imresize(mask, (img_size, img_size), mode='reflect', anti_aliasing=True)

        X.append(img)
        Y.append(mask)

    path_x = dir_input + '/images-{}.npy'.format(img_size)
    path_y = dir_input + '/masks-{}.npy'.format(img_size)

    np.save(path_x, np.array(X))
    np.save(path_y, np.array(Y))

Here is gcloud storage hierarchy
gs://my_bucket
|
|----inputs
|      |----images/
|      |-----masks/
|
|----outputs
|
|----trainer

dir_input should be gs://my_bucket/inputs
This doesn't work. What is the proper way to load images from that path on cloud, and save numpy array in the inputs folder?
Preferable with skimage, which is loaded in setup.py

A: Most Python libraries such as numpy don't natively support reading from and writing to object stores like GCS or S3. There are a few options:

*

*Copy the data to local disk first (see this answer).

*Try using the GCS python SDK (docs)

*Use another library, like TensorFlow's FileIO abstraction. Here's some code similar to what you're trying to do (read/write numpy arrays).

The latter is particularly useful if you are using TensorFlow, but can still be used even if you are using some other framework.


text:
Q: Python If Statement and Lists i'm fairly new to python and am looking for some help. What i would like to do is read a csv file and then use a for loop with an if statement to locate at rows of that data contain a value and print it out with a header and some formatting using f'.
The issue i seem to have it when finding the data using the if statement, im unsure what i can output the data to, which will then enable it to be printed out (the search output could contain multiple rows and columns):
with open(r'data.csv', 'r') as csv_file:
    # loop through the csv file using for loop
    for row in csv_file:
        # search each row of data for the input from the user
        if panel_number in row:
            ??

A: Use the csv module. Then in your if statement you can append the row to a list of matches
import csv

matched_rows = []
with open(r'data.csv', 'r') as file:
    file.readline() # skip over header line -- remove this if there's no header
    csv_file = csv.reader(file)
    for row in csv_file:
        # search each row of data for the input from the user
        if row[0] == panel_number:
            matched_rows.append(row)

print(matched_rows)


text:
Q: Force remove cached May I know what is the command in terminal to force remove cache from GIT?
As per what I know to remove GIT is
    git rm --cached thefilename
But now I am getting an error
error: 'tutorial.h' has staged content different from both the file and the HEAD
(use -f to force removal)
So, may I know how am I going to remove this?

A: git rm --cached -f thefilename


text:
Q: Is using @if(Auth::user()) the same as @auth in my blade view? I realized I am using 2 ways to prevent people who are not logged from seeing stuff that are meant for members only. The first one is using @if(Auth::user()) and the second one is using @auth. For example:
@auth
    <button class="submit-btn like liked" id='{{ $image->id }}'>
@endauth

And
@if(Auth::user())
    <button class="submit-btn like liked" id='{{ $image->id }}'>
@endif

Is there any difference between those 2 examples or should I just stick to one of them?

A: Since version 5.4.29 they are basically the same. The shorter @auth and @endauth are only a shorter/hidden way for the if-else construction. For your own comfort, it is a good idea to stick to one of them.
The real moment it shines is when you are using guards, so you don't have to do something like this (assuming you have a usertype 'administrator'):
@if(Auth::user()->type === 'administrator')

Instead, the following suffices:
@auth('administrator')

A: More correctly to use:
Auth:check() Auth:guest() in your code because they return bool
auth()->check() auth()->guest() (same with helper).
And @auth @guest in blade.


text:
Q: Null character appearing when I print a file I have a code where I read a file and remove a block of line if a certain keyword matches. If I see the key word THERMST, I delete the line before and all lines until I reach a & :
QNODE "CExtHrn - Heater_Bidon" 1.0 T884 TOTAL
THERMST "CExtHrn" 0  2.500000E+01  3.000000E+01 883 ID  0.000000E+00  0.000000E+00  0.000000E+00  0.000000E+00  0.000000E+00 "Heater_Bidon"
NAME2 Heater_ CExtHrn - Heater_Bidon
NAME Heater_      40097      40170          1
TABTYPE 884 TABLE OPERATION
TABDATA 884 885 INTERP
TABDATA 884 883 THERMST
TABTYPE 885 QNODE TIME
TABDATA 885  2.000000E+01  0.000000E+00
$

However, for an obscure reason, when I print to a new file, it gives several null characters on a certain line. The weird thing is that this line is not related with the line I just changed. If I don't modify the file, by commenting the following lines, I don't get any null characters.
# We delete the last 2 line and skip the rest of the qnode/thermst definition
splice @INPF1_OUT, -2;
# Skipping the lines until next comment line.
$ii++ until substr($INPF1_IN[$ii], 0, 1) eq '$';
$ii = $ii - 1;

Any idea what this could be? The null characters are causing problems for what I do with the file.
Here is what the line should be :
NAME winte_T     101269     101270          1

here is what it prints in the new file :
NAME winte_T ULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNUL  101269     101270          1

You can see that the line that cause the error is not related to the one that should be modified
Thank you, the code is below
#!/bin/perl

use strict;
use Text::ParseWords;

open (INPF1_in, '<', $INPF1)
  or die "Not able to open : $INPF1";
my @INPF1_IN = <INPF1_in>;
close INPF1_in;
my @INPF1_OUT; # Output INPF1

my $cardno = 1;
my $ii = 0;
until ($ii > $#INPF1_IN) {
    my $INPF_line = $INPF1_IN[$ii];
    push(@INPF1_OUT, $INPF_line); # Adding line
    chomp($INPF_line);
    if ($INPF_line eq "-1") {
        $cardno++;
    }
    if ($cardno == 9) {
        my @line = parse_line(" ", 0, $INPF_line); # parsing the line elements

         if ($line[0] eq "THERMST") { # If Thermostat
            # We delete the last 2 line and skip the rest of the qnode/thermst definition
            splice @INPF1_OUT, -2;
            $ii++ until substr($INPF1_IN[$ii], 0, 1) eq '$';
            $ii = $ii-1; # Skipping the lines until next comment line.
        }
    }
    $ii++;
}

open (INPF1_out, '>', $INPF1);
print INPF1_out $_ foreach @INPF1_OUT;
close INPF1_out;

A: I may be misreading your code, but it look like you're trying to do something very simple in perl, a very hard way.
If I'm reading it right, what you're trying to do is take an input record format, and conditionally print certain lines. Perl has a very good tool for this, called the 'range operator'.
I think you will be able to accomplish what you want with something considerably simpler.
#!/bin/perl

use strict;
use warnings;

while ( <DATA> ) {
    print unless ( m/^THERMST/ ... m/^\$$/ );
}

__DATA__
QNODE "CExtHrn - Heater_Bidon" 1.0 T884 TOTAL
THERMST "CExtHrn" 0  2.500000E+01  3.000000E+01 883 ID  0.000000E+00  0.000000E+00  0.000000E+00  0.000000E+00  0.000000E+00 "Heater_Bidon"
NAME2 Heater_ CExtHrn - Heater_Bidon
NAME Heater_      40097      40170          1
TABTYPE 884 TABLE OPERATION
TABDATA 884 885 INTERP
TABDATA 884 883 THERMST
TABTYPE 885 QNODE TIME
TABDATA 885  2.000000E+01  0.000000E+00
$

This is an example, based on the data you've given so far - if you can give a bit more to show exactly what you're trying to accomplish, I would be pretty sure you can extract the information you need without having to do iterating through elements in an array of words. Perl can do better than that.
(I am guessing a bit, as it's completely unclear where you're getting $cardno from. However this should be quite easy to modify to suit your needs)


text:
Q: Loading multiple models with loadModel promise I would like to load an array of models using loadModel promise and loadAsHidden option. Then once all the models are loaded show them all at once. It seems every promise is resolved straight after I run the loadModel command. So the showHiddenModels function is ran before the models are fully loaded. Storeys array contains the svf addresses of the files.
function loadAllModels() {
    let options =
    {
        loadAsHidden: true,
        globalOffset: { x: 0, y: 0, z: 0 }
    };

    let promises = [];
    let length = storeys.length;
    let counter = 0;

    for (let storey of storeys) {
        let modelPromise = viewer.loadModel(storey.Svf, options);
        modelPromise.then((result) => {
            counter++;
            console.log('counter: ' + counter);

            if (counter == length) {
                showHiddenModels();
            }
        });

        promises.push(modelPromise);
    }
}

function showHiddenModels() {
    let models = viewer.impl.modelQueue().getHiddenModels();

    for (let model of models) {
         viewer.showModel(model);
    }

    let extension = viewer.getExtension('Autodesk.ViewCubeUi');
    extension.setViewCube('[top/front]');
}

This is how it looks in the console. So first the promise.then is called and after that it starts loading the files.

A: LoadModel fulfills its promise soon as the model seed file is loaded and not its full geometry/texture etc...
For lifecycle event where the model is completed loaded subscribe to Autodesk.Viewing.GEOMETRY_LOADED_EVENT:
viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, event=>{
  //event {type:string, model:object, target:object}
})

And in multiple model scenarios this event would fire multiple times when each and every model finishes loading - use the id of the model object to tell when the last model is completely loaded.


text:
Q: How to read structured import parameter in function module? I'm new to SAP ABAP and want to achieve the following: I've my custom Z function module (SE37) which should have a table as import parameter. This table I want to read/loop in the code, parse the values and pass it back to an export parameter (which is also the [same] table).
What I did so far:

*

*In SE11 I've created a structure containing all required fields ZCOLLECTSTRUCT

*Also in SE11 I've created a new table type ZCOLLECTTYPE which refers to this struct

*In the function module for an import parameter I've entered TYPE ZCOLLECTTYPE.

Now I want to loop over the entries of this table (which will be passed by a RFC call to the function module). I thought I just need to declare an internal table and a workarea based on the table type. But the gap is still, how can I bring the data to the internal table?
DATA:  itabImport LIKE ZCOLLECTTYPE.
DATA:  itabExport LIKE ZCOLLECTTYPE.
DATA:  wa_itabImport TYPE ZCOLLECTTYPE.
DATA:  wa_itabExport TYPE ZCOLLECTTYPE.

loop at itabImport into wa_itabImport.
  MOVE-CORRESPONDING itabImport TO itabExport.
  APPEND wa_itabExport.
endloop.

Appreciate any insights.
Edit:
I dont know how to get the data (values) from the import parameter table to the internal table.

to my itabImport?

A: Import parameters are just like variables. You can do
itabImport = import_batch.

Or avoid itabImport completely with
LOOP AT import_batch INTO wa_itabImport.

Note that your work areas need to be typed with the structure type, not with the table type:
DATA: wa_itabImport TYPE ZCOLLECTSTRUCT.
DATA: wa_itabExport TYPE ZCOLLECTSTRUCT.

A: Use just like that in your function module
LOOP AT import_batch INTO DATA(wa_itab).

and don't bother about typing.


text:
Q: Is there a way to verify if a topic as been subscribed to I am trying to make a python program that receive and send messages to my mqtt server from many devices (gateway). What i would like to do is when i receive a message from a device, verify if this device adresse as already been subscribed so i can receive external message to this device and route it to this particular device.
Right now each time i receive data from a device i resubscribe to the topic not knowing if it is already subscribed.
if (time.time() - last_sent_message) >= 0.25:
    message = daemon.memcache_read()
    if message:
        daemon.serial_print(message)
        #daemon.udp_send(message)
        try:
            mqttc.publish("to_" + message[8:17], message)
            mqttc.subscribe("from_" + message[8:17], 0)
        except:
            pass
        last_sent_message = time.time()

A: No, it is up to you to keep track of what topics you have subscribed to


text:
Q: How should I produce to JMS endpoints on a dynamic list of other nodes? From my hub system, I want to be able to communicate with a dynamic list of other nodes. I'm going to have a broker on each system and a static queue name. Thus I can address each node by targeting its broker. I have something working, using an endpoint per destination, but the Camel JMS doc implies that's not a great idea. I'll probably have less than 100 endpoints but I'm keen to see if there's a better way.
A dynamic recipient list would be perfect if I could specify the broker URI as part of the endpoint URI, but I can't see how to do that.
It'd probably be more sensible to use a single central broker and have the other nodes pick up from that, but I have a requirement that those nodes must not need to be configured with a central location. So the messages must be sent out, rather than collected.
Thanks in advance.

A: Firstly, it could be easier if you plug JNDI registry in your application. Apache ActiveMQ already comes with an integrated lightweight JNDI provider. Alternatively, you can use some app server's JNDI or another lightweight implementation. Then fill this registry with broker destinations (ConnectionFactory instances).
Initialize JndiTemplate in your context:
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
    <props>
            <prop key="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</prop>
            <prop key="java.naming.provider.url">tcp://localhost:61616</prop>
    </props>
    </property>
</bean>

After that you can specify сonnectionFactory property on endpoint in Dynamic Router using destinations from your registry:
public class FooDynamicRouter {

  private AbstractApplicationContext ctx;
  private JndiTemplate jndiTemplate;

  @Consume(uri = "activemq:outgoing")
  @DynamicRouter
  public String route(@XPath("/destination/code") String code, Document body) {
     if (code != null) {
       if (!ctx.containsBean("cf"+code)) {
          ctx.getBeanFactory().registerSingleton("cf"+code, jndiTemplate.lookup("cf"+code));
       }
       return "jms:queue:foo?connectionFactory=cf"+code;
     } else {
       return null;
     }
  }
}

Perhaps there is simplier way to bind your JNDI registry entries with application context in runtime, but I didn't find it.


text:
Q: Adding a large brace next to itemize: beamer How can I add a large "}" (that covers top to bottom of Part 2) to the right of all texts of Part 2 on layer number 7? I don't "}" to be at right end of the frame because I want to write "Part 2" at the right hand side of it. Any idea?
\begin{frame}
%%%% Part1%%%%%
\begin{itemize}
\item<1-> A
\end{itemize}
%%%%%%%%%%%%%%%

%%%% Part2%%%%%
\begin{itemize}
\item<2-> B
\item<3-> C:
\begin{itemize}
\item<4-> C1,
\item<5-> C2.
\end{itemize}
\end{itemize}
%%%%%%%%%%%%%%%

%%%% Part3%%%%%
\begin{itemize}
\item<6-> D
\end{itemize}
%%%%%%%%%%%%%%%
\end{frame}

A: \documentclass{beamer}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{tikzmark,decorations.pathreplacing,calligraphy}

\begin{document}

\begin{frame}
%%%% Part1%%%%%
\begin{itemize}
\item<1-> A
\end{itemize}
%%%%%%%%%%%%%%%

%%%% Part2%%%%%

\begin{itemize}
\item<2-> B\tikzmark{start}
\item<3-> C:
\begin{itemize}
\item<4-> C1,
\item<5-> C2.\tikzmark{end}
\end{itemize}
\end{itemize}

%%%%%%%%%%%%%%%

%%%% Part3%%%%%
\begin{itemize}
\item<6-> Limited to finite horizon problems
\end{itemize}
%%%%%%%%%%%%%%%

\begin{tikzpicture}[remember picture,overlay]
    \draw[decorate,decoration={calligraphic brace}]
        ([yshift=10pt,xshift=60pt]{{pic cs:end}|-{pic cs:start}}) --
        node[xshift=5pt,anchor=west] {Part 2}
        ([xshift=60pt]{pic cs:end})
;
\end{tikzpicture}

\end{frame}

\end{document}

(Thanks to @Loop Space for suggesting the calligraphic brace!)


text:
Q: Apple in-app subscription : how to detect if the subscription is auto renewing? Here is my response to fetch my latest receipt. I apply subscription which is monthly. That implies a flag to tell us that the monthly subscription auto renews its expires_date . Would you please tell me which param tells auto renewing subscription is enabled ?
 "latest_receipt_info" =         (
                    {
            "expires_date" = "2019-07-31 13:08:33 Etc/GMT",
            "expires_date_ms" = 1564578513000,
            "expires_date_pst" = "2019-07-31 06:08:33 America/Los_Angeles",
            "is_in_intro_offer_period" = false,
            "is_trial_period" = false,
            "original_purchase_date" = "2019-07-31 12:09:11 Etc/GMT",
            "original_purchase_date_ms" = 1564574951000,
            "original_purchase_date_pst" = "2019-07-31 05:09:11 America/Los_Angeles",
            "original_transaction_id" = 1000000552773665,
            "product_id" = "MP20190527_2",
            "purchase_date" = "2019-07-31 13:03:33 Etc/GMT",
            "purchase_date_ms" = 1564578213000,
            "purchase_date_pst" = "2019-07-31 06:03:33 America/Los_Angeles",
            quantity = 1,
            "transaction_id" = 1000000552793408,
            "web_order_line_item_id" = 1000000045982930,
        }
    ),

   "pending_renewal_info" =         (
                        {
                "auto_renew_product_id" = "MP20190527_2",
                "auto_renew_status" = 1,
                "original_transaction_id" = 1000000552773665,
                "product_id" = "MP20190527_2",
            }
        ),

A: As per apple doc if user turned off auto renew, value of auto_renew_status flag will be 0.
Please refer following apple doc for receipt field with description for more information
https://developer.apple.com/library/archive/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW8


text:
Q: How can use MySQL locking using a single connection? or any alternative for using a new connection every time am using locks? Well I know there is limit to maximum connections MySQL can handle at a time, so my question is
In my application (a discord bot), I've many functions which are using MySQL locks like SELECT ... FOR UPDATE and there are quite a chance multiple instances of these functions are executed concurrently so, is MySQL locking possible in a single connection? What I mean here is, is it possible to have a single connection and lock a row and meanwhile another query on that same connection executes updating that same row but this time that query needs to wait till the lock is released.
Currently am using a new connection for each and every query, so I need suggestions what should I do in this case?
Increase max_connections ? or Any other way of achieving this?
EDIT:
Currently am using this function each time am executing a query
def execute_query(query,param=None):
 db = connector.connect(host=host,user=user,password=password,database=database)
 db.set_charset_collation('utf8mb4', 'utf8mb4_bin')
 cursor = db.cursor(buffered=True)
 try:
  cursor.execute(query,param)
  reply = cursor.rowcount
  db.commit()
  db.close()
  print("Query executed successfully!")
  return reply
 except Exception as ex:
  db.rollback()
  db.close()
  print(ex)
  return ex


text:
Q: What's Faster/More Efficient For Grabbing First 10 Elements In Array I need the key, value, and index of the first 10 elements of my sorted associative array.
$top10pts = array_slice($toppoints, 0, 10);
foreach ($top10pts as $key => $val) {
    echo "
".(array_search($key, array_keys($top10pts))+1)."	".htmlentities($key)."	".$val."
";
}

or
for ($i=0; $i<10; $i++) {
    $val = array_slice($toppoints, $i, 1);
    echo "
".($i+1)."	".htmlentities(key($val))."	".$val[key($val)]."
";
}

or another method?
Being new to PHP, both methods seem stupid and superfluous.

A: This is the best method that came to my mind.
$top10pts = array_slice($toppoints, 0, 10);
$i = 1;
foreach ($top10pts as $key => $val)
    echo "
".($i++)."	".htmlentities($key)."	".$val."
";

Notice that, for more than 10 items, this method works better because it has no conditions in the loop. In interpreters such as php, it's usually better to use internal functions rather than doing the things yourself.

A: Similar to ernie's answer but you dont need array slice at all
$index = 0;
foreach ($top10pts as $key => $val) {
    echo "
".$index++."	".htmlentities($key)."	".$val."
";
    if($index >=10) break;
}

A: Since you sorted already, a foreach will iterate in order, so I'd use a modification of your first, getting rid of the array_search: . . .
$index = 0;
$top10pts = array_slice($toppoints, 0, 10);
foreach ($top10pts as $key => $val) {
    echo "
".$index."	".htmlentities($key)."	".$val."
";
    $index++;
}


text:
Q: What are my options with a downloaded Rackspace cloud image? I've got an unresponsive Rackspace slice that has defied all attempts at accessing. I created an emergency image from this and deleted it, downloading the files that compromise the image to a local source. There are a number of files / assets I would still like to recover from this server if possible but not sure exactly what I can do with the image files, if anything.
Here's the files I have, for what its worth:
emergency_########_######_cloudserver########.tar.gz.0 (5gb)
emergency_########_######_cloudserver########.tar.gz.1 (5gb)
emergency_########_######_cloudserver########.tar.gz.2 (5gb)
emergency_########_######_cloudserver########.tar.gz.3 (50mb)
emergency_########_######_cloudserver########.yml (25kb)

Is it possible to mount this image as a drive? Are there other forensic recovery options?

A: If what you get after putting the .tar.gz back together and unpacking it results in a disk image, then you should be able to recover files from it.
To begin with, for best results you should be working from a Linux system, with plenty of drive space available (50GB or more). I'm not sure if this is even possible with Windows.
First put the file back together:
cat emergency*.tar.gz.* > image.tar.gz

Now unpack it:
tar -zxvf image.tar.gz

What comes next depends on what was in the tarball. Hopefully it's a single file containing a disk image. In that case, inspect it with:
kpartx -l *imagefile*

(Where imagefile is the name of the disk image file that came out of the tarball.)
You should see what looks like a partition table. If all looks well with the partition table, run:
kpartx -v -a *imagefile*

This will map the partitions in the image to /dev/mapper/loop0p*.
You should then be able to mount these partitions and look at their contents. Remember to mount the filesystems read-only (-o ro) to prevent further damage.

A: FYI, this almost definitely belongs on ServerFault.
The "emergency" files are showing up as ".tar.gz" in the file extension, which tells me that they should be tar archives that you can extract like a zip file. If you're on Windows, download 7-zip from http://7-zip.org and you should be able to open them.
I'm not sure what you'll find within since I've never been a Rackspace customer; but I hear that they have "fanatical support" so it may be within your power to ask them about their backup files and how to access them....
Best of luck.


text:
Q: why this code doesnt work and I cant expire the cookie? Hello the expire button is not working! whats the problem?
I want to expire the cookie when the user clicks the expire button.
please tell me the problem and the correct form of the code.Please tell me the reason!
I recently started php so Idont know much things aboat it.please explain it very simple.
I also added the codes and the picture!
imag_1
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <form method="POST">

            <input placeholder="Cookie name" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="name">
            <input placeholder="Cookie value" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="value">

        <button type="submit" class="btn btn-primary" name="submit">Submit</button>
    </form>
    <?php
    if (isset($_POST["submit"])) {
        $Cookiename = $_POST["name"];
        $Cookievalue = $_POST["value"];
        if (!empty($Cookiename) && !empty($Cookievalue)) {
            setcookie($Cookiename, $Cookievalue);
        } else {
            echo "
Please fill the fields!!!
";
        }
    }
    ?>

                    Cookie name

                    cookie value

                <?php foreach ($_COOKIE as $key => $val) { ?>

                        <?php echo $key ?>

                        <?php echo $val ?>

                        <form method="POST"><button type="submit" class="btn btn-primary" name="expire" value="<?php echo $key; ?>">expire</button></form>

                <?php } ?>

<?php
if (isset($_GET["expire"])) {
    setcookie('$_POST["expire"]','', time() - 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999);
    echo '$_POST["expire"]'.'is deleted!';
}
?>


text:
Q: Is it possible to get listed registered email accounts on iOS? There is a form in my App, and I want to make it easier to user to fill out the form. Can I get the registered email accounts on Email App and ask user to choose one to use for my form?

A: You can set auto-correction to "on" and the keyboard type to "email" in the text view properties. In this case when the user begins to type his email address the system offers its own address as an auto-correction tooltip. That's all what you can do with this.


text:
Q: How add @angular-eslint/schematics? Error I want to add @angular-eslint/schematics to a project. But I can't do it. Neither in the admin panel, nor in the user.
I tried:

*

*ng add @angular-eslint/schematics

*npm install --save-dev eslint

*npm i -D @angular-eslint/template-parser

*ng add @angular-eslint/schematics@latest

*ng add @angular-eslint/schematics@next

*ng add @angular-eslint/schematics --legacy-peer-deps

*ng add @angular-eslint/schematics --force

*Delete node_modules package-lock chache and reinstall

"dependencies": {
    "@agm/core": "^3.0.0-beta.0",
    "@angular/animations": "^14.0.5",
    "@angular/cdk": "^14.0.4",
    "@angular/common": "^14.0.5",
    "@angular/compiler": "^14.0.5",
    "@angular/core": "^14.0.5",
    "@angular/forms": "^14.0.5",
    "@angular/localize": "^14.0.5",
    "@angular/platform-browser": "^14.0.5",
    "@angular/platform-browser-dynamic": "^14.0.5",
    "@angular/router": "^14.0.5",
    "@fortawesome/angular-fontawesome": "~0.11.1",
    "@fortawesome/fontawesome-svg-core": "~6.1.1",
    "@fortawesome/free-solid-svg-icons": "~6.1.1",
    "@kolkov/ngx-gallery": "^2.0.1",
    "@larscom/ngx-translate-module-loader": "^3.0.6",
    "@ng-bootstrap/ng-bootstrap": "~12.1.2",
    "@ngx-translate/core": "~14.0.0",
    "@ngx-translate/http-loader": "~7.0.0",
    "autoprefixer": "10.4.7",
    "bootstrap": "~5.1.3",
    "chart.js": "^3.8.0",
    "chartjs-plugin-datalabels": "^2.0.0",
    "font-awesome": "~4.7.0",
    "hammerjs": "~2.0.8",
    "lodash": "~4.17.21",
    "ng-animate": "~2.0.1",
    "ng2-charts": "^3.1.0",
    "ng2-nouislider": "^1.8.3",
    "ngx-ellipsis": "^4.0.0",
    "ngx-infinite-scroll": "^13.0.2",
    "ngx-spinner": "~14.0.0",
    "ngx-teximate": "~0.3.0",
    "ngx-translate-multi-http-loader": "^8.0.2",
    "nouislider": "^15.6.0",
    "primeicons": "~5.0.0",
    "primeng": "^13.4.1",
    "rxjs": "~7.5.5",
    "tslib": "^2.4.0",
    "zone.js": "~0.11.6"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.0.5",
    "@angular-eslint/template-parser": "^14.0.0",
    "@angular/cli": "^14.0.5",
    "@angular/compiler-cli": "^14.0.5",
    "@types/googlemaps": "^3.39.13",
    "@types/jasmine": "~4.0.3",
    "@types/lodash": "~4.14.182",
    "@types/node": "~18.0.3",
    "@types/uuid": "~8.3.4",
    "eslint": "^8.19.0",
    "jasmine-core": "~4.2.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.1",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.7.4"
  }

"dependencies": {
    "@angular/animations": "^14.0.5",
    "@angular/cdk": "^14.0.4",
    "@angular/common": "^14.0.5",
    "@angular/compiler": "^14.0.5",
    "@angular/core": "^14.0.5",
    "@angular/forms": "^14.0.5",
    "@angular/platform-browser": "^14.0.5",
    "@angular/platform-browser-dynamic": "^14.0.5",
    "@angular/router": "^14.0.5",
    "@kolkov/ngx-gallery": "^2.0.1",
    "@ngx-pwa/local-storage": "^13.0.3",
    "@types/lodash": "^4.14.182",
    "bootstrap": "^5.1.3",
    "eva-icons": "^1.1.3",
    "hammerjs": "^2.0.8",
    "lodash": "^4.17.21",
    "moment": "^2.29.4",
    "ngx-moment": "^6.0.2",
    "ngx-pagination": "^6.0.2",
    "ngx-spinner": "^14.0.0",
    "ngx-toastr": "^15.0.0",
    "normalize.css": "^8.0.1",
    "primeflex": "^3.2.1",
    "primeicons": "^5.0.0",
    "primeng": "^13.4.1",
    "quill": "^1.3.7",
    "rxjs": "~7.5.5",
    "tslib": "^2.4.0",
    "zone.js": "~0.11.6"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.0.5",
    "@angular/cli": "^14.0.5",
    "@angular/compiler-cli": "^14.0.5",
    "@types/jasmine": "~4.0.3",
    "@types/node": "^18.0.3",
    "codelyzer": "6.0.2",
    "jasmine-core": "~4.2.0",
    "jasmine-spec-reporter": "~7.0.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.1",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "^2.0.0",
    "protractor": "^7.0.0",
    "ts-node": "~10.8.2",
    "tslint": "~6.1.0",
    "typescript": "~4.7.4"
  }

A: In my case helped
npm i @angular-eslint/schematics --force
before
add @angular-eslint/schematics
But for some reason ADD does not always work, and before using it, you must first install the library.


text:
Q: ZF2 Form Collection - Using Collection for Doctrine Type "array" I'm stuck with ZF2! I'm trying to add a Collection element on my form to display an array of phone numbers stored in a simple "array" in my Doctrine entity.
I want to know what is the proper way to get my values working with Doctrine without using a Fieldset as it only need one field (the phone number).
I tried a lot of things but nothing is working. If someone did it, could you tell me please!


text:
Q: Operating System Log in and log out time using java Can any one help me
 to know
how to detect system log in and log off time using java api?
Only login time when logging in and logout time when system shutdown.
If possible is der available for linux machine also.

A: take a look at this:
public static long getSystemUptime() throws Exception {
long uptime = -1;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
    Process uptimeProc = Runtime.getRuntime().exec("net stats srv");
    BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
        if (line.startsWith("Statistics since")) {
            SimpleDateFormat format = new SimpleDateFormat("'Statistics since' MM/dd/yyyy hh:mm:ss a");
            Date boottime = format.parse(line);
            uptime = System.currentTimeMillis() - boottime.getTime();
            break;
        }
    }
} else if (os.contains("mac") || os.contains("nix") || os.contains("nux") || os.contains("aix")) {
    Process uptimeProc = Runtime.getRuntime().exec("uptime");
    BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
    String line = in.readLine();
    if (line != null) {
        Pattern parse = Pattern.compile("((\\d+) days,)? (\\d+):(\\d+)");
        Matcher matcher = parse.matcher(line);
        if (matcher.find()) {
            String _days = matcher.group(2);
            String _hours = matcher.group(3);
            String _minutes = matcher.group(4);
            int days = _days != null ? Integer.parseInt(_days) : 0;
            int hours = _hours != null ? Integer.parseInt(_hours) : 0;
            int minutes = _minutes != null ? Integer.parseInt(_minutes) : 0;
            uptime = (minutes * 60000) + (hours * 60000 * 60) + (days * 6000 * 60 * 24);
        }
    }
}
return uptime;
}

this will give you the uptime, so subtract it from current time.

A: If by system you mean the Operating System, then i'll sugest you to use a script for that,
especially for linux. For example you can use the file ~/.bashrc to detect the log in.


text:
Q: How to order control m job using REXX? like Control m utility CTMAPI I have to order few jobs in control m from different scheduling tables. this is manual task so i want to automate it using rexx.
I found below in 'Order or Force under Batch, REXX or CLIST' section of 'CONTROL M USERGUIDE'
EXEC CTMAPI PARM='ORDER variable'
I could not find syntax to call CMTAPI using rexx.

A: ADDRESS 'LINKMVS' is the equivalent of // EXEC PGM=something,PARM='whatever' in REXX. I don't know what the variable is supposed to be, but since this is Control-M, I am going to assume job name. A very simple example:
say 'Enter name of job'
pull jobname
parmvar = 'ORDER' jobname
`ADDRESS 'LINKMVS' 'CTMAPI parmvar'

Please note that for LINKMVS, the variable name goes inside the string passed. The LINKMVS environment substitutes the variable automatically. For example, if I entered MYJOB to the prompt, LINKMVS will build a PARM string of `ORDER MYJOB'. This is the exact equivalent of
// EXEC PGM=CTMAPI,PARM='ORDER MYJOB'

This IBM® Knowledge Center page for the z/OS 2.3 TSO/E REXX Reference manual shows several examples of calling a program in the same manner as // EXEC PGM=,PARM= (item 1). Items 5 through 9 show different ways of using ADDRESS 'LINKMVS'; note how variables are treated in each example.

A: After suggestions from NicC, zarchasmpgmr and few research, finally i am able to order job with CTMJOB utility. I searched for the loadlib and called TSO using REXX.
/*****REXX*******/
ADDRESS TSO
"CALL 'MY.IN.LOAD(CTMJOB)'
' ORDER DSN=MY.SCHED.LIB  TABLE=SCHDTBL,
JOB=JOBNAME,DATE=DATE'"
EXIT

Details found in INCONTROL for ZOS utilities guide. This document was very useful.
http://documents.bmc.com/supportu/952/56/64/195664/195664.pdf


text:
Q: How to use groupby or aggreation in linux here is the exemple
[A]
XXXX
SSSS
[B]
EEEEE
EEEEE
[A]
ZZZZ
RRRR
[B]
TTTTT
UUUUU
[C]
OOOOO
ZZZZZ

the question is how can we do in linux shell groupby element to have this result ? :
[A]
XXXX
SSSS
ZZZZ
RRRR
[B]
EEEEE
EEEEE
TTTTT
UUUUU
[C]
OOOOO
ZZZZZ

So if can have a function or script or set of commands to do this task that would help me a lot in my project of auto proxy and load balancers. Thank you

A: Using awk:
awk '
/^\[/ {
  group = $0
  next
}
{
  elems[group] = elems[group] $0 ORS
}
END {
  for (group in elems)
    printf "%s%s%s", group, ORS, elems[group]
}' file


text:
Q: How to fill an echoed  with PHP, after clicking a button I have this problem, I'm using PHP to create an HTML document, creating everything with echo, my problem is that I'm creating a select, but it must be filled when the index of the other one changes, filling in doc creation is easy, but how can I fill it using PHP when selecting something in the other select?
$html_ciudad = '';
$file = $DOCUMENT_ROOT. "newContact.php";
$dom = new DOMDocument;
$dom->loadHTMLFile($file);
$div = $dom->getElementById("City");

foreach($ciudades->getCiudad($id) as $ciu){
    $newDiv = $dom->createElement('option');
    $newDiv->setIdAttribute($ciu["IdCd"]);
    $newDiv->nodeValue(utf8_encode($ciu["Cd"]));
    $div->appendChild($newDiv);
    $html_ciudad .=
        '<option id="'.$ciu["IdCd"].'" value="">'.utf8_encode($ciu["Cd"]).'</option>';
}

I tried that way, everything working, but not showing result, If someone knows how to do this, even if the code is completely different, is welcome haha thanks.

A: So if i understood it well, if your select value change, you should load from another page with ajax another select...This code may help:
in your main page:

$('select').on('change', function() {
   if(this.value==1){

        $("#div1").load("another_select.php");
   }

})

</script>

in another_select.php page:

echo "<select>";
...
echo "</select>";


text:
Q: Badging TitleArea Commands I have a form with a command added to the right side of the titlearea. I will like to badge the command icon with dynamic values.

I have checked the documentation for Command and there seems to be no method to badge

A: You need to convert the command to a component first:
Command cmd = tb.addMaterialCommandToRightSide(...);
Button btn = tb.findCommandComponent(cmd);
Container cnt = btn.getParent();
btn.remove();
FloatingActionButton fab = FloatingActionButton.createBadge("" + number);
cnt.add(badge.bindFabToContainer(btn, Component.RIGHT, Component.TOP));

Notice that this will only work once so you will need to save some of the components here and remove/replace them if you want to update the number.


text:
Q: Storing intermediate results during overridden equals method Actual case:
I would like to override public boolean equals(java.lang.Object obj) for some of the objects in my current Java project. This method should still return true when the challenge object is considered equal to the current one. However, while establishing the equality between objects, I need to store some processing results in a data structure belonging to another, singleton, class (I have to store the list of differences if any, for future use in the application workflow).
Calling the overridden equals() will then have a side-effect which is intimately linked to the way I establish that the objects are equal. However, there is no side-effect to the method when it's not overridden. Is that considered as a design flaw? Is there any good practice that would go against such approach?
Oracle documentation about method overriding is quite laconic, imho, about this: "The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed.".
I don't see any restriction with such statement but I'd like to get advice from OOP developers/designers/architects.
Thank you!
More details (simplified code):
// Dataform is a JAX bean class
public class Dataform {
    String name;
    // Column is a JAX bean class
    ArrayList<Column> columns;
    // Footer is a JAX bean class
    Footer footer;

    // equals is redefined the same way for each JAX bean classes
    @Override
    public boolean equals(Object obj){
        if(this.getClass().isInstance( obj )){
            // equalsXML is a method that compares XML elements (JAX beans in this case). This method can in turn call equals() on
            if (XMLObject.equalsXML( this, obj ).isEmpty()){
                // Store differences in singleton class for future access
                return false;
            }
            else{
                return true;
            }
        }
        else{
            return super.equals( obj );
        }
    }
}

A: If you need to do some extra processing for specific methods (or almost anything) whithout touching programs code, consider Aspect Oriented Programming. This is a technique when you modify bytecode either during compile time, or dynamically. It sounds complex, but its not. This technique is perfect for logging, monitoring, extra security, exceptions handling and many others. Personally I prefer to use it for things not related to domain model. Imagine if you need to do logging for entire program. You would need to add extra line to each method you want to log. With AOP you can do this with very few lines without touching your programs code at all. Read about AspectJ. It is oldest and probably most advanced tool so far (except BCEL - direct byte code manipulation framework)


text:
Q: How to delete a specific Status type in JIRA I created a new Status type in JIRA status. Let's call the new status "MERGED." This is in addition to the standard status that Jira provides, like "To Do", "In Progress", "Done" etc.
However, we've decided not to use it. All items that were tagged as "Merged" have since been moved to "Done".
How do I delete the "Merged" status option in Jira so that nobody accidentally tags any items and it does not appear in any JQL queries?

A: This is explained in Defining Status Field Values, see Deleting a Status:

The View Statuses page can be used to edit and delete Statuses. Please note that only statuses (i.e. statuses that are not used in any workflow) can be deleted.

*

*A Delete link for deleting a Status will only appear next to the Edit link of an Inactive status

As outlined, you need to ensure that no workflow is using the status you want to delete, which can see Statuses in the workflow designer for how to achieve this:

Remove a status – via Properties panel. Removes the status from the workflow, but not the JIRA instance.

Once you removed the status in question from all workflows, you can then remove it from the JIRA instance as well as outlined in the first quote above.


text:
Q: Why would a built-in Wordpress function be undefined in a plugin? I'm troubleshooting a custom plugin from one of my predecessors.
The plugin is on a Multisite installation and it creates some default posts and pages when a new site is added.
It uses the built-in WP function get_page_by_title() and I just got
PHP Fatal error: Uncaught Error: Call to undefined function get_page_by_title()
The code in question is
function addPostOverview() {
    $title = 'Project Overview';
    $page = get_page_by_title($title, null, 'post');

    if (!empty($page)) {
        return;
    }

$post = array(
        'post_content' => 'Overview Example. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum mauris lorem, tempor a erat a, vehicula ultricies diam. Suspendisse in leo aliquet, ornare sapien vitae, commodo mi. Nullam ornare, mi et volutpat accumsan, enim tellus aliquam quam, vitae molestie sapien magna quis est. Praesent et magna efficitur, ornare nunc eget, commodo nunc. Donec et erat ac urna pharetra luctus et sed mauris.', // The full text of the post.
        'post_name' => 'project-overview', // The name (slug) for your post
        'post_title' => $title, // The title of your post.
        'post_status' => 'publish', //[ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ] // Default 'draft'.
        'post_type' => 'post', // [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] // Default 'post'.
        'comment_status' => 'closed', // Default is the option 'default_comment_status', or 'closed'.
        'post_category' => array(get_cat_ID('Project Page'))  // Default empty.
    );

    $postID = wp_insert_post($post, $wp_error);
}
addPostOverview();

In what circumstances would a built-in WP function be undefined? I'm in WP 6.1.1 (latest) and just updated to PHP 8.1.


text:
Q: Compile Gstreamer/orc 0.4.32 on ubuntu1804 for arm running in rootfs using ninja occur undefined reference exception I am trying to compile gstreamer/orc on ubuntu_1804 for arm which running on rootfs my android mobile phone, but something wrong like this:
I tried some option (-j 1) to make it compile with single thread, but still not working.


text:
Q: Excel VBA: Sort rows Numerically (by column value) THEN sort by one specific string I don't know if this is the right approach for this. But here goes. I have some excel data:
Column 1 |  Column 2
1        |   open
3        |   issue
7        |   closed
8        |   open

I need to sort by column 2 (all columns with 'open' at top of list but with a numerical sort also so the row with '8,Open' would be at the top) then the rest of the rows need sorting only numerically highest numbers first.
resulting in:
Column 1 |  Column 2
8        |   open
1        |   open
7        |   closed
3        |   issue

Below is my code for the numeric only (column 12). I need help with the other aspect.
With ActiveSheet.Sort
    .SortFields.Clear
    .SortFields.Add Key:=Selection.EntireRow.Columns(12), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    .SetRange ActiveSheet.Range(Data)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

A: you could use the Sort method of the Range object
Dim iniRow As Long

With Range("Data")
    .Sort key1:=.Range("B1"), order1:=xlDescending, Header:=xlYes '<~~ first sort by column 2 ("B" in my test)
    iniRow = Application.CountIf(.Columns(2).Cells, "open") '<~~ then count how many "open" are there
    .Offset(iniRow + 1).Resize(.Rows.Count - (iniRow + 1)).Sort key1:=.Range("A" & iniRow + 2), order1:=xlDescending, Header:=xlNo '<~~ finally order remaining by column 1 ("A" in my test)
End With

A: Try this:
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Range("B1"), xlSortOnValues, xlAscending, "Open"
ActiveSheet.Sort.SortFields.Add Range("A1"), xlSortOnValues, xlDescending
With ActiveSheet.Sort
    .SetRange Range(Data)
    .Header = xlGuess
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

EDIT:
_________________________________________________________________________________
Dim SortStr As Variant
Dim SortNum As Long

'change below array as per your requirement
SortStr = Array("Open", "in progress", "almost finished")
Application.AddCustomList ListArray:=SortStr
SortNum = Application.CustomListCount

ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Range("B1"), xlSortOnValues, xlAscending, SortNum
ActiveSheet.Sort.SortFields.Add Range("A1"), xlSortOnValues, xlDescending
With ActiveSheet.Sort
    .SetRange Range(Data)
    .Header = xlGuess
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Application.DeleteCustomList Application.CustomListCount


text:
Q: Trying to add Imageview to canvas via FrameLayout.addView(); I can add this logo to the canavas if I do this:
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(200,200);

ImageView boo = new ImageView(ExampletouchActivity.this);
boo.setImageResource(R.drawable.ic_launcher);
boo.setLayoutParams(lp);
fr.addView(boo); //this works fine

But if I try to add the same logo to the canvas like this it does not show anything up:
fr.addView(new Toucher(ExampletouchActivity.this));

My Toucher class is like so...
public class Toucher extends View{
ImageView boo;

public Toucher(Context context)
{
    super(context);
    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(200,200);
    boo = new ImageView(context);
    boo.setImageResource(R.drawable.ic_launcher);
    boo.setLayoutParams(lp);
}
@Override
public void onDraw(Canvas c)
{
    boo.draw(c);
}

I have been trying for ages and cannot work out why this imageview will not draw itself to the canvas?
Many Thanks

A: Layout and Canvas aren't the same thing. Layout is "draw this for me", and Canvas is "I'm drawing this".  In your working example, you're taking a static image and putting it into a Layout.

A: When you are using the canvas, in a view things are different, so try using:
canvas.drawBitmap(bg, src, dst, paint);


text:
Q: PDF documents can only be saved, not opened When I click on a PDF link in Iceweasel (Firefox in Debian) there is no option to open the document, only to save it. In Edit -> Preferences -> Applications I have set the action for PDF documents to "Use Atril Document Viewer" but apparently it has no effect. Any clues?

A: I'm not entirely sure if this is exactly the same problem, but despite setting the default to open PDFs in an external application, Firefox frequently ignores this, popping up a dialogue box instead of automatically opening the external application.
One solution that worked for me was to install the Open in Browser extension, and set it to Never ask to confirm "Save File" action. Despite the slightly confusing nomenclature, the next time I attempted to open a PDF, I set it to Open in browser as PDF, and Do this automatically for files like this from now on. The next time I attempted to open a PDF, it opened automatically without the dialogue box.


text:
Q: Projectile, the focus of its parabolic path, and the circle drawn through the focus Consider any projectile O and its path. Assume that drag or any other type of non-conservative or resisting force doesn't exist and that only that gravitational pull of the earth exists. Note: Let the acceleration due to gravity g remain constant.
Hence, the trajectory of this projectile near the earth's surface will be a parabola. Take any point A on this parabola, and drop a perpendicular to the parabola's directrix at B. With A as the center and AB as the radius draw a circle which will surely meet the focus.
Let this circle cross the vertical line of symmetry of the parabola(i.e. the line of symmetry is a secant to the circle). Is this possible and if yes, what happens in this physical situation?

For Your Information ---

*

*The distance from the focus to the launch point of a projectile is $v^2/(2g)$

*This distance is always true regardless of the angle of projection.

*The x coordinate of the vertex of a parabola and its focus are equal.

*The distance from any point to the focus is equal to the perpendicular distance from that point to the directrix.(Eg: AF = AB)

*The initial velocity of water coming out the cylindrical vessel is given by..
$$v = \sqrt{2g(H-h)}$$
Here is an example problem that illustrates such a case. Give it a try if you want to.
I came across this problem statement, in this book... https://www.cambridge.org/core/books/200-more-puzzling-physics-problems/B4DC45F5A40D4B792653B407975F3A41

At the top of a long incline that makes an angle θ with the horizontal,
  there is a cylindrical vessel containing water to a depth H. A hole is to be drilled
  in the wall of the cylinder, so as to produce a water jet that lands a distance d down
  the incline. How far, h, from the bottom of the vessel should the hole be drilled in
  order to make d as large as possible? What is this maximum value of d?

Note:F is the focus of the parabolic path taken by the projectile and e is the directrix.
In the solution for this problem I found the following statements...

Consider an arbitrary point P on the incline, and denote the point on the directrix directly above it by Q. If there is at least one possible water
  jet trajectory passing through P, then its focus is as far from P as P is from the
  directrix e. Now consider a circle, denoted by k, that has center P and radius PQ. Let P approach the vessel on the inclined plane. At some particular point
  P', the associated circle k', with center P' and radius P'Q', touches the y-axis. The point at which it touches gives the focus F of the parabolic path followed by water that falls the maximum distance down the slope.

If the incline is steep enough, it can happen that the distance OF is larger than H
  (corresponding to a launch point below ground). By investigating the (physically)
  limiting case of OF = H, we can obtain the critical angle θ' for the slope of the incline.
If θ > θ', the best that can be done is to drill the hole at the bottom of the vessel
  (at O, where h = 0). Then, circle k' no longer touches the y-axis, but crosses it at point O.

A: Without loss of generality, let
$x = v_0 t$ and $y = -\frac{1}{2}g t^2$
so
$y = -g x^2/(2v_0^2).$
As you have found, the focus is at $(0,-v_0^2/(2g))$ and the directrix is the line $y=v_0^2/(2g)$.
The circle through a point on the parabola and the focus is given by
$(x-x_0)^2+(y-y_0)^2=r^2$
where
$y_0 = -gx_0^2/(2v_0^2)$ and
$r=(v_0^2/g+gx_0^2/v_0^2)/2$.
Setting $x=0$ and solving for $y$ we find
$y_1 = -v_0^2/(2g)$ and $y_2= v_0^2/(2g)-gx_0^2/v_0^2$.
Then $y_1=y_2$ if and only if $x_0 = \pm v_0^2/g$.
Thus, are only two points on the parabola for which there is one point of intersection with the line of symmetry.
This occurs when the particle is twice the focal length from the line of symmetry.
For all other points the circle intersects the line of symmetry at two points.
Thus, this occurs at almost all points on the trajectory---these points are not special.

Figure 1. Trajectory for $v_0=10\,\mathrm{m/s}$, $g=10\,\mathrm{m/s^2}$.


text:
Q: How to create new button runtime i use this code in vb to add a new button on runtime:
Sub AddButton(ByVal label As String, ByVal location As Point)

Dim b As Button

b = New Button
b.Location = location
b.Text = label
Me.Controls.Add(b)

End Sub

but i want to give it a name and get/set its properties and also give it new event
such as give it a click event , that change the text of my new button.
Thanks

A: You name the button like this:
Sub AddButton(ByVal label As String, ByVal location As Point)
    '...
    b.Name = "MyButton"
    '...
End Sub

And you add a click handle like this:
Sub AddButton(ByVal label As String, ByVal location As Point)
    '...
    'Option 1:
    AddHandler b.Click, Sub(sender As Object, e As EventArgs) CType(sender, Button).Text = "NewText"

    'Option 2:
    AddHandler b.Click, AddressOf MyButtonClick
    '...
End Sub

Private Sub MyButtonClick(sender As Object, e As EventArgs)
    CType(sender, Button).Text = "NewText"
End Sub


text:
Q: ViewController does not conform to protocol MSBandClientManagerDelegate I am trying to use Swift to implement the Microsoft Band SDK.  I keep getting this error when trying to set up my code.
class ViewController: UIViewController, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MSBClientManagerDelegate, UIScrollViewDelegate {

I have never seen this before, but I have also never tried to convert an Objective C sample to Swift.
Any help would be appreciated!
EDIT:  Here is the protocol from Objective C
@protocol MSBClientManagerDelegate<NSObject>

- (void)clientManager:(MSBClientManager *)clientManager clientDidConnect:(MSBClient *)client;
- (void)clientManager:(MSBClientManager *)clientManager clientDidDisconnect:(MSBClient *)client;
- (void)clientManager:(MSBClientManager *)clientManager client:(MSBClient *)client didFailToConnectWithError:(NSError *)error;

@end

EDIT 2:  After using suggested Swift Helper class
This is how I am trying to set up the connection.
 var clients:NSArray = bandHelper.attachedClients()!
    var firstClient: MSBClient = clients[0] as MSBClient

if (clients.count == 0){
    println("The band is not detected")
    return
}

I have no clue how this should be set up
bandHelper.connectClient(firstClient, {completion: (connected:true -> void in)})
println("Please wait...connecting to band")

Then, when trying to send a photo to the band, this function does not work
bandHelper.client?.personalizationManager.updateMeTileImage(bandScaledImage, { (completionHandler: NSError!) -> Void in
           NSLog("%@", NSError())})

I am getting thrown off by using the helper class.  Any help would be appreciated!

A: Sample Project
I linked a sample Swift project for Microsoft Band Kit iOS that can send a haptic to the band.  Find the link here: http://droolfactory.blogspot.com/2015/03/ios-swift-example-of-connecting-with.html

Microsoft Band Bridging Header
First to convert the Objective-C classes to be used with Swift, create a Bridging Header. Mine look like this for just the MicrosoftBandKit-iOS framework:
#ifndef ModuleName_Bridging_Header_h
#define ModuleName_Bridging_Header_h

#import <MicrosoftBandKit_iOS/MicrosoftBandKit_iOS.h>

#endif

Make sure to replace the ModuleName with the name of your apps Module. Find more on Bridging Header files at: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

Band Helper Class
Next I wrapped the MSBClientManagerDelegate in a helper class (BandManager) which uses a singleton to manage the Band. I have a gist for it here (https://gist.github.com/mthistle/8f6eb30c68a918fc6240)
The code for this the gist is:
import Foundation

let kConnectionChangedNotification = "kConnectionChangedNotification"
let kConnectionFailedNotification  = "kConnectionFailedNotification"

private let _SharedBandManagerInstance = BandManager()

class BandManager : NSObject, MSBClientManagerDelegate {

    private(set) var client: MSBClient?
    private var connectionBlock: ((Bool) -> ())?
    private var discoveredClients = [MSBClient]()

    private var clientManager = MSBClientManager.sharedManager()

    class var sharedInstance: BandManager {
        return _SharedBandManagerInstance
    }

    override init() {
        super.init()
        self.clientManager.delegate = self
    }

    func attachedClients() -> [MSBClient]? {
        if let manager = self.clientManager {
            self.discoveredClients = [MSBClient]()
            for client in manager.attachedClients() {
                self.discoveredClients.append(client as! MSBClient)
            }
        }
        return self.discoveredClients
    }

    func disconnectClient(client: MSBClient) {
        if (!client.isDeviceConnected) {
            return;
        }
        if let manager = self.clientManager {
            manager.cancelClientConnection(client)
            self.client = nil
        }
    }

    func connectClient(client: MSBClient, completion: (connected: Bool) -> Void) {
        if (client.isDeviceConnected && self.client == client) {
            if (self.connectionBlock != nil)
            {
                self.connectionBlock!(true)
            }
            return;
        }

        if let connectedClient = self.client {
            self.disconnectClient(client)
        }

        self.connectionBlock = completion;
        self.clientManager.connectClient(client)
    }

    func clientManager(clientManager: MSBClientManager!, clientDidConnect client: MSBClient!) {
        if (self.connectionBlock != nil) {
            self.client = client
            self.connectionBlock!(true)
            self.connectionBlock = nil
        }

        self.fireClientChangeNotification(client)
    }

    func clientManager(clientManager: MSBClientManager!, clientDidDisconnect client: MSBClient!) {
        self.fireClientChangeNotification(client)
    }

    func clientManager(clientManager: MSBClientManager!, client: MSBClient!, didFailToConnectWithError error: NSError!) {
        if error != nil {
            println(error)
        }
        NSNotificationCenter.defaultCenter().postNotificationName(kConnectionFailedNotification, object: self, userInfo: ["client": client])
    }

    func fireClientChangeNotification(client: MSBClient) {
        NSNotificationCenter.defaultCenter().postNotificationName(kConnectionChangedNotification, object: self, userInfo: ["client": client])
    }

}


text:
Q: Woocommerce checkout field is it possible to hide certain checkout filed in woo-commerce when user is logged in ? like i have a checkout field of Email address  i do not want my user to see this when the user is logged in  Your suggestion would be a great help.

A: Try :
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
   if(is_user_logged_in()){
      unset($fields['billing']['billing_email']);
   }
return $fields;
}

Source : https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/


text:
Q: Автоматизация проверок сайта на типовые уязвимости В этом вопросе хочется собрать список устанавливаемых локально решений и онлайн-сервисов, позволяющих автоматически протестировать сайт на типовые уязвимости, такие как XSS, CSRF, SQL инъекции, открытые листинги каталогов, открытые файлы конфигов, открытые .svn и .git, открытые phpinfo() и проч.
Задача - провести тестирование сайта перед его выкаткой в продакшен с минимальной ручной работой, в идеале - скормить сервису URL сайта и нажать кнопку "Go!", на выходе получив список уязвимостей с сортировкой по типу/критичности.

A: https://www.tinfoilsecurity.com - требуется регистрация и подтверждение владения сайтом (через DNS или выкладывание проверочного файла), после чего возможна автоматическая проверка на наличие известных системе уязвимостей. По найденным уязвимостям строится отчёт, по каждой уязвимости даются ссылки на материалы для изучения матчасти и способов закрытия уязвимости. Системе можно сказать "эту дырку я закрыл" и инициировать перепроверку - система ответит, действительно ли уязвимость перестала воспроизводиться. Работает небыстро, ругается на любые HTTP формы без капчи и на insecure куки, то есть в реальном большом проекте даст много ложно-положительных срабатываний. Первый месяц работает бесплатно, дальше - либо за деньги, либо урезанный функционал.

A: Недавно Яндекс выпустил своё открытое решение для сканирования сайтов на уязвимости - Manul.
Надо скачать .zip архив, распокавать его у себя на сайте и просто зайти на www.example.com/manul браузером - вся работа происходит прямо там.
При сканировании Manul собирает информацию обо всех файлах, лежащих в корневом каталоге и ниже его, — об их размере, дате модификации, вычисляет хэш-суммы. Параллельно каждый файл проверяется на вредоносность по приложенной антивирусной базе и помечается одним из трех флажков:

*

*желтый — в файле присутствует подозрительный код, который по различным признакам может оказаться вредоносным;

*красный — в файле присутствует известный Манулу вредоносный код;

*зеленый — в файле не найдено ничего подозрительного.

Завершив проверку, Manul сохраняет всю полученную информацию в виде XML. Фрагменты кода — как подозрительные, так и вредоносные — также прикладываются в отчет. Для просмотра отчета предлагается специальный онлайновый просмотрщик.


text:
Q: How to create a document fragment in Google Apps Script? I'm creating an app in Google Sheets using Google App Script.  The app scrapes a web page and returns an HTML page to me as a string.  I'm trying to insert it into a DOM so that I can use DOM queries to find the data I need within the page.  Normally, you could do that by either creating a document fragment with document.createDocumentFragment(), or creating a detached element with document.createElement(), then setting the innerHTML with the HTML string.  The problem is, GAS doesn't have a document context.
Does anyone have ideas for a workaround, or maybe some other way to query a large text string?
p.s. My very first instinct was to find the data I need as an API but I can't find anything that meets my needs.  Screen scraping is my last resort.
UPDATE: Thank you for whoever found and tagged the similar question.  Cheerio library for GS is the correct solution.
https://stackoverflow.com/a/61928025/735374

A: You can not create a DOM in Google Apps Script, at least not in the server-side code.
In order to query the HTML string you would need to know exactly where in the page the data you need will be with identifiable substrings such as containing element IDs - but often times these are generated and so can't be known. HTML is also famously unable to be parsed by RegEx.
You could potentially do this as a Sheets add-on, if having the script run unattended is not required. In this case the workflow would be along the lines of:

*

*Scrape the HTML data as a string

*Create an HTMLOutput object using the createHtmlOutput(html) method

*Open the HTML as a dialog or sidebar and do your querySelector calls inside the dialog. (In this case you will have to add these as code inside a <script> tag which runs on loading the page

*Return the values to Google Apps Script using google.script.run