text:
Q: Why is clang unwilling or unable to eliminate duplicate loads here Consider the following C program:
typedef struct { int x; } Foo;

void original(Foo***** xs, Foo* foo) {
    xs[0][1][2][3] = foo;
    xs[0][1][2][3]->x = 42;
}

As far as I understand, per the C standard Foo** cannot alias Foo* etc, as their types are not compatible. Compiling the program with clang 14.0 and -O3 however results in duplicate loads:
    mov     rax, qword ptr [rdi]
    mov     rax, qword ptr [rax + 8]
    mov     rax, qword ptr [rax + 16]
    mov     qword ptr [rax + 24], rsi
    mov     rax, qword ptr [rdi]
    mov     rax, qword ptr [rax + 8]
    mov     rax, qword ptr [rax + 16]
    mov     rax, qword ptr [rax + 24]
    mov     dword ptr [rax], 42
    ret

I would expect an optimising compiler to either:
(A) Assign to x on foo directly and assign foo to xs (in any order)
(B) Perform address calculations for xs once and use them for assigning foo and x.
Clang correctly compiles B:
void fixed(Foo***** xs, Foo* foo) {
    Foo** ix = &xs[0][1][2][3];
    *ix = foo;
    (*ix)->x = 42;
}

as follows: (actually turning it into A)
    mov     rax, qword ptr [rdi]
    mov     rax, qword ptr [rax + 8]
    mov     rax, qword ptr [rax + 16]
    mov     qword ptr [rax + 24], rsi
    mov     dword ptr [rsi], 42
    ret

Interestingly gcc compiles both definitions into A. Why is clang unwilling or unable to optimise the address calculation in the original definition?
Compiler Explorer Playground

A: This is a partial answer.
The loads are performed twice because the optimizer missed the optimization. It succeed to detect this specific case, but fail by reporting the following errors:

Missed - load of type ptr not eliminated in favor of load because it is clobbered by store
Missed - load of type ptr not eliminated because it is clobbered by store
Missed - load of type ptr not eliminated because it is clobbered by store
Missed - load of type ptr not eliminated because it is clobbered by store

You can see that by opening the "optimization output" window in Godbolt.
This optimization is performed by the Global Value Numbering (GVN) pass in LLVM and the specific error appears to be reported from the function reportMayClobberedLoad. The code states that the missed load-elimination is due to an intervening store (again). For more information, one certainly need to delve into the algorithm of this optimization pass. A good start seems to be the GVNPass::AnalyzeLoadAvailability function. Fortunately, the code is commented.
Note a simplified Foo** use-case is optimized and a simplified Foo*** use-case is not optimized by default, but using restrict fix the missed-optimization (it looks like the optimizer wrongly assumes that aliasing can be an issue here due to the store).
I am wondering if this could be due to the LLVM-IR which seems to make no distinction between a Foo** or Foo*** pointer types: they are apparently all considered as raw pointers. Thus, the store forwarding optimization could fail because of the store may impact any pointer of the chain and the optimizer cannot know which one due to the aliasing (itself due to the loss of pointer type). Here is the produced LLVM-IR code:
define dso_local void @original(ptr nocapture noundef readonly %0, ptr noundef %1) local_unnamed_addr #0 !dbg !9 {
  call void @llvm.dbg.value(metadata ptr %0, metadata !24, metadata !DIExpression()), !dbg !26
  call void @llvm.dbg.value(metadata ptr %1, metadata !25, metadata !DIExpression()), !dbg !26
  %3 = load ptr, ptr %0, align 8, !dbg !27, !tbaa !28
  %4 = getelementptr inbounds ptr, ptr %3, i64 1, !dbg !27
  %5 = load ptr, ptr %4, align 8, !dbg !27, !tbaa !28
  %6 = getelementptr inbounds ptr, ptr %5, i64 2, !dbg !27
  %7 = load ptr, ptr %6, align 8, !dbg !27, !tbaa !28
  %8 = getelementptr inbounds ptr, ptr %7, i64 3, !dbg !27
  store ptr %1, ptr %8, align 8, !dbg !32, !tbaa !28
  %9 = load ptr, ptr %0, align 8, !dbg !33, !tbaa !28
  %10 = getelementptr inbounds ptr, ptr %9, i64 1, !dbg !33
  %11 = load ptr, ptr %10, align 8, !dbg !33, !tbaa !28
  %12 = getelementptr inbounds ptr, ptr %11, i64 2, !dbg !33
  %13 = load ptr, ptr %12, align 8, !dbg !33, !tbaa !28
  %14 = getelementptr inbounds ptr, ptr %13, i64 3, !dbg !33
  %15 = load ptr, ptr %14, align 8, !dbg !33, !tbaa !28
  store i32 42, ptr %15, align 4, !dbg !34, !tbaa !35
  ret void, !dbg !38
}

A: The answer seems to be it's an open LLVM issue: [TBAA] Emit distinct TBAA tags for pointers with different depths,types.
Jérôme's answer tipped me off that this might have something to do with Type Based Alias Analysis (TBAA) when I noticed all loads use the same TBAA metadata.
Right now clang only emits* the following TBAA:
; Descriptors
!15 = !{!"Simple C/C++ TBAA"}
!14 = !{!"omnipotent char", !15, i64 0}
!13 = !{!"any pointer", !14, i64 0}
!21 = !{!"int", !14, i64 0}
!20 = !{!"", !21, i64 0}
; Tags
!12 = !{!13, !13, i64 0}
!19 = !{!20, !21, i64 0}

Looking at the LLVM revision I figured eventually clang might be able to emit something along the lines of:
; Type descriptors
!0 = !{!"TBAA Root"}
!1 = !{!"omnipotent char", !0, i64 0}
!3 = !{!"int", !0, i64 0}
!2 = !{!"any pointer", !1, i64 0}
!11 = !{!"p1 foo", !2, i64 0} ; Foo*
!12 = !{!"p2 foo", !2, i64 0} ; Foo**
!13 = !{!"p3 foo", !2, i64 0} ; Foo***
!14 = !{!"p4 foo", !2, i64 0} ; Foo****
!10 = !{!"foo", !3, i64 0} ; struct {int x}

; Access tags
!20 = !{!14, !14, i64 0} ; Foo****
!21 = !{!13, !13, i64 0} ; Foo***
!22 = !{!12, !12, i64 0} ; Foo**
!23 = !{!11, !11, i64 0} ; Foo*
!24 = !{!10, !3, i64 0}  ; Foo.x

(I'm still not sure I fully grok the TBAA metadata format so please excuse any mistakes)
Together with the code below LLVM produces the expected assembly.
define void @original(ptr %0, ptr %1) {
  %3 = load ptr, ptr %0, !tbaa !20
  %4 = getelementptr ptr, ptr %3, i64 1
  %5 = load ptr, ptr %4, !tbaa !21
  %6 = getelementptr ptr, ptr %5, i64 2
  %7 = load ptr, ptr %6, !tbaa !22
  %8 = getelementptr ptr, ptr %7, i64 3
  store ptr %1, ptr %8, !tbaa !23

  %9 = load ptr, ptr %0, !tbaa !20
  %10 = getelementptr ptr, ptr %9, i64 1
  %11 = load ptr, ptr %10, !tbaa !21
  %12 = getelementptr ptr, ptr %11, i64 2
  %13 = load ptr, ptr %12, !tbaa !22
  %14 = getelementptr ptr, ptr %13, i64 3
  %15 = load ptr, ptr %14, !tbaa !23 ; : Foo*
  store i32 42, ptr %15, !tbaa !24

  ret void
}

Compiler Explorer Playground
* Compiler's Explorer LLVM IR view filters these out by default but you can see them by using -emit-llvm and disabling "Directives" filtering


text:
Q: How do i call a parentfunction from a child class the inherits from a parent? I am currently working on a function, from which I want to call a parent function, from the child which is being passed to the function.
but cant seem to access the function in the parent.  Everything is public in the parent class.
So why can't from my child class access my parent function.
Example:
public class Parent
{
    public parent();
    public void oblige();

}

public class child : parent
{
    public child();
    public void work();
}

public class house
{
    public house();
    public void child_labour(Child child)
    {
        //child.base.parent.oblige()?
    }
}

A: try this:
public class Program
{
    static void Main(string[] args)
    {

        var house = new House();
        var child = new Child();
        house.child_labour(child);

        Console.ReadKey();
    }
}

public class Parent
{

    public void Oblige()
    {
       Console.WriteLine("CallOblige");
    }

}

public class Child : Parent
{
    public void Work()
    {
        Console.WriteLine("Child Working");
    }
}

public class House
{

    public void child_labour(Child child)
    {
        child.Oblige();
    }
}

When you run you'll get "CallOblige"
p.s. you need check C# syntax, as I can see you learning, too many silly errors.
You don't need a default constructor, for example.
All the best!

A: First if all you must write consturctors, methods at least empty braces. Like this.
public class Parent
{
    public Parent()
    {

    }

    public void Oblige()
    {

    }
}

The second you should read this article to undertand basic principles of accessing.
Code example:
class Program
{
    static void Main(string[] args)
    {
        House house = new House();
        Child child = new Child();
        house.child_labour(child);
    }
}

public class Parent
{
    public Parent()
    {

    }

    public void Oblige()
    {
        Console.WriteLine("Hello world");
    }
}

public class Child : Parent
{
    public Child()
    {

    }

    public void Work()
    {

    }
}

public class House
{
    public House()
    {

    }

    public void child_labour(Child child)
    {
        child.Oblige();
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Cómo mostrar una imagen Base64 en Swift? Recibo una imagen ya convertida a base 64 almacenada en mi base de datos 'Firebase', el siguiente paso es mostrar esa imagen en mi aplicación iOS escrita en Swift4.

A: Hola si viene en base 64 yo utilizo algo a si para pasarla a imagen.
En mi ejemplo yo recibo la imagen en un Rest service, como resultado la variable imagen es un String inicialmente:
var imagen = JsonUtils.stringByJSON(r["imagen"])

if imagen != nil {
   obj.imagen = imagen
   let dataImg: Data = Data(base64Encoded: imagen, options:
   NSData.Base64DecodingOptions())!

   obj.miImagen = UIImage(data: dataImg)
                }


text:
Q: How to understand logic in simple math? So this bothers me a lot and I know the logic behind it but I seem to not comprehend this logic. Please explain the following.
When I write in Python this
x = 1
x = x + 1

it means x equals 1 (logic) but the 2nd line I was told that it says, "The new value of x is equal to the old value of x , which is 1 , + 1  "  this bothers me because in math you would not have a "new value of x and an old value of x" because x will have only one value.
Also I would replace the first x so it will be like 1 = 1 + 1 (because they are 2 x-s and I replace both of them with the value of 1) which is 1=2 which is nonsense but until now that is how I would think about it.

A: When you write x = 1 that means you create a variable with the value 1.
When you write x = x + 1 that doesn't mean you compare the two sides but if you want to do that,  you write x == x + 1, not x = x + 1.
x = x + 1 means you want to add new value to x


text:
Q: Modifying in-call voice playback in Android custom ROM I would like to modify Android OS (official image from AOSP) to add preprocessing to a normal phone call playback sound.
I've already achieved this filtering for app audio playback (by modifying HAL and audioflinger).
I'm OK with targeting only a specific device (Nexus 5X). Also, I only need to filter playback - I don't care about recording (uplink).
UPDATE #1:
To make it clear - I'm OK with modifying Qualcomm-specific drivers, or whatever part that it is that runs on Nexus 5X and can help me modify in-call playback.
UPDATE #2:
I'm attempting to create a Java layer app that routes the phone playback to the music stream in real time.
I've already succeeded in installing it as a system app, getting permissions for initializing AudioRecord with AudioSource.VOICE_DOWNLINK. However, the recording gives blank samples; it doesn't record the voice call.
This is the code inside my worker thread:
// Start recording
int recBufferSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
mRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_DOWNLINK, 44100, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, recBufferSize);

// Start playback
int playBufferSize = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
mTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, playBufferSize, AudioTrack.MODE_STREAM);

mRecord.startRecording();;
mTrack.play();

int bufSize = 1024;
short[] buffer = new short[bufSize];
int res;
while (!interrupted())
{
    // Pull recording buffers and play back
    res = mRecord.read(buffer, 0, bufSize, AudioRecord.READ_NON_BLOCKING);
    mTrack.write(buffer, 0, res, AudioTrack.WRITE_BLOCKING);
}

// Stop recording
mRecord.stop();
mRecord.release();
mRecord = null;

// Stop playback
mTrack.stop();
mTrack.release();;
mTrack = null;

I'm running on a Nexus 5X, my own AOSP custom ROM, Android 7.1.1. I need to find the place which will allow call recording to work - probably somewhere in hardware/qcom/audio/hal in platform code.
Also I've been looking at the function voice_check_and_set_incall_rec_usecase at hardware/qcom/audio/hal/voice.c However, I wasn't able to make sense of it (how to make it work the way I want it to).
UPDATE #3:
I've opened a more-specific question about using AudioSource.VOICE_DOWNLINK, which might draw the right attention and will eventually help me solve this question's problem as well.

A: There are several possible issues that come to my mind. The blank buffer might indicate that you have the wrong source selected. Also since according to https://developer.android.com/reference/android/media/AudioRecord.html#AudioRecord(int,%20int,%20int,%20int,%20int) you might not always get an exception even if something's wrong with the configuration, you might want to confirm whether your object has been initialized properly. If all else fails, you could also do an
"mRecord.setPreferredDevice(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);"
to route the phone's built-in earpiece directly to the input of your recorder. Yeah, it's kinda dirty and hacky, but perhaps suits the purpose.
The other thing what was puzzling me that instead of using the builder class you've tried to configure the object directly via its constructor. Is there a specific reason why you don't want to use AudioRecord.Builder (there's even a nice example at https://developer.android.com/reference/android/media/AudioRecord.Builder.html ) instead?


text:
Q: ¿Cómo hacer una llamada a una función que contiene variables de registro? C++ Resulta que a una función le tengo que pasar varios parámetros:
Código:
const int MAX = 6;
typedef int TipoMatriz[MAX][MAX];
struct TipoZona{
    int ancho;
    int alto;
};

En el siguiente módulo:
bool esPosibleRellenarZona (TipoZona zona, int fila, int columna, TipoMatriz M);

... no sé pasarle muy bien lo de TipoZona zona y TipoMatriz M para que lo calcule.

A: TipoZona y TipoMatriz son Objetos asi que debes tener un clase que se llame TipoZona y otra clase que se llame TipoMatriz y ya de ahí los obtienes, te dejo como es la creación de una clase en c++, y cabe destacar que sus atributos son privados:
//Esto define la clase TipoMatriz
class TipoMatriz{
};


text:
Q: Luego de tomar una foto Camera.TakePhoto() no funciona la inicialización de variables En un evento al utilizar la función Camera.TakePhoto(), al retornar de tomar la foto, y dentro del mismo evento, las variables que inicializo no toman el valor nuevo, continúan con el viejo.
Se tiene un botón X que llama al evento 'Procesar'.
Este evento verifica si el nombre del empleado (cargado antes) no es vacío. Si no lo es, procesa, luego se actualiza la variable &EmployeeName = ''

*

*Si tomo la foto y luego de finalizar el evento, vuelvo a presionar el mismo botón, vuelve a entrar porque la variable &EmployeeName sigue cargada y no la actualizó.

*Si no tomo la foto, al presionar el botón X, no procesa porque la variable &EmployeeName esta inicializada.

Ejemplo:
Event 'Procesar'
    composite
        If not &EmployeeName.IsEmpty()
            If &DeviceTakePhoto = 'S'
                Do 'TakePhoto'
                If &Image.IsEmpty()
                    msg('Debe tomar una foto!')
                    &HayFoto = 'N'
                Else
                    &HayFoto = 'S'
                EndIf
            EndIf
            If  ( (&DeviceTakePhoto = 'S' and &HayFoto <> 'N') or &DeviceTakePhoto <> 'S' )
                &EmployeeName     = ''
            EndIf
        EndIf
    EndComposite
EndEvent

Sub 'TakePhoto'
    &Image = Camera.TakePhoto()
EndSub

Dentro del 'Procesar' original, llamo a otros procs() que no cambian en nada la operativa, también funciona bien si obtengo la geolocalización.
Ya probé poner la llamada de Camera.TakePhoto() en el evento 'Procesar' y pasa lo mismo, de hecho, era como estaba siempre pero lo saqué para probar.

A: Mauricio, estoy tratando de reproducir este problema sin éxito.
Aquí puedes encontrar el apk de ejemplo y se comporta como es esperado:
Apk:
http://apps5.genexus.com/Id09ca2f2c930605d40267ac204495c800/TestTakePhoto.apk
Xpz:
http://apps5.genexus.com/Id09ca2f2c930605d40267ac204495c800/gxmetadata/TestTakePhoto.xpz
Primer click toma la foto. Siguiente no lo hace porque ya hay una.
Estoy probando con Genexus v15 u7, Android 8.0.
Por favor , si este ejemplo no funciona en tu dispositivo enviame los datos del device.
Si funciona, envianos tu ejemplo para evaluar las diferencias y en que versión de Genexus lo estas haciendo.
Gracias,

A: Tuve el mismo problema con dispositivos Samsung, concretamente con un S4 y un S8,instalando el preview de U9 me solicionó el problema.
Te paso el SAC #42769: Imagen tomada desde algunos dispositivos Android queda vacía y no presenta error.


text:
Q: Change the color of the turtle on the move I'm writing a program about traffic in roundabouts. I have 3 colors for 3 different directions car was red car turn right, go straight green car, sky turn left. because there is one lane for turning right should not I want to change the car red car blue sky or other AU to the cars that did not go right anymore?
What function should I use to change the color of the car?

A: This will not be correct because I can't work out exactly what you need from the question, but you need to use the with statement to identify the correct cars. Here is something that is close to what I think you want:
to ...
  ...
  let to-be-red cars with [ (heading = 0 or heading = 180)
                            and distancexy 0 0 < 30
                            and ycor < -11 ]
  ask to-be-red [ set color red ]
end


text:
Q: SQL Update doesn't save affected rows? I'm still new to a lot of core SQL, so here's my issue:
I have a table with a lot of columns named C441, C442, C443, etc. and I'm trying to loop them and change the SMALLINT value to 1 in all of them, this is what I've tried:
DECLARE @count INT;
DECLARE @field varchar(max);

SET @count = 441;

WHILE (@count < 551)
BEGIN
    SET @field = ('C' + CAST(@count AS VARCHAR));
    PRINT @field;

    UPDATE #tablenamenotrelevant#
    SET @field = 1
    WHERE [MemberId] = 1060;

    SET @count = (@count + 1);
END

It does print the column names correctly, e.g.
(1 row(s) affected)
C442

(1 row(s) affected)
C443

(1 row(s) affected)
C444

But when I select the values from the table, they aren't changed, what simple thing am I missing?
I'm using SQL Server 2012 Management Studio.

A: You need to use dynamic TSQL:
 declare @sql varchar(1000)
 set @sql = 'UPDATE #tablenamenotrelevant# SET ' + @field + ' = 1 WHERE [MemberId] = 1060;'
 exec (@sql)

or possibly better still, create a single update statement setting all relevant columns and execute that.


text:
Q: why after applying my function to the array it returns the same array? I'm looping over an array with my function compare to get the max number of temperature from the array but there was no any changes after applying the function to the array temperature.

let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];

function compare(temperature) {
  let i = 0;

  for (i = 0; i < temperature.length; i++) {
if (typeof temperature[i] === "string") temperature.splice(i, 1);
  }

  for (let k = i + 1; k < temperature.length; k++) {
if (temperature[i] < temperature[k]) Array.splice(i, 1);
else if (temperature[i] > temperature[k]) Array.splice(k, 1);
  }
  return temperature;
}

console.log(temperature);

A: Check this out!
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];

function compare(temperature) {
    let i = 0;

    for (i = 0; i < temperature.length; i++) {
        if (typeof temperature[i] === "string")
            temperature.splice(i, 1);
    }

    for (let k = i + 1; k < temperature.length; k++) {
        if (temperature[i] < temperature[k])
            Array.splice(i, 1);

        else if (temperature[i] > temperature[k])
            Array.splice(k, 1);
    }
    return temperature;
}

console.log(compare(temperature));

A: You can achieve this with a single line of code by using Math.max() on array.
Working Demo :

// Input array
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];

// Math.max() to get maximum number element from an array.
const maxTemp = Math.max(...temperature.filter(elem => typeof elem !== 'string'));

// Result
console.log(maxTemp);


text:
Q: How to enable plymouth bootscreen animation? My netbook, running Lucid, can't display bootscreen animation. I want to know how to enable it.
My netbook is Acer Aspire One D260. Intel Atom N450, 1GB RAM and GMA 3150.
I know a tool called rcconf able to turns on/off services using the scripts in
/etc/init.d/. I thought maybe plymouth can be initialized there but I'm not really sure and I don't how to do it.
Thank you.

A: Keeping it disabled, helps your computer to boot faster. It can be enabled and customized from Plymouth manager, which you can install from Ubuntu Software Center.


text:
Q: Get occurences of past 2 weeks on any given date I have data like
id | date   |
-------------
 1 | 1.1.20 |
 3 | 4.1.20 |
 2 | 4.1.20 |
 1 | 5.1.20 |
 6 | 2.1.20 |

What I would like to get is to get the amount of occurrences an user with ID did in the past 2 weeks on any given date so basically "occurences between date - 14 days and date. I'm trying to categorize users by their amount of sessions past 2 weeks, and I'm following them by daily cohorts.
This query does not work since there can be days when the user does not log in aka does not have a row:
COUNT (distinct id) OVER (PARTITION BY id ORDER BY date ROWS BETWEEN 14 PRECEDING AND  0 FOLLOWING)

A: Unfortunately, Presto does not support range() window functions.  One method is a self-join/aggregation or correlated subquery:
select t.id, count(tprev.id)
from t left join
     t tprev
     on tprev.id = t.id and
        tprev.date > t.date - interval '13' day and
        tprev.date <= t.date
group by t.id;

This interprets your request as wanting 14 days of data, including the current day.
Another method that is much more verbose but might be faster is to use lag() . . . and lag() again:
select t.id,
       (1 +   -- current date
        (case when lag(date, 1) over (partition by id order by date) > date - interval '14' day then 1 else 0 end) +
        (case when lag(date, 2) over (partition by id order by date) > date - interval '14' day then 1 else 0 end) +
        . . .
        (case when lag(date, 13) over (partition by id order by date) > date - interval '14' day then 1 else 0 end) +
       ) as cnt_14
from t;


text:
Q: DNS Server Routing I have a local DNS server setup to resolve things like myserver.mydomain.com myserver2.mydomain.com to specific internal servers. Now if i map those subdomains externally to the external ip of my local DNS, is there a way that I could get those to map so that they work externally as well as internally without some type of VPN?

A: Yes, but since the public DNS hierarchy will not know about "mydomain.com", you'll need to configure the client to use your own DNS server as resolver.
BIND can do both resolver (for your client) and authority (for publishing zone *.mydomain.com) at the same time. You can use BIND views to "restrict" the zone to your client only (and not other Internet hosts).
If you use a DNS server other than BIND, one that splits resolver and authority, you'll need to also tell your resolver "query  for anything like *.mydomain.com".


text:
Q: Tasks which contains smaller tasks with ACK from Consumer I am working on some POC project and trying to solve the following problem.
I have a Publisher which is sending a messages to the Queue:
bus.PublishAsync<IBaseScenario>(new TestScenario())
            .ContinueWith(task =>
            {
                if (task.IsCompleted && !task.IsFaulted)
                    Console.WriteLine("TestScenario queued with success.");
                else
                    Console.WriteLine(task.Exception.Message);
            });

And some Consumers which are consuming a messages:
bus.SubscribeAsync<IBaseScenario>("test_1_consumer",
            message => Task.Factory.StartNew(() =>
            {
                var testScenario = message as TestScenario;
                var anotherTestScenario = message as AnotherTestScenario;

                ResolveScenario(testScenario);
                ResolveScenario(anotherTestScenario);

            }).ContinueWith(task =>
            {
                if (task.IsCompleted && !task.IsFaulted)
                    Console.WriteLine("Task ended up with success.");
                else
                    Console.WriteLine(task.Exception.Message);
            }));

At this point everything is working as needed, but here is what I would like to achieve.
My Message is some kind of Scenario which contains steps, each Scenario is sent to the Queue and then maintained by a Consumer.

*

*I would like to get a some kind of ACK info from Consumer sent to Publisher everytime when the each Step is done on the Consumer site (for example if its ended up with success or not.

*I would like to get also an info about which Consumer got the Message.
Every Message (Scenario) should be treated as atomic operation, so there should not be possible to doing steps on different Consumers and if some Step will end without success, then the whole scenario should be treated as failed.
Are these 2 requirements possible to solve using the following architecture or do I need to use something more?

A: The easiest thing to do would be to use EasyNetQ's request response model described here https://github.com/EasyNetQ/EasyNetQ/wiki/Request-Response
In the response you can put the identity of the consumer that processed the message and the final status of the scenario. If one scenario is sent in one message, and that scenario contains all the steps necessary then all steps would be processed by a single consumer.
That said, message duplication is always a problem due to either sending the message twice or a message being requeued after a consumer fails. If it is critical that a scenario NEVER be processed more than once, then you will need to implement message deduplication or make each scenario idempotent. That is a general fact of life when working with RabbitMQ.


text:
Q: Do a less on file returned by which command I have a file which is in one of the folders in the $PATH. I want to see the contents of it using less. Problem is I seem to need to run which command to find the actual location and then do less on it.
e.g.
> which students.csv
/opt/files/students.csv
> less /opt/files/students.csv

Is there a way to combine these two commands and do less on the ouput of which command? Thanks.

A: You can run
less `which students.csv`

Recent shells also allow
less $(which students.csv)


text:
Q: Why does sql ignores my sentence? I`m making a filter for a real estate business. They have several properties and filters to get them as the customer fetches.
I'm having a problem where after various OR setences Mysql ignores the sentences detailed after this OR.
SELECT * FROM props WHERE tipo = 'Casas_Casa' OR tipo = 'Departamentos_Duplex' OR tipo = 'Casas_Chalet' OR tipo = 'Casas Condominio' OR tipo = 'Countries y Barrios cerrados_Casas' OR tipo = 'Countries y Barrios cerrados_Casas' OR tipo = 'PH' AND operacion = 'Alquiler' ORDER BY modif DESC

Mysql responds whith all the OR's but does not recognises the 'operacion' value but it does order them.

A: The reason for this is that AND has higher precedence than OR, so the AND operacion = 'Alquiler' portion of the condition is "tied to" the 'PH' constraint alone.
Add parentheses to force the correct precedence:
SELECT *
FROM props
WHERE (tipo = 'Casas_Casa'
    OR tipo = 'Departamentos_Duplex'
    OR tipo = 'Casas_Chalet'
    OR tipo = 'Casas Condominio'
    OR tipo = 'Countries y Barrios cerrados_Casas'
    OR tipo = 'Countries y Barrios cerrados_Casas'
    OR tipo = 'PH')
AND operacion = 'Alquiler'
ORDER BY modif DESC

You can also use IN expression to simplify your condition:
SELECT *
FROM props
WHERE tipo IN (
    'Casas_Casa'
,   'Departamentos_Duplex'
,   'Casas_Chalet'
,   'Casas Condominio'
,   'Countries y Barrios cerrados_Casas'
,   'Countries y Barrios cerrados_Casas'
,   'PH')
AND operacion = 'Alquiler'
ORDER BY modif DESC


text:
Q: Custom Component's form tag has action="[parent page]" I have a custom component that includes a logout button (using a commandButton) which is used on several pages of a Force.com site. I have written a controller for this component which includes a simple action for the button which sets a cookie and then logs the user out by returning a PageReference to the login page.
However, when I click the logout button, the user is not redirected to the login page, but rather to the actual parent page of the custom component (i.e. the page that the user is already on). On inspection of the generated HTML I see that the component has a form tag which  has an action set to the url of the parent page.
So when I click on the commandButton the button must be submitting this form rather than using the returned PageReference from the controller. I can see that the component controller action is running and is returning the correct url.
I wonder first of all why the form for this component is being generated with the action having it's parent page's url, and secondly if this is obligatory then how I can prevent this.
public PageReference setCookieAndLogOut() {

    Util u = new Util();
    u.setUserLoggedOutAndExpireWebsiteSession(sessionId);

    PageReference pRef = new PageReference('/apex/loginpage');
    pRef.setRedirect(true);
    return pRef;
}

<apex:component controlle="mycontroller">
    <apex:form>
        <apex:commandButton action="{!setCookieAndLogOut}" value="Log Out" />
    </apex:form>
</apex:component>

Generated HTML:
<form id="thePage:j_id6:j_id7:j_id11" name="thePage:j_id6:j_id7:j_id11" method="post" action="/homepage" enctype="application/x-www-form-urlencoded">
    <input type="submit" name="thePage:j_id6:j_id7:j_id11:j_id13" value="Log Out">
</form>

Many thanks

A: A custom component is rendered as part of the parent apex:page, and an apex:form in a custom component is rendered as part of the page.  It has to submit (action='...') to the parent page - the component only exists in the context of the parent.  But other parts of the page (including hidden inputs) route the action to the component's controller.  If you aren't ending up on the page expected, it's probably due to an issue with setCookieAndLogOut().  You could start with a debug statement in setCookieAndLogOut to confirm to yourself that the controller method is being called.
Is 'loginpage' an apex page you've created?  If so, you'll need '/apex/loginpage'.  I don't believe PageReference('loginpage') will produce a link to the system login page.  I can't find documentation of it, and it doesn't work for me in a dev org.
I'm not clear what your cookie logic is; if you just need a link to log the user out Salesforce, the following should work:
<apex:outputLink value="{!URLFOR('/secur/logout.jsp')}" >Logout</apex:outputLink>

Warning: this isn't documented behavior; it's relying on the system logout link being located at /secure/logout.jsp, and so could change in the future.  That said, I'm not aware of a documented method of adding a logout link to a page or forcing a logout via apex code.

A: The apex:form tag supports "pass through attributes" From the documentation:
To add a pass-through attribute to, for example, an  component, prefix the attribute with "html-" and set the attribute value as normal.

<apex:outputPanel layout="block" html-data-role="panel" html-data-id="menu">
    <apex:insert name="menu"/>
</apex:outputPanel>

<apex:outputPanel layout="block" html-data-role="panel" html-data-id="main">
    <apex:insert name="main"/>
</apex:outputPanel>

This produces the following HTML output.

div id="..." data-id="menu" data-role="panel">

/div>
div id="..." data-id="main" data-role="panel">

/div>
you should be able to pass through an "action" attribute that will then submit the form to the page you want.


text:
Q: How do I access a mounted Windows server from the command line I don't know much about networking so please help me.
I am using Ubuntu 16.04 and I connect to windows server of my university by going to Places > Connect to Server and there I enter smb://fileserver2 followed by my user-name and password and I easily access whatever I want to access from nautilus but I want to access this server from command terminal(like other mounted drives by going to /media) so how can I do that?
P.S.- I have already seen How do I access a mounted Windows share from the command line? and this does not help.


text:
Q: flow from setup to teardown in robotium what is the flow of the program in robotium.I mean are  setup() and teardown() called for every testcase separately ??
option 1
setup()
TC01
teardown()
setup()
TC02
teardown()
or option2
setup()
TC01
TC02
TC03
teardown()

A: Setup is called before every test method and teardown is called after every test method.
So the answer is option 1.


text:
Q: How to change the Material design EditText theme color Programmatically I've tried this solution and worked fine in XML, But how I can do the samething via code ?

Actually I wanna change edittext (theme: lable, text color, line color) on press of a button.

A: In Android changing the style after creating the view is not supported. That is you can't set a style to the view dynamically. But what you can do is create that view in xml, set the style you want in the xml only and when you want to show a view, you inflate it.
e.g.
    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="This is a template"
    style="@style/my_style" />

and now inflate tis view wherever you want to use as,
TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);


text:
Q: Julia - is ulimit working with a Julia session? I search and it doesn't seem to have a Julia core way to limit RAM used so I search Linux instead.
According to this question, I can limit the RAM used by my command to 64GB with:
ulimit -v 64000000

I am wondering if I do:
$ulimit -v 64000000
$julia
$julia>

Am I doing everything alright, i.e., everything I do like launching a JuMP model within my Julia console will be limited to 64GB of RAM?

A: Since ulimit appears to set resource limits for your entire user account, I can find no reason why this should not also apply to Julia processes run under that user account.
The one exception that comes to mind might be if you are running Julia processes on multiple nodes of a linux cluster with, e.g. the Distributed.jl stdlib, but this is a rather niche case.


text:
Q: How not to get a gtkdrawingarea cleared in the draw event? My drawingarea is cleared everytime the draw event is called.
How to avoid a drawingarea to be cleared ?
Thanks
#!/usr/bin/env python3

import gi
gi.require_version('Gtk','3.0')
from gi.repository import Gtk, Gdk
import cairo
import math

class MouseButtons:
    LEFT_BUTTON = 1
    RIGHT_BUTTON = 3

class Example(Gtk.Window):

    def __init__(self):
        super(Example, self).__init__()

        self.init_ui()

    def init_ui(self):

        self.darea = Gtk.DrawingArea()
        self.darea.connect("draw", self.on_draw)
        self.darea.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)

        self.add(self.darea)

        self.set_title("Fill & stroke")
        self.resize(230, 150)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.connect("delete-event", Gtk.main_quit)

        self.darea.connect("button-press-event", self.on_button_press)

        self.coords = []
        self.show_all()

    def on_draw(self, wid, cr):

        cr.set_source_rgb(0.6, 0.6, 0.6)
        cr.arc(self.coords[0], self.coords[1], 40, 0, 2*math.pi)
        cr.fill()

    def on_button_press(self, w, e):

        if e.type == Gdk.EventType.BUTTON_PRESS \
            and e.button == MouseButtons.LEFT_BUTTON:
            self.coords = [e.x, e.y]

        self.darea.queue_draw()

def main():
    app = Example()
    Gtk.main()

if __name__ == "__main__":
    main()

In this example, each time I click on the drawingarea, a circle is drawn. I would like to draw the new circle but without to redrawing the previous one.
Is it possible ?

A: I would recommend adjusting your mental model of the drawing area; don't think of it as being "cleared" every time the draw handler is called. Rather, think of it like this: the draw handler is called every time the drawing area needs to be redrawn from scratch (among other reasons: because some other window moved in front of it, or because your program asked for a draw update). The drawing area's contents, once drawn, are not persisted anywhere.
If you need persistent window contents, then you should use a backing store and draw that onto the screen in the draw handler, or you could use a canvas library if you want to treat existing drawn objects as independently existing.

A: I found he answer :
#!/usr/bin/env python3

import gi
gi.require_version('Gtk','3.0')
from gi.repository import Gtk, Gdk
import cairo
import math

class MouseButtons:
    LEFT_BUTTON = 1
    RIGHT_BUTTON = 3

class Example(Gtk.Window):

    def __init__(self):
        super(Example, self).__init__()
        self.init_ui()

    def init_ui(self):

        self.darea = Gtk.DrawingArea()
        self.darea.connect("draw", self.on_draw)
        self.darea.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)

        self.add(self.darea)

        self.set_title("Fill & stroke")
        self.resize(230, 150)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.connect("delete-event", Gtk.main_quit)

        self.darea.connect("button-press-event", self.on_button_press)
        self.show_all()

        a = self.darea.get_allocation()
        print (a.x, a.y, a.width, a.height)
        self.img = cairo.ImageSurface(cairo.Format.RGB24, a.width, a.height)

    def on_draw(self, wid, cr):
        cr.set_source_surface(self.img, 0, 0)
        cr.paint()

    def on_button_press(self, w, e):
        if e.type == Gdk.EventType.BUTTON_PRESS \
            and e.button == MouseButtons.LEFT_BUTTON:
            cr = cairo.Context(self.img)
            cr.set_source_rgb(0.6, 0.6, 0.6)
            cr.arc(e.x, e.y, 40, 0, 2*math.pi)
            cr.fill()

        self.darea.queue_draw()

def main():
    app = Example()
    Gtk.main()

if __name__ == "__main__":
    main()


text:
Q: Interacting with axSockwavePlayer playing a youtube video in Winforms c#? Short Question:
How could I get events from an axShockwavePlayer playing youtube videos?
(events such as "video playing" and "paused")

Long Question:
I have an application in winforms with a shockwave player.
In it I play youtube videos and I was wondering if I could interact with the youtube player in my application.
I'm trying to get the state of the player and change my background music according to it.
Searching around I found this question:
How to control the youtube flash player with c#?
and the great
answer.
(both from 2012)
Playing around with it I found out that appearently the answer is too old, and won't work for me.
The posted answer includes simple debuging, and this is what i got for clicking the player (and start playing the video):
ytbPlayer FlashCall: raw: <invoke name="isNaN" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "isNaN()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="
        (function() {
          try {
            yt.www.watch.ads.checkInit();
            return true;
          } catch (e) {
            window['adModuleLoaded'] = true;
            return false;
          }
        })" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "
        (function() {
          try {
            yt.www.watch.ads.checkInit();
            return true;
          } catch (e) {
            window['adModuleLoaded'] = true;
            return false;
          }
        })()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.top.location.href.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.top.location.href.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="googletag.cmd.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "googletag.cmd.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="googleGetCompanionAdSlots" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "googleGetCompanionAdSlots()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="google_get_companion_slot_params" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "google_get_companion_slot_params()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.top.location.href.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.top.location.href.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.top.location.href.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.top.location.href.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.height.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.height.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.width.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.width.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="navigator.javaEnabled" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "navigator.javaEnabled()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.history.length.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.history.length.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.availHeight.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.availHeight.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.availWidth.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.availWidth.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.colorDepth.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.colorDepth.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.navigator.plugins.length.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.navigator.plugins.length.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.navigator.mimeTypes.length.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.navigator.mimeTypes.length.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="yt.util.activity.getTimeSinceActive" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "yt.util.activity.getTimeSinceActive()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.top.location.href.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.top.location.href.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="google_show_companion_ad" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "google_show_companion_ad()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="Goog_AdSense_Lidar_sendVastMessage" returntype="xml"><arguments><string>expandedChanged</string><string>741024059.2435002</string><object><property id="opt_bounds"><object><property id="width
"><number>431</number></property><property id="height"><number>62</number></property><property id="expanded"><false/></property><property id="left"><number>20</number></property><property id="top"><number>128</number></property></o
bject></property></object></arguments></invoke>
ytbPlayer_FlashCall: "Goog_AdSense_Lidar_sendVastMessage(expandedChanged741024059.24350024316220128)
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="Goog_AdSense_Lidar_getUrlSignalsList" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "Goog_AdSense_Lidar_getUrlSignalsList()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="Goog_AdSense_Lidar_sendVastMessage" returntype="xml"><arguments><string>expandedChanged</string><string>741024059.2435002</string><object><property id="opt_fullscreen"><false/></property><pro
perty id="opt_bounds"><object><property id="width"><number>431</number></property><property id="height"><number>62</number></property><property id="expanded"><true/></property><property id="left"><number>20</number></property><prop
erty id="top"><number>128</number></property></object></property></object></arguments></invoke>
ytbPlayer_FlashCall: "Goog_AdSense_Lidar_sendVastMessage(expandedChanged741024059.24350024316220128)
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="googletag.cmd.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "googletag.cmd.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="googleGetCompanionAdSlots" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "googleGetCompanionAdSlots()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="google_get_companion_slot_params" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "google_get_companion_slot_params()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.top.location.href.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.top.location.href.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.height.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.height.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.width.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.width.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="navigator.javaEnabled" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "navigator.javaEnabled()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.history.length.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.history.length.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.availHeight.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.availHeight.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.availWidth.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.availWidth.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.screen.colorDepth.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.screen.colorDepth.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.navigator.plugins.length.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.navigator.plugins.length.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.navigator.mimeTypes.length.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.navigator.mimeTypes.length.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="yt.util.activity.getTimeSinceActive" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "yt.util.activity.getTimeSinceActive()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.top.location.href.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.top.location.href.toString()
YTplayer_FlashCall: unknownCommand
ytbPlayer FlashCall: raw: <invoke name="window.document.referrer.toString" returntype="xml"><arguments></arguments></invoke>
ytbPlayer_FlashCall: "window.document.referrer.toString()
YTplayer_FlashCall: unknownCommand

This is the code I used:
 private void ytbPlayer_FlashCall(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FlashCallEvent e) //asigned as an event handler for FlashCall
        {
            Console.Write("ytbPlayer FlashCall: raw: " + e.request.ToString() + "\r\n");
            // message is in xml format so we need to parse it
            XmlDocument document = new XmlDocument();
            document.LoadXml(e.request);
            // get attributes to see which command flash is trying to call
            XmlAttributeCollection attributes = document.FirstChild.Attributes;
            String command = attributes.Item(0).InnerText;
            // get parameters
            XmlNodeList list = document.GetElementsByTagName("arguments");
            List<string> listS = new List<string>();
            foreach (XmlNode l in list)
            {
                listS.Add(l.InnerText);
            }
            Console.Write("ytbPlayer_FlashCall: \"" + command.ToString() + "(" + string.Join(",", listS) + ")\r\n");
            // Interpret command
            switch (command)
            {
                case "onYouTubePlayerReady": YTready(listS[0]); break;
                case "YTStateChange": YTStateChange(listS[0]); break;
                case "YTError": YTStateError(listS[0]); break;
                default: Console.Write("YTplayer_FlashCall: unknownCommand\r\n"); break;
            }
        }

        private string ytbPlayer_CallFlash(string ytFunction)
        {
            string flashXMLrequest = "";
            string response = "";
            string flashFunction = "";
            List<string> flashFunctionArgs = new List<string>();

            Regex func2xml = new Regex(@"([a-z][a-z0-9]*)(\(([^)]*)\))?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Match fmatch = func2xml.Match(ytFunction);

            if (fmatch.Captures.Count != 1)
            {
                Console.Write("bad function request string");
                return "";
            }

            flashFunction = fmatch.Groups[1].Value.ToString();
            flashXMLrequest = "<invoke name=\"" + flashFunction + "\" returntype=\"xml\">";
            if (fmatch.Groups[3].Value.Length > 0)
            {
                flashFunctionArgs = parseDelimitedString(fmatch.Groups[3].Value);
                if (flashFunctionArgs.Count > 0)
                {
                    flashXMLrequest += "<arguments><string>";
                    flashXMLrequest += string.Join("</string><string>", flashFunctionArgs);
                    flashXMLrequest += "</string></arguments>";
                }
            }
            flashXMLrequest += "</invoke>";

            try
            {
                Console.Write("YTplayer_CallFlash: \"" + flashXMLrequest + "\"\r\n");
                response = ytbPlayer.CallFunction(flashXMLrequest);
                Console.Write("YTplayer_CallFlash_response: \"" + response + "\"\r\n");
            }
            catch
            {
                Console.Write("YTplayer_CallFlash: error \"" + flashXMLrequest + "\"\r\n");
            }

            return response;
        }

        private static List<string> parseDelimitedString(string arguments, char delim = ',')
        {
            bool inQuotes = false;
            bool inNonQuotes = false;
            int whiteSpaceCount = 0;

            List<string> strings = new List<string>();

            StringBuilder sb = new StringBuilder();
            foreach (char c in arguments)
            {
                if (c == '\'' || c == '"')
                {
                    if (!inQuotes)
                        inQuotes = true;
                    else
                        inQuotes = false;

                    whiteSpaceCount = 0;
                }
                else if (c == delim)
                {
                    if (!inQuotes)
                    {
                        if (whiteSpaceCount > 0 && inQuotes)
                        {
                            sb.Remove(sb.Length - whiteSpaceCount, whiteSpaceCount);
                            inNonQuotes = false;
                        }
                        strings.Add(sb.Replace("'", string.Empty).Replace("\"", string.Empty).ToString());
                        sb.Remove(0, sb.Length);
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    whiteSpaceCount = 0;
                }
                else if (char.IsWhiteSpace(c))
                {
                    if (inNonQuotes || inQuotes)
                    {
                        sb.Append(c);
                        whiteSpaceCount++;
                    }
                }
                else
                {
                    if (!inQuotes) inNonQuotes = true;
                    sb.Append(c);
                    whiteSpaceCount = 0;
                }
            }
            strings.Add(sb.Replace("'", string.Empty).Replace("\"", string.Empty).ToString());

            return strings;
        }

        private void YTready(string playerID)
        {
            //YTState = true;
            //start eventHandlers
            ytbPlayer_CallFlash("addEventListener(\"onStateChange\",\"YTStateChange\")");
            ytbPlayer_CallFlash("addEventListener(\"onError\",\"YTError\")");
        }

        private void YTStateChange(string YTplayState)
        {
            switch (int.Parse(YTplayState))
            {
                case -1: gm_Name.Text = "not started"; break; //not started yet
                case 1: Console.WriteLine("playing");  break; //playing
                case 2: Console.WriteLine("paused"); break; //paused
                                                  //case 3: ; break; //buffering
                case 0: Console.WriteLine("YOU"); break; //ended
            }
        }
        private void YTStateError(string error)
        {
            Console.Write("YTplayer_error: " + error + "\r\n");
        }

Looking at the debug code, I found no keyword that could have me know that the user clicked the shockwaveplayer.
How could I change the code to match the current youtube api?

A: My problem turned out to be that the youtube API wasn't turned on, because I directed my ShockwavePlayer to a wrong youtube video adress.
Instead of:
ytbPlayer.Movie = @"http://www.youtube.com/v/" + video;

I should have wrote:
ytbPlayer.Movie = @"http://www.youtube.com/v/" + video + "?version=3&enablejsapi=1";


text:
Q: Image editor SDK for android Need to integrate a image editing component to my android application . Is there any SDK to implement this . Or can I implement it through inbuilt image editor in android through intent like this
Intent editIntent = new Intent(Intent.ACTION_EDIT);
editIntent.setDataAndType(uri, "image/*");
editIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(editIntent, null));

A: There are many Image editor available on market but the best one I find is Creative SDK which is acquired by adope.Try this SDK
https://creativesdk.adobe.com/


text:
Q: "Modernized" OAUTH: callback not triggering This is in reference to:
https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html
which asks to post questions on stack overflow under #google-oauth.
Two questions from the developer of an email app for Android, trying to implement the "modernized" OAUTH flow as described at the link above.
1 - I registered my callback URI in Google Developer Console, looks like this: org.kman.AquaMail:/oauth2redirect
2 - My code builds an approval URI, based on https://accounts.google.com/o/oauth2/auth, basically same as it did for WebView, but the redirect_uri parameter is the above custom scheme URI.
3 - I am able to bring up this approval URI in a Chrome Custom Tab
4 - Added this to my manifest, copied it out of AppAuth-Android sample:

  <!-- OAUTH result activity for Gmail -->

  <activity android:name=".mail.oauth.OAuthGmailResultActivity">
      <intent-filter>
          <action android:name="android.intent.action.VIEW"/>

          <category android:name="android.intent.category.DEFAULT"/>
          <category android:name="android.intent.category.BROWSABLE"/>

          <data android:scheme="org.kman.AquaMail"/>

( argh, the markdown parser ate the closing tags for intent-filter and activity, but they're there )
So far so good (almost).
Now this turns bad:
When I actually sign in, in the Chrome Custom Tab, and grant the permissions by pressing "allow" on the screen that says "app would like to" --
My "result activity" the one with the intent filter for my custom scheme, does not get invoked.
Instead the Chrome Tab just redirects to google.com (.ru in my case).
There is nothing interesting in the logcat (such as a failed attempt to run this activity).
How do I go about debugging this?
PS - I know the approval_url with the custom scheme is there, I can see it  in the Chrome Tab if I tap the "three dots" and then the "info" icon.

A: Duh. In case someone else runs into this.
By the time the approval_url makes it back to my app, it's been converted to lowercase.
So org.kman.AquaMail:/oauth2redirect becomes org.kman.aquamail:/oauth2redirect.
And so the intent filter for the "result activity" needs to have the scheme in lowercase as well.


text:
Q: Store information in wish list and cart with cookies ($_COOKIE) For a long time without developing, soon after the resumption I find myself encountered with a big problem that I find in my project in which I am now developing in PHP, which consists of the use of $_COOKIE to save information from a wish list and shopping cart on a page, through requests $_GET or $_POST. I found the request $_GET the simplest way to save and redirect information to specific places within the schedule, such as for a session variable or even to a database.
I am through the following challenge, store information of items (books) in the shopping cart when added by the customer and still to complete, save the desired products by the same to later buy or even make some order with it. It's a complex problem to solve or I'm making it difficult for all programming logic to find a solution to solve this case myself.
Being a little more specific regarding the specifications of the problem, I have to make a shopping cart so that the customer has on the home page, options such as adding the book to the shopping list, declaring the amount of items you want to buy and with this through requisitions $_GET, the item is added to the cart using $_SESSION. At first this solution was working, but then came the biggest challenge to be developed, turning the session into cookies. Initially, I was writing some functions that were and is still working for the cart cookie, now for the wish list encounter difficulties in storing the customer's book wishes within it, mainly in relation to the attempt to delete 2 or more items from the wish list. The source code below reflects well the problem I'm going through:
conn.php
<?php
if (!isset($_COOKIE['cart'])) {
    setcookie('cart', json_encode([]), time() + 604800);
}

if (!isset($_COOKIE['desire'])) {
    setcookie('desire', json_encode([]), time() + 604800);
}

if (!isset($_COOKIE['total_value_buy'])) {
    setcookie('total_value_buy', 0, time() + 604800);
}

// CART FUNCTIONS

function addbook($id_book, $qtd) {
    $book = listbook($id_book);

    if ($qtd <= $book["number_copies"] && $qtd > 0) {
        $validation = false;
        foreach (json_decode($_COOKIE['cart']) as $key => $book) {
            if ($book->id_book == $id_book) {
                $validation = true;
                editbook($id_book, ($book->qtd_book + $qtd));
            }
        }

        if ($validation == false) {
            $book = ["id_book" => $id_book, "qtd_book" => $qtd, "vl_book" => $book["vl_book"]];
            $cart = json_decode($_COOKIE['cart']);
            array_push($cart, $book);
            setcookie('cart', json_encode($cart), time() + 604800);
        }
        return ("book added to cart");
    } else {
        return ("book not added! it is only allowed to purchase items below their available quantity in stock.");
    }
}

function editbook($id_book, $qtd) {
    foreach (json_decode($_COOKIE['cart']) as $key => $book) {
        if ($book->id_book == $id_book) {
            $book = listbook($id_book);
            if ($qtd <= $book["number_copies"] && $qtd > 0) {
                $cart = json_decode($_COOKIE['cart']);
                $cart[$key]->qtd_book = $qtd;
                $cart[$key]->vl_book = ($book["vl_book"]);
                setcookie('cart', json_encode($cart), time() + 604800);
            } else {

            }
        }
    }
}

function deletebook($index) {
    $cart = json_decode($_COOKIE['cart']);
    foreach ($cart as $key => $book) {
        if ($key == $index) {
            unset($cart[$key]);
            setcookie('cart', json_encode($cart), time() + 604800);
        }
    }
}

// WISHLIST FUNCTIONS (apparently they are cart-like functions, but it's not working properly).

function adddesire($id_book) {
    $validation = false;
    foreach (json_decode($_COOKIE['desire'], true) as $book) {
        if ($book['id_book'] == $id_book) {
            $validation = true;
            editdesire($id_book);
            return ("successfully updated");
        }
    }

    if ($validation == false) {
        $book = ["id_book" => $id_book];
        $desire = json_decode($_COOKIE['desire'], true);
        array_push($desire, $book);
        setcookie('desire', json_encode($desire), time() + 604800);
        return ("book added to wish list");
    }
}

function editdesire($id_book) {
    foreach (json_decode($_COOKIE['desire'], true) as $book) {
        if ($book['id_book'] == $id_book) {
            $desire = json_decode($_COOKIE['desire']);
            setcookie('desire', json_encode($desire), time() + 604800);
        }
    }
}

function deletedesire($index) {
    $desire = json_decode($_COOKIE['desire']);
    foreach ($desire as $key => $book) {
        if ($key == $index) {
            unset($desire[$key]);
            setcookie('desire', json_encode($desire), time() + 604800);
        }
    }
}
?>

cart.php
<?php include 'conn.php'; ?>

<?php

// CART UPDATE

if (isset($_POST['update'])) {

    // The COUNTER $e within the variables $_POST is constructed by means of a repeat loop (foreach) on the loading of the page

    for ($e = 0; $e < (int) $_POST['qtd_items']; $e++) {
        if (isset($_POST['id_book' . $e]) && $_POST['qtd_book' . $e] > 0) {
            editItem($_POST['id_book' . $e], $_POST['qtd_book' . $e]);
        } else {
            deleteItem($e);
        }
    }

    setcookie('cart', json_encode(array_values(json_decode($_COOKIE['cart']))), time() + 604800);
}

// APPLICATION OF THE COUPON ON PURCHASE

if (isset($_POST['apply_coupon']) || isset($_COOKIE['user_coupon'])) {
    for ($e = 0; $e < (int) isset($_POST['qtd_items']) ? $_POST['qtd_items'] : 0; $e++) {
        if (isset($_POST['id_book' . $e]) && $_POST['qtd_book' . $e] > 0) {
            editItem($_POST['id_book' . $e], $_POST['qtd_book' . $e]);
        } else {
            deleteItem($e);
        }
    }

    if (isset($_POST['apply_coupon'])) {
        $coupon = listcoupon2($_POST['cd_coupon'])->fetch_all(MYSQLI_ASSOC);
        setcookie('user_coupon', $_POST['cd_coupon'], time() + 604800);

    } else if (isset($_COOKIE['user_coupon'])) {
        $coupon = listcoupon2($_COOKIE['user_coupon'])->fetch_all(MYSQLI_ASSOC);
        setcookie('user_coupon', isset($coupon[0]['cd_coupon']) ? $coupon[0]['cd_coupon'] : 0, time() + 604800);
    } else {
        setcookie('user_coupon', (isset($coupon['cd_coupon'])) ? $coupon['cd_coupon'] : $_COOKIE['user_coupon'], time() + 604800);
    }

}

// CART UPDATE AND PURCHASE COMPLETION

if (isset($_POST['buy'])) {
    for ($e = 0; $e < (int) $_POST['qtd_items']; $e++) {
        if (isset($_POST['id_book' . $e]) && $_POST['qtd_book' . $e] > 0) {
            editItem($_POST['id_book' . $e], $_POST['qtd_book' . $e]);
        } else {
            deleteItem($e);
        }
    }

    setcookie('cart', json_encode(array_values(json_decode($_COOKIE['cart']))), time() + 604800);
    setcookie('total_value_buy', $_POST["total_value_buy"], time() + 604800);
}
?>

desire.php
<?php include 'conn.php'; ?>

<?php

// WISH LIST UPDATE

if (isset($_POST['update'])) {

    for ($e = 0; $e <= (int) $_POST['qtd_items']; $e++) {
        if (!isset($_POST['id_book' . $e])) {
            $desires = json_decode($_COOKIE['desire'], true);
            // ERASING ITEMS FROM THE LIST
            foreach ($desires as $key => $item) {
                if ($key == $e) {
                    unset($desires[$key]);
                    setcookie('desire', json_encode($desires), time() + 604800);
                }
            }
            echo "erased<hr>";
        }
    }
}
?>

What would be the best alternative to solve this problem in the PHP language? I have tried to look for other alternatives in
how-to-unset-a-json-object,cannot-use-object-of-type-stdclass-as-array,how-to-convert-an-array-into-an-object-using-stdclass,how-to-use-array-push-for-json-encode,arrays-in-cookies-php
... but the code continues to generate error.


text:
Q: third party cookies and flash action script Let's say I have third party cookies enabled in my browser. I'm on a web site using a flash app that quietly submits network data via action script to another hostname. Can that other host track me using third party cookies? Are there any HTTP headers sent by Flash that can let the server know the difference between a request sent via action script and a regular HTTP browser request?
Pardon me if this is already answered somewhere else but I wasn't able to find an answer. Thank you.

A: I was able to find the answer myself. Unless third party cookies are disabled in the browser, cookies are sent in the HTTP headers to the second host name depending of course on the crossdomain.xml policy.
https://www.adobe.com/devnet/flashplayer/articles/cross_domain_policy.html


text:
Q: how to dynamically add the options(options are in form of"java.sql.ResultSet") to the select tag in jsp I want to add the options to my select tag which I retrieved from the data base.
For example
If the user wants the location of certain store.
First the database will retrieve the "country" and displayed in select tag.
Now on selecting the country the next state's should be displayed in select tag which is retrieved from database depending upon the country that was selected.

A: JSPs are compiled on server side. What you are trying to accomplish is DOM manipulation which happens at client side. You cannot dynamically generate state names based on country selected using JSP tags. You have to do it using javascript and Ajax. Check out jQuery Autocomplete with remote datasource
I would rather post some code.
HTML
    <select id="PIA" name="PIA"  tabindex="2" class='combobox' required='required' placeholder="Select Office">

                    <option value="!valid">Select Office</option>
                    <option value='AHD'>AHEMDABAD</option>
                    <option value='BPL'>BHOPAL</option>
                    <option value='BHU'>BHUBNESWAR</option>
                    <option value='COC'>COCHIN</option>
                    <option value='DLH'>DELHI</option>
                    <option value='GZB'>GHAZIABAD</option>
                    <option value='GUW'>GUWAHATI</option>
                    <option value='HYD'>HYDERABAD</option>
                    <option value='JPR'>JAIPUR</option>
                    <option value='JAL'>JALANDHAR</option>
                    <option value='JMU'>JAMMU</option>
                    <option value='CAL'>KOLKATA</option>
                    <option value='KOZ'>KOZHIKODE</option>
                    <option value='LKO'>LUCKNOW</option>
                    <option value='BOM'>MUMBAI</option>
                    <option value='PAT'>PATNA</option>
                    <option value='SUR'>SURAT</option>
                    <option value='ASR'>AMRITSAR</option>
                    <option value='BLY'>BAREILLY</option>
                    <option value='DDN'>DEHRADUN</option>
                    <option value='MLP'>MALAPPURAM</option>
                    <option value='NGP'>NAGPUR</option>
                    <option value='GOA'>PANAJI</option>
                    <option value='PNE'>PUNE</option>
                    <option value='RPR'>RAIPUR</option>
                    <option value='RCH'>RANCHI</option>
                    <option value='SML'>SHIMLA</option>
                    <option value='SGR'>SRINAGAR</option>
                    <option value='THN'>THANE</option>
                    <option value='TVM'>TRIVANDRUM</option>
                  </select>

    <select id='district' name='district' tabindex="2" class='combobox'>

        <option id="!valid" value='!valid'>Select District</option>

    </select>

Javascript
$('document').ready(function(){
    $('#PIA').combobox({
    maxheight: '100px',
    selected: function(e,u){
            $.getJson({
                "yourURL",
                $(this).val();
                function(districts){
                   $.each(districts[$(this).val()], function(key, value){
               $('#district').append("<option value='"+key+"'>"+value+
                        "</option>");
                });

            });
      });
});

Don't forget to include jquery and jquery UI scripts on top of your page.

A:

<form action="post" name="customerRegForm">

    <select name="state" onchange="changeCities()">

      <option value="1">Gujarat</option>

      <option value="2">Rajasthan</option>

   </select>
  <select name="cities">  </select>

  <input type="text" name="res"></input>

</form>

Write a Servlet which accepts parameter passed from XMLHttpRequest and return the response from servlet.


text:
Q: UserDefaults.standard.stringArray(forKey: "AppleLanguages") contents issue I am using Xcode to develop iOS apps, and I recently found this situation, in the debugging console:
(lldb) p Locale.preferredLanguages[0]
(String) $R6 = "en"
(lldb)

(lldb) p UserDefaults.standard.stringArray(forKey: "AppleLanguages")
([String]?) $R20 = 1 value {
[0] = "en"
}
(lldb)

As one can see above, only "en" (the English language) is present in the list.
There is probably nothing strange about that, but what is weird is that I can see this while my phone is set in a different language (French), I have also tried while the phone is in Japanese with the same situation.
The truth is, I do not understand what is going on and would be glad if someone could make clarify this. I expect to see several items in the list, but more importantly I expect to see the language my device is currently set in. In other words:
"fr", + possibly some other items
(while being in French)

"ja", + possibly some other items
(while being in Japanese)

Running the same debugger command in another app I get:
(lldb) p UserDefaults.standard.stringArray(forKey: "AppleLanguages")
([String]?) $R6 = 14 values {
  [0] = "ja-JP"
  [1] = "fr-JP"
  [2] = "en-JP"
  [3] = "zh-Hant-JP"
  [4] = "zh-Hans-JP"
  [5] = "es-JP"
  [6] = "th-JP"
  [7] = "zh-HK"
  [8] = "ru-RU"
  [9] = "ko-KR"
  [10] = "fi-FI"
  [11] = "de-DE"
  [12] = "bo-JP"
  [13] = "hi-JP"
}
(lldb)

This last result is more what I expect to see (since my phone is currently set in Japanese). But what setting in my first app can lead to the result I get. This is the very problem.
For information, I am using Xcode version 11.2 and iOS version 12.4.2.


text:
Q: Probability With replacement A bag contains blue, red and white discs. In an experiment, 24 students in a class take turns to remove a disc from the bag, record its colour and replace it. This is repeated 10 times. At the end of the experiment the relative frequencies are:
Red: 118/240, blue: 83/240, white: 39/240
Anne suggests that there are 10 discs in the bag. Is this a reasonable suggestion?
Based on the information, how many discs of each colour do you think are in the bag?

A: Firstly I agree with John Chessant in the sense of the ratio of the various coloured discs, i.e. R:B:W = 3:2:1.
As to whether Anne's suggestion is "reasonable" or not, there  is a somewhat subjective element to this question.
I'm inclined to think that Anne must of had some prompting factor to suggest 10, she may have gave such a number because she could clutch all or most of the discs in the one hand thereby giving her a fair guesstament as to the number of discs.
 A statistician would deem it blatantly unreasonable, Anne's mother would deem it highly reasonable. I waver somewhere in between, after all it is not outside the realm of possibilities that the results can occur with the ratios of 5:3:2 however unlikely. But personally believing the ratio is most likely 3:2:1 with the actual numbers being 6,4,2, for Red, Blue and White respectively, then Anne's guesstament is out by only 2, if this is the case I still hold the same view regarding her suggestion i.e. Not unreasonable ( call me a softie).
In light of what I have said in the above I give my answer to the second question as----
Red=6
Blue=4
White=2

A: I think that $10$ discs is not a reasonable suggestion. It is most likely to be a multiple of $6$. In that case, there would be $3n$ red discs, $2n$ blue discs, and $n$ white discs, for a total of $6n$ discs.
To see why, notice that since $240$ discs were recorded, the numerators give the number of times each disc was chosen (i.e., $118$ red, $83$ blue, and $39$ white). Notice that these are about a $3:2:1$ ratio! (One way to see this is to estimate $118\to 120$, $83\to80$, and $39\to40$.)
So the number of red discs is three times the number of white discs, and the number of blue discs is two times the number of white discs.
(Edit: Of course, it is possible that, given $10$ discs, the recorded numbers of discs would still be as above, but it is extremely unlikely.)


text:
Q: Java JFrame key listener stops working randomly I'm trying to create a 2d game in Eclipse using a JFrame and keylistener. My code looks like the following:
Main.java
public static void main(String[] args) {
    DrawerManager game = new DrawerManager();
    JFrame frame = new JFrame("Game");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(game);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.addKeyListener(game);
}

DrawerManager.java
public class DrawerManager extends JPanel implements KeyListener {

    public Scene scene = new GameScene( sceneContext );

    int frame = 0;

    public long last = 0;
    public int ups = 30; //UPDATES PER SECOND

    public DrawerManager() {

    }

    @Override
    public void processKeyEvent(KeyEvent event) {
        super.processKeyEvent(event);
    }

    @Override
    protected void paintComponent(Graphics g) {
        ...
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {
        scene.keyPressed(e);
    }

    @Override
    public void keyReleased(KeyEvent e) {
        scene.keyReleased(e);
    }

 }

GameScene.java
 public class GameScene extends Scene{

    GameContext context;
    Player player;

    public GameScene(SceneContext sceneContext) {
        ...
    }

    public void keyPressed(KeyEvent event) {
        Logic here
    }

    public void keyReleased(KeyEvent event) {
        Logic here
    }

 }

When just launching the game it works fine but after some time it randomly stops receiving any events. My initial thought was that it had something to do with holding down multiple keys, but that doesn't seem to be the case. From my tests I can see that holding down space for a couple of seconds for some reason makes it work again. Keep in mind that the issue is very random, sometimes it happens right away and sometimes it doesn't happen for a very long time.
The issue seems very odd, as the game is extremely simple right now I cannot see anything that would interfere with the event listener. I also tried exporting the code to a jar file with no luck...
I'm running the code in Eclipse Oxygen (4.7.1a) on Mac.
Any help is appreciated!


text:
Q: Apache Camel route with MongoDB gives an error No bean could be found in the registry I am trying into implement a route to insert content into MongoDB. Below is the route I tried and it gives me an error:
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: localhost:27017 of type: com.mongodb.client.MongoClient
from("rabbitmq:localhost:5672/tasks?autoDelete=false&routingKey=camel&queue=task_queue")
        .bean(itemDetails, "consumeItemDetails(${exchange})")
        .to("mongodb://localhost:27017?database=ItemDB&collection=ItemDetails&operation=save");

I was not sure where and how to define a bean of type MongoClient and how I can pass the host and port numbers as parameters. Could anyone please guide me on this?

A: You need to declare a MongoClient bean. If you're running your application through Spring Boot (starter), it will provide your app with a bean named mongo. Otherwise, you need to follow Chanfir's advice.

A: In your route definition , you need to add the beanId as following :
 from("rabbitmq:localhost:5672/tasks?autoDelete=false&routingKey=camel&queue=task_queue")
        .bean(itemDetails, "consumeItemDetails(${exchange})")
        .to("mongodb:mongoBean?database=ItemDB&collection=ItemDetails&operation=save");

And  define a bean of type MongoClient with beanId mentionned in your xml/annotation configuration then define database connection params inside the bean :
Example using Spring xml configuration :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">

  <mongo:mongo-client id="mongoBean" host="${mongo.url}" port="${mongo.port}" credentials="${mongo.user}:${mongo.pass}@${mongo.dbname}">
    <mongo:client-options write-concern="NORMAL" />
  </mongo:mongo-client>
</beans>

Example using Annotations :
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {

    @Override
    protected String getDatabaseName() {
        return "test";
    }

    @Override
    public MongoClient mongoClient() {
        ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
            .applyConnectionString(connectionString)
            .build();

        return MongoClients.create(mongoClientSettings);
    }

    @Override
    public Collection getMappingBasePackages() {
        return Collections.singleton("com.baeldung");
    }
}

A: To be able to execute the code using Spring Boot 2.7.3 and Camel 3.18.2, I have to explicitely register the Mongo client when loading the route:
 @Autowired
    MongoConfig mongoConfig;

then :
context.getRegistry().bind("connectionBean", mongoConfig.mongoClient());

Is there a way to automatically register the Mongo Client?

A: you can easily add a bean inside your Application class if you are developing using Java DSL, like this:
@Bean("myconnection")
public MongoClient mongo() {
    return new MongoClient("localhost", 27107);
}


text:
Q: Pass method as an argument I have two similar methods:
public void methodOne() {
    final List<User> users = userService.getUsers();
    final Integer count = getCount();
    emailService.sendEmailOne(users, count);
}

public void methodTwo() {
    final List<User> users = userService.getUsers();
    final Integer count = getCount();
    emailService.sendEmailTwo(users, count);
}

The difference is - I'm sending different type of email. Can I pass method name as an argument here to get something like:
public void method(sendEmail) {
   final List<User> users = userService.getUsers();
    final Integer count = getCount();
    emailService.sendEmail(users, count);
}

A: The method headers in your first code snippet (e.g. public void methodOne {) are not syntactically correct. There are no parameter list after the method name.
To have the flexibility of choosing a method at runtime, you can create an interface with one abstract method, then implement it into two different classes and override it accordingly. Then you can use an instance of your interface as the parameter of method.
It should be something like this:
public interface Sender {
    abstract public void send();
}

public class SenderOne implements Sender {
    public void send() {
        // your implementation here
    }
}

public class SenderTwo implements Sender {
    public void send() {
        // your implementation here
    }
}

And finally:
public void method (Sender sender) {
    //...
    sender.send();
}

A: There is a much faster and easier way to accomplish it.
This post here also includes some previous answers.
The first class declarations are just to make the example compilable.
The interesting parts start after the method getCount()
package snippet;

import java.io.IOException;
import java.util.List;

public class LamdaExample {
    // dummy declarations
    static class User {}
    static class EmailService {
        public void sendEmailOne(final List<User> pUsers, final Integer pCount) {}
        public void sendEmailTwo(final List<User> pUsers, final Integer pCount) {}
    }
    static class UserService {
        public List<User> getUsers() {
            return null;
        }
    }

    public LamdaExample() {}
    private final UserService   userService     = new UserService();
    private final EmailService  emailService    = new EmailService();
    private Integer getCount() {
        return null;
    }

    // interesting part comes here

    public void methodOne() {
        System.out.println("LamdaExample.methodOne()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailOne(users, count);
    }
    public void methodTwo() {
        System.out.println("LamdaExample.methodTwo()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailTwo(users, count);
    }

    public void method(final Runnable sendEmail) {
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        sendEmail.run();
    }

    public static void main(final String[] args) {
        // simple runnable, see code above
        final LamdaExample t = new LamdaExample();
        t.method(() -> t.methodOne());
        t.method(() -> t.methodTwo());

        // extended special functional interface, see code below
        t.methodSpecial((p, q) -> t.methodX(p, q));
        t.methodSpecial((p, q) -> t.methodY(q, p));

    }

    // extended example starts here

    @FunctionalInterface
    interface MySpecialInterface {
        double specialMethod(String param1, Class<?> param2) throws IOException;
    }

    public void methodSpecial(final MySpecialInterface sendEmail) {
        final List<User> users = userService.getUsers();
        final Integer count = getCount();

        try {
            sendEmail.specialMethod("lol", this.getClass());
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    public double methodX(final String pP, final Class<?> pQ) {
        System.out.println("LamdaExample.methodX()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailOne(users, count);
        return 123.456;
    }
    public double methodY(final Class<?> pQ, final String pP) {
        System.out.println("LamdaExample.methodY()");
        final List<User> users = userService.getUsers();
        final Integer count = getCount();
        emailService.sendEmailTwo(users, count);
        return 98.765;
    }

}


text:
Q: Add button to grid in ExtJs I'm very new with ExtJS.
Does any one know how to add button to each row of grid in ExtJS?
Please give me some example.
Thanks

A: You can check it out here, hope it helps!
http://techmix.net/blog/2010/11/25/add-button-to-extjs-gridpanel-cell-using-renderer/

A: Actualy Ext.Buttons in a row cell is as far as i can tell impossible with the current setup of Ext. Ofcourse it is actually possible to render the HTML of a button in the div of the cell but i actually think that would be a bad idea.
A better way is to implement Saki's rowactions plugin which makes it really easy to add buttons/actions to each row.
http://rowactions.extjs.eu/

A: you should use a custom renderer but I advice you to use a toolbar button instead more clean.
If you wanna have more reference here come the documentation of the ColumnModel class.
anyway it would give something like that
 var grid = new Ext.grid.GridPanel({
     store: store,
     columns: [{
         id: 'company',
         header: 'Company',
         width: 160,
         sortable: true,
         dataIndex: 'company'
     }, {
         header: 'Price',
         width: 75,
         sortable: true,
         renderer: 'usMoney',
         dataIndex: 'price'
     }, {
         header: 'Change',
         width: 75,
         sortable: true,
         renderer: change,
         dataIndex: 'change'
     }, {
         header: '% Change',
         width: 75,
         sortable: true,
         renderer: pctChange,
         dataIndex: 'pctChange'
     }, {
         header: 'Last Updated',
         width: 85,
         sortable: true,
         renderer: Ext.util.Format.dateRenderer('m/d/Y'),
         dataIndex: 'lastChange'
     }, {
         header: 'action',
         width: 85,
         sortable: false,
         renderer: function(val) {
             return '<input type="button" value="toto" id="' + val + '"/>';
         },
         dataIndex: 'somefieldofyourstore'
     }],
     stripeRows: true,
     autoExpandColumn: 'company',
     height: 350,
     width: 600,
     title: 'Array Grid',
     // config options for stateful behavior
     stateful: true,
     stateId: 'grid'
 });

This snippet is an extract of this sample.
For the toolbar way I advice you, just add a button to the toolbar of the GridPanel and hook the SelectionModel so you can disable the buttons when the user doesn't select any row.

A: You can also try this code for adding button as image in your grid here is code :
new Ext.grid.ColumnModel([{
    xtype: 'actioncolumn',
    header: "Action",
    items: [{
        icon: '../images/enable.png',
        tooltip: 'Enable App',
        width: 50,
        id: 'enableAppId',
        handler: function(grid, rowIndex) {
            //add code for button click
        }
    }]
}]);

I have also use this for enable the row data.

A: I'm gonna add an extra answer to this question because since this question has been posted i've created an extension for the ExtJS grid component that allows buttons to be added to grid columns.
https://github.com/Inventis/Ext.ux.grid.ButtonColumn
Just be aware that it might affect performance on older/slower systems when rendering a large amount of rows.


text:
Q: NGRX filter causing ExpressionChangedAfterItHasBeenCheckedError I'm using an NGRX filter on a selector to filter the items in a list based on the state value for the filter.. When the page first loads, no problems. If I refresh the page I get an ExpressionChangedAfterItHasBeenCheckedError error. If I remove/comment the filter portion, the error goes away. Is there any way to do selector filtering without causing this error?
export const getRatings = (state: MyState) => state.ratings
    .filter(rating =>
        state.filterByText === '' ||
        rating.name.toLowerCase().includes(state.filterByText.toLowerCase())
    );

Use in the component
ngOnInit() {
  this.ratings$ = this.store.select(myState.getRatings);
}

Use in html
<sb-rating-cards [ratings]="ratings$ | async"></sb-rating-cards>

A: With help of RxJs you can transform Observable how ever you want (make it cold, hot, replay etc.). Change Detection is triggered if Input Observable emits, so it makes me think that Angular component is designed to take Observable as an input, but not a live stream.
And this is a known issue (if you can call it so).
One suggests to add a pipe(delay(0)), what might be a fast way to solve it (but in real life it might bring you problems, if it takes some time to build, because delay(0) is similar to setTimeout - it runs on async scheduler, which runs in macro task queue (just like setTimeout)).
Otherwise, pass Observable as it is and subscribe in child component, where you also manage unsubscribing when destroyed.


text:
Q: xmlstarlet - order alternate pairs of tag values With the this XML

1
<c>2</c>
3
<c>4</c>

I would like this output from xmlstarlet:
1 2
3 4

But with this command:
xml sel -T -t -m /a -v b -v c -n

I get:
1
32
4

A: Ok, I was making it too complicated:
xml sel -T -t -m /a/* -v . -o " " -i "name()=\"c\"" -n -b test.xml

So that's: always print out the value of the child of a, print a space, and if this tag is c then print a new line.


text:
Q: PHP mail sending problems i was created Normal php script with headers for send the mail to my clients, my clients are have business mail account on their own domain mail account. The mail function working fine for any personal account like gmail,yahoo. But if i send the mail to any business mail account it's not going to in-box , but the mail status say successfully send. i had checked my mail function headers  it's also looking fine. and also i had tried another php mail function like PHP-Mailer, RMail , These third-party function also return value true, but mail was not in inbox. my server os in Linux, please clear this any one, thanks advance

A: Your mailfunction will return successfully sent whenever the mail has successfully left the server. whether the server of the recipient picks up the email, and accepts it, is unknown to your mailfunction, and totally out of your hands.
Since you mention that your testmails being sent to your personal emailaddresses all arrive, I assume that the problem is not in your PHP program, but in the recipients mailserver not accepting the email. Most probably they are being filtered as spam. A good way to prevent this is by using a real emailaddress on a valid domain and an SMTP server on that domain (same IP-Address) to send the mail from. Otherwise, many mailservers will see that the IP-address from the program sending the mail, and the IP-address of the mailserver in the "FROM" field are not the same, and label it as spam.


text:
Q: How to stop event propagation in jQuery click function inside click function? I'm having troubles stopping click event propagation. I have a click function inside another click function.
Here's what I'm trying to achieve:

*

*Select a label by clicking it

*Then click inside the box to determine which label was clicked

This works fine if you select labels one by one. But if you click on Label 1 and then Label 2, both events are recorded (see console log). Or if you click on Label 1 five times and then click inside the box, all five events are captured.
How can I stop this event propagation?
JSFiddle: https://jsfiddle.net/q930bvff

var objectName, currentObject;
$('.label').click(function(event) {

  $('.label').removeClass('selected');
  $(this).addClass('selected');
  objectName = $(this).attr('id');
  currentObject = $(this).hasClass('selected');

  if (currentObject) {
    $('#box').one('click', function(e) {
      console.log(objectName);
    });
  }

 event.stopPropagation();

});
html,
body {
  font-family: 'Helvetica', Arial, sans-serif;
  font-size: 1em;
}

.label {
  padding: 12px;
  border-radius: 4px;
  background: #000;
  color: #fff;
  display: inline-block;
  cursor: pointer;
}

.label.selected {
  background: green;
}

#box {
  height: 300px;
  width: 300px;
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  margin-top: 5px;
}

Label 1

Label 2

A: Use $('#box').off("click") before every new .one("click" to kill all the previously created click handlers on #box.
See working snippet below:

var objectName, currentObject;
$('.label').click(function(event) {

  $('.label').removeClass('selected');
  $(this).addClass('selected');
  objectName = $(this).attr('id');
  currentObject = $(this).hasClass('selected');

  if (currentObject) {
    $('#box').off("click").one('click', function(e) {
      console.log(objectName);
    });
  }

 event.stopPropagation();

});
html,
body {
  font-family: 'Helvetica', Arial, sans-serif;
  font-size: 1em;
}

.label {
  padding: 12px;
  border-radius: 4px;
  background: #000;
  color: #fff;
  display: inline-block;
  cursor: pointer;
}

.label.selected {
  background: green;
}

#box {
  height: 300px;
  width: 300px;
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  margin-top: 5px;
}

Label 1

Label 2


text:
Q: Easier solution for urn-problem Assume we have an urn with $n$ different balls and we draw three times with replacement. What is the probability to draw the same ball at least twice?
My thoughts to this are:
There are $n^3$ possibilities to draw $3$ balls independently from an urn.
There are $n$ possibilities to draw the same ball exactly $3$ times.
There are $n\cdot(n-1)\cdot2+n\cdot1\cdot(n-1)=3\cdot n\cdot (n-1)$ possibilities to draw the same ball exactly two times, because:
(First case: Draw a random ball, then a different one, then the first one or the second one again.
Second case: Draw a random ball, then the same again, then a different one)
So we get $$\frac{3\cdot n\cdot (n-1)+n}{n^3}=\frac{3}{n}-\frac{2}{n^2}$$ for the sought probability.
Now I feel like this is too complicated and one can probably find the solution pretty easily with a much better abstraction. Thank you!

A: The probability that the three balls are distinct is $$1\times \frac {n-1}n\times \frac {n-2}n=\frac {n^2-3n+2}{n^2}=1-\frac 3n+\frac 2{n^2}$$
Your desired result follows immediately.


text:
Q: What is the Extinction of the Shape-shifters (like Beorn) in Middle-Earth Lore? In the movie The Hobbit, The Desolation of Smaug - the party wind up at Beorn's Hall. When Beorn is asked about other Shape-Shifters he makes reference to a past event where Azog captured the shape-shifters and tortured them for his own entertainment.
My question is - is there any mention in the Hobbit, LoTR, Silmarillion or other letters for the extinction of the Shapeshifters?

A: No, because Beorn wasn't the last of the skin-changers.
The eradication of the skin-changers was made up for the film. The "Beornings" were led by a son of Beorn during the War of the Ring, when they helped Aragorn cross the Anduin while tracking Gollum. After the war, the elves gave them part of Mirkwood to live in.