text:
Q: Python Durable Functions struggling get customStatus of Blob URL I have a routine that rates thousands of orders so it takes a bit to run. I am trying to set it up so the front end UI that calls the routine can check the progress of it, so I decided to do it through an Azure Durable Function. I have a lot of experience with other Azure Functions, but the Durable Function is new to me. Initially I created a dictionary that had orders that were done and orders that were not yet done, and then returned it using:
context.set_custom_status(status_update)

This worked for testing small orders, but the problem became that for large samples, it exceeded the 16kb limit that Azure allows for JSON text. So I found a suggestion to write the updates to a Blob and then send the Blob URL to the custom status. This is where I have been banging my head against the wall for.
I have tried different ways of doing this, but the problem I always run into is either 1. The blobs try to save as the same name and crash. 2. The custom status is just Null. I am guessing it has something to do with multiple instances running, but this type of function is new to me so I'm potentially confused by it and not really sure the best way to handle it.
This code is all in my DurableFunctionsOrchestrator function. Here is one way I tried doing it while letting the "Update" function handle dropping the file in the blob.
       for order in orders:
           print(order)
           custom_update = yield context.call_activity('Update', order)
           context.set_custom_status(custom_update)
           # expected this custom_update to return the URL for the blob, but the custom update is Null

I also tried it this way where I let the orchestrator function save the blob:
        for order in orders_list:
            order_status = yield context.call_activity('Update', order)
            print(order_status)
            rated_orders.append(order)
            not_rated_orders = list(filter(lambda order: order not in rated_orders, orders_list))
            status_update.update({'Rated Orders' : rated_orders, 'Orders to process' : not_rated_orders})
            blob_name = f'test_{order}.json'
            blob = BlobClient.from_connection_string(conn_str=connection_string, container_name=container, blob_name=blob_name)
            blob.upload_blob(json.dumps(status_update))
            custom_update = {'Blob Url' : str(blob.url)}
            print(f"{blob_name} : {custom_update}")
            context.set_custom_status(json.dumps(custom_update))

This method will update the custom Status, but will crash shortly after with this error:

System.Private.CoreLib: Exception while executing function:
Functions.DurableFunctionsOrchestrator. Microsoft.Azure.WebJobs.Extensions.DurableTask: Orchestrator > > function 'DurableFunctionsOrchestrator' failed: The specified blob already exists.
RequestId:911649d3-401e-011b-23ef-532bf4000000
Time:2021-05-28T18:29:52.5057612Z
ErrorCode:BlobAlreadyExists
Error:None.

So even though I'm trying to save the order as the Blob name, and the orders are all unique, it is still trying to process that order again, my guess is because it is a different instance running.
How can I get the program to only process an order once, save an updated status of what orders have been processed to a Blob, and return the URL of the blob in the customStatus when I request a GET update on the Durable Function Orchestrator?


text:
Q: Add a color box in select box I have a problem. I have a drop down of colors.
For example
<select>
    <option>Red</option>
    <option>Blue</option>
</select>

I want to add a colored box before the name of the color.
I can't find a solution for this.
Thanks for the help in advance.

A: I haven't found a way to easily add color boxes or images directly to Select boxes, but it's relatively simple to do this by replacing Select elements with Definition List (DL) elements. There's an excellent tutorial showing you how to do this here
I created a jsfiddle with color boxes http://jsfiddle.net/NjaEL/ (just change the path for the arrow icon so that an arrow is displayed in the container).
The basic code is:
HTML

Color

RedRed

     ...

CSS
.dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; } .dropdown dd { position:relative; } .dropdown dt a {background:#ffffff url(images/arrow1.png) no-repeat scroll 97.5% center ; display:block; padding-right:20px;width:70px; border: 1px solid #d3d3d3;} .dropdown dt a:hover { color:#212121; border: 1px solid #999999;} .dropdown a, .dropdown a:visited { color:#555555; text-decoration:none; outline:none;} .dropdown a:hover { color:#212121;} .dropdown dd ul { background:#ffffff none repeat scroll 0 0; border:1px solid #d3d3d3; color:#555555; display:none; left:0px; padding:5px 0px; position:absolute; top:0px; width:90px; list-style:none;} .dropdown dd ul li a { padding:5px; display:block;} .dropdown span.value { display:none;} .dropdown .color { border: 1px solid silver; vertical-align:middle; margin-right:5px; min-width: 10px;}

Javascript
$(document).ready(function() {
$(".dropdown dt a").click(function() {
    $(".dropdown dd ul").toggle();
});
$(".dropdown dd ul li a").click(function() {
    var text = $(this).html();
    $(".dropdown dt a span").html(text);
    $(".dropdown dd ul").hide();
    $("#result").html("Selected value is: " + getSelectedValue("sample"));
});
function getSelectedValue(id) {
    return $("#" + id).find("dt a span.value").html();
}
$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
});
});

A: With CSS only it wouldn't work in all browsers - read here: https://stackoverflow.com/a/2966006/1361042
and your colored box should be an image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jpa date nativequery sql server I'm developing something using jpa and sql server 2008 and I'm getting the following error
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
Error Code: 241

Call: SELECT TOP 100 * FROM [database].[dbo].[registro] WHERE (indate between 'Wed Apr 30 01:01:01 COT 2014' and 'Mon May 12 01:01:01 COT 2014') or name like '%and%'
Query: ReadAllQuery(referenceClass=Register sql="SELECT TOP 100 * FROM [database].[dbo].[register] WHERE (indate between 'Wed Apr 30 01:01:01 COT 2014' and 'Mon May 12 01:01:01 COT 2014') or name like '%and%'")

the jpa query:
Query query = em.createNativeQuery("SELECT TOP 100 * FROM [database].[dbo].[register] WHERE (indate between '"+idate+"' and '"+fdate+"') or name like '%"+name+"%'",Register.class);

Can somebody please tell me what to change or a better way to do the query.

A: You should't use date string in native query.
Also you must avoid sql injection by using setParemeter.
The following query should work :
String query = "SELECT TOP 100 * FROM [database].[dbo].[register] WHERE (indate between ? and  ?);"

Query query = em.createNativeQuery(query).setParameter(1,[your-date- value],TemporalType.DATE).setParameter(2,[your second-date-value],TemporalType.DATE);

List<Register> registerList = query.getResultList();

I hope this help you.


text:
Q: Problemas al cerrar mi formulario en C# (se repite el mensaje de confirmacion) Mi problema radica en que mi formulario tiene un evento de cerrar y de echo lo hace correctamente siempre y cuando no me regrese a donde se delcaro dicho evento, esto quiere decir que mientras navegue por otras ventanas excepto en la inicial, me aparece el mensaje una sola vez y si regreso 2 o 3 veces al formulario inicial, la ventana de cierre al darle clic en la "x" me aparece 2 o 3 veces.
Codigo del evento:
//Metodo para cerrar la aplicacion cuando el usuario guste.
private void cierre(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        DialogResult dialogResult = MessageBox.Show("¿Esta seguro de Que quiere cerrar la aplicacion?", "Cerrar la Aplicacion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
        if (dialogResult != DialogResult.Yes)
        {
            e.Cancel = true;
            return;
        }
    }
}

Codigo con el que avanzo a la siguiente ventana:
//Metodo para llevarme a la ventana de Modal_General
private void btnCompras_Click(object sender, EventArgs e)
{
    this.Close();
    Modal_General general = new Modal_General();
    general.Show();
}

Codigo con el que regreso a mi formulario inicial.
 private void btnRegresar_Click(object sender, EventArgs e)
    {
        this.Close();
        Inicio inicio = new Inicio();
        inicio.Show();
    }

el codigo del evento Cierre se encuentra en mi formulario princiapl, y cuando me regreso a mi formulario inicial y doy clic en x, la ventana emergente de confirmacion se abre dos veces, no se si es porque tal vez aplico  inicio.Closed += (s, args) => this.Close();, para ir a la siguiente ventana y luego para regresar a la ventana inicial.
Ventana que aparece dos veces:

Codigo Completo del formulario al que avanza:
namespace Presupuesto_DaeboSoft
{
    public partial class Modal_General : Form
    {

        private MySqlConnection connection;
        string imgPath;
        string imagen;
        int conteo=0;
        string fecha="";

        //Metodo para obtener las imagenes actuales de tu sistema
        public void obtenerImagenes()
        {
            String Mes = DateTime.Now.Month.ToString();
            PictureBox[] pics = { Enero, Febrero, Marzo, Abril, Mayo, Junio, Julio, Agosto, Septiembre, Octubre, Noviembre, Diciembre };
            for (int i =0; i < Convert.ToInt32(Mes); i++)
            {
                imagen = pics[i].Name;
                var directorio = new System.IO.DirectoryInfo(@"..\..\Imagenes\Imagenes_Modal\Usuario\" + imagen);
                if (directorio.Exists==true) {
                    conteo = directorio.GetFiles().Length-1;
                }

                    imgPath = @"..\..\Imagenes\Imagenes_Modal\Usuario\"+imagen+@"\"+imagen+conteo + ".jpeg";
                if (imgPath != null && Directory.Exists(@"..\..\Imagenes\Imagenes_Modal\Usuario\"+imagen) == true)
                {
                    pics[i].Image = Image.FromFile(imgPath);
                }
            }
        }

        //Metodo para no cambiar de tamaño el formulario y que se ejecute de forma central
        public void notSize()
        {
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.CenterToScreen();
        }

        //Constructor del Formulario
        public Modal_General()
        {
            Base_de_Datos.Conexion conn = new Base_de_Datos.Conexion();
            connection = conn.iniciarBD();

            InitializeComponent();

            obtenerImagenes();
            notSize();

            //Me genera un ciclo que rellena de imagenes los meses despues del actual.
            //Tambien me desabilita los botones de cambio inecesario.
            String Dia = DateTime.Now.Day.ToString();
            String Mes = DateTime.Now.Month.ToString();
            String Año = DateTime.Now.Year.ToString();

            fecha = Año + "-" + Mes + "-" + Dia;

            lblDia.Text = Dia;
            lblMes.Text = Mes;
            lblAño.Text = Año;
            PictureBox[] pics = { Enero, Febrero, Marzo, Abril, Mayo, Junio, Julio, Agosto, Septiembre, Octubre, Noviembre, Diciembre };
            Button[] botones = { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12 };

            for (int MesE = Convert.ToInt16(Mes); MesE < pics.Length; MesE++)
            {
                pics[MesE].Image = Image.FromFile(@"..\..\Imagenes\Imagenes_Modal\Default\NoAplica.png");
                pics[MesE].Enabled = false;
                botones[MesE].Visible = false;

            }

        }

        private void Modal_General_Load(object sender, EventArgs e)
        {

        }

        //Eventos clic que llaman el metodo de cambiar imagen
        //*************************************************************************************\\
        private void btn1_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Enero",Enero);
        }

        private void btn2_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Febrero",Febrero);
        }

        private void btn3_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Marzo",Marzo);
        }

        private void btn4_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Abril", Abril);
        }

        private void pic12_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Diciembre", Diciembre);
        }

        private void pic6_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Junio", Junio);
        }

        private void pic7_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Julio", Julio);
        }

        private void pic8_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Agosto", Agosto);
        }

        private void pic9_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Septiembnre", Septiembre);
        }

        private void pic10_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Octubre", Octubre);
        }

        private void pic11_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Noviembre", Noviembre);
        }

        private void pic5_Click(object sender, EventArgs e)
        {
            Cambiar_Imagen("Mayo", Mayo);
        }
        //*************************************************************************************\\

        //Metodo para cambiar la imagen del picturebox
        public void Cambiar_Imagen(string valor, PictureBox picture)
        {
            OpenFileDialog open = new OpenFileDialog();

            open.Filter = "Image Files(*.jpg; *.jpeg; *.gif;*.png)|*.jpg; *.jpeg; *.gif;*.png";
            if (open.ShowDialog() == DialogResult.OK)
            {
                string ext = Path.GetExtension(open.FileName);
                var fileInfo = new FileInfo(open.FileName);
                picture.Image = new Bitmap(open.FileName);
                Image img = System.Drawing.Image.FromFile(open.FileName);

                string archivoOrigen = open.FileName;
                string rutaDestino = @"..\..\Imagenes\Imagenes_Modal\Usuario";
                string archivoDestino = System.IO.Path.Combine(rutaDestino, open.SafeFileName);

                DirectorySecurity securityRules = new DirectorySecurity();
                securityRules.AddAccessRule(new FileSystemAccessRule("NQ054", FileSystemRights.FullControl, AccessControlType.Allow));
                DirectoryInfo di = Directory.CreateDirectory(@"..\..\Imagenes\Imagenes_Modal\Usuario", securityRules);

                if (Directory.Exists(@"..\..\Imagenes\Imagenes_Modal\Usuario") == true)
                {

                    if (!di.CreateSubdirectory(@"" + valor).Exists)
                    {
                        DirectoryInfo subcarpeta = di.CreateSubdirectory(@"" + valor);
                    }
                    int fCount = Directory.GetFiles(@"..\..\Imagenes\Imagenes_Modal\Usuario\" + valor, "*", SearchOption.TopDirectoryOnly).Length;
                    string ruta = @"..\\..\\Imagenes\\Imagenes_Modal\\Usuario\\" + valor + "\\\\" + valor + fCount + ".jpeg";
                    string archivo = valor + fCount + ".jpeg";
                    File.Copy(archivoOrigen, ruta, true);
                    connection.Open(); //se abre conexion
                    string Query = "Insert Into Imagenes (Ruta, Tipo, NumeroI,Archivo,FechaCambio) values('" + ruta + "','" + valor + "',2,'" + archivo + "','"+fecha+"')";
                    MySqlCommand Conn = new MySqlCommand(Query, connection);
                    MySqlDataReader reader = Conn.ExecuteReader();
                    connection.Close(); //se cierra conexion

                }
                else
                {

                    DirectoryInfo subcarpeta = di.CreateSubdirectory(@"" + valor);
                    int fCount = Directory.GetFiles(@"..\..\Imagenes\Imagenes_Modal\Usuario\" + valor, "*", SearchOption.TopDirectoryOnly).Length;
                    string ruta = @"..\\..\\Imagenes\\Imagenes_Modal\\Usuario\\" + valor + "\\" + valor + fCount + ".jpeg";
                    string archivo = valor + fCount + ".jpeg";
                    File.Copy(archivoOrigen, archivo, true);
                    connection.Open(); // se abre conexion
                    string Query = "Insert Into Imagenes (Ruta, Tipo, NumeroI,ArchivoFechaCambio) values('" + ruta + "','" + valor + "',2,'" + archivo + "',1,'"+fecha+"')";
                    MySqlCommand Conn = new MySqlCommand(Query, connection);
                    MySqlDataReader reader = Conn.ExecuteReader();
                    connection.Close(); //se cierra conexion

                }

            }
        }

        private void btnRegresar_Click(object sender, EventArgs e)
        {
            this.Close();
            Inicio inicio = new Inicio();
            inicio.Show();
        }

    }
}

Codigo Completo del Formulario de Inicio:
namespace Presupuesto_DaeboSoft
{
    public partial class Inicio : Form
    {

        int contador = 0;

        //constructor de la clase, inicia todos los componentes
        public Inicio()
        {
            InitializeComponent();
        }

        //Metodo para no cambiar de tamaño el formulario y que se ejecute de forma central
        public void notSize()
        {
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.CenterToScreen();
        }

        //Metodo que carga los elementos iniciales del formulario
        private void Inicio_Load(object sender, EventArgs e)
        {

            notSize();
            String quincena = calendario.TodayDate.Day.ToString();
            int dia = int.Parse(quincena);

            if (dia > 15)
            {
                lblQuincena.Text = "2";
            }
            else
            {
                lblQuincena.Text = "1";
            }

        }

        //Metodo para cerrar la aplicacion cuando el usuario guste.
        private void cierre(object sender, FormClosingEventArgs e)
        {
                if (e.CloseReason == CloseReason.UserClosing)
                {
                    DialogResult dialogResult = MessageBox.Show("¿Esta seguro de Que quiere cerrar la aplicacion?", "Cerrar la Aplicacion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (dialogResult != DialogResult.Yes)
                    {
                        e.Cancel = true;
                        return;
                    }

            }

        }

        //Metodo que me da la hora actual.
        private void horaActual(object sender, EventArgs e)
        {
            String tiempo = DateTime.Now.ToString("HH:mm:ss");
            lblTiempo.Text = "Hora Actual: " + tiempo;
        }

        //Metodo para llevarme a la ventana de Modal_General
        private void btnCompras_Click(object sender, EventArgs e)
        {
            this.Close();
            Modal_General general = new Modal_General();
            general.Show();
        }

    }
}

A: protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);
    if (PreClosingConfirmation() == System.Windows.Forms.DialogResult.Yes)
    {
        Dispose(true);
        Application.Exit();
    }
    else
    {
        e.Cancel = true;
    }
}

private DialogResult PreClosingConfirmation()
{
    DialogResult res = System.Windows.Forms.MessageBox.Show("¿Esta seguro de Que quiere cerrar la aplicacion?", "Cerrar la Aplicacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    return res;
}

Prueba este código usando Application.Exit(); en vez de usar Close();.


text:
Q: INSERT INTO SELECT strange order using UNION I had a typical non-normalized table (tempTable) with multiple numbered columns (rep1,rep2,...).
So i wrote a script to insert the non-normalized data into a normalized table (myTable):
insert into myTable
select idRep,rep FROM
(
    select idRep, ISNULL(rep1,'') as rep FROM tempTable
    union
    select idRep, ISNULL(rep2,'') as rep FROM tempTable
    union
    select idRep, ISNULL(rep3,'') as rep FROM tempTable
    union
    select idRep, ISNULL(rep4,'') as rep FROM tempTable
    union
    select idRep, ISNULL(rep5,'') as rep FROM tempTable
) as t

Note: The table myTable also contains an auto-incremented IDENTITY column as its PRIMARY KEY.
The order rep1, rep2, rep3, rep4, rep5 is important in my scenario. Strangely, when I executed the script, the data wasn't inserted in the correct order such as the auto-generated id '1000' had the value from 'rep3' and the id '1001' had the value from 'rep1'.
Why is that? How was the script executed?

A: The reason it is not going in the order you expect when using UNION is that union attempts to impose uniquness, so it is processing all of those rows together and bringing them out in the order most convenient for the engine.
If you switch to UNION ALL (which does not try to impose uniqueness) as Parado suggested it will not do the processing and they will go into the table in the order you put them in, almost all the time.  This however is not gaurunteed and certain very unusual circumstances going on in other processes (especially ones that somehow touch on your tempTable) can affect it.
If you use an order by as Kash suggests then that will gauruntee the order of the ids (which can matter), but not technically the order that the rows get inserted (which very rarely matters in practice).
There is a good summary of some of this on MSDN.
So, that takes care of the why.  As for the how to get what you actually want, I would use Kash's suggestion of adding a column to use with an order by clause, but I would use UNION ALL instead of UNION.  Using UNION is like adding and implicit "distinct" requirement, which takes up processor cycles and makes the query plan more complicated.

A: Your outer Select has no order, hence the INSERT is not ordered like it seems.
There are a few Ordering Guarantees in SQL Server and an INSERT of SELECT with ORDER BY guarantees computation of identity values as quoted:

INSERT queries that use SELECT with ORDER BY to populate rows
  guarantees how identity values are computed but not the order in which
  the rows are inserted

Change your SQL to make it ordered:
insert into myTable
select idRep,rep FROM
(
    select idRep, ISNULL(rep1,'') as rep, 1 as Grp FROM tempTable
    union
    select idRep, ISNULL(rep2,'') as rep, 2 as Grp FROM tempTable
    union
    select idRep, ISNULL(rep3,'') as rep, 3 as Grp FROM tempTable
    union
    select idRep, ISNULL(rep4,'') as rep, 4 as Grp FROM tempTable
    union
    select idRep, ISNULL(rep5,'') as rep, 5 as Grp FROM tempTable
) as t ORDER BY Grp

A: Try with union all. It does't sort the data:
insert into myTable
select idRep,rep FROM
(
    select idRep, ISNULL(rep1,'') as rep FROM tempTable
    union all
    select idRep, ISNULL(rep2,'') as rep FROM tempTable
    union all
    select idRep, ISNULL(rep3,'') as rep FROM tempTable
    union all
    select idRep, ISNULL(rep4,'') as rep FROM tempTable
    union all
    select idRep, ISNULL(rep5,'') as rep FROM tempTable
) as t

A: Here is another way to do this without unions altogether. It references the source table only once. Sorting is simple.
declare @numbers table (number int)
insert into @numbers (number)
values (1),(2),(3),(4),(5)

insert into mytable
select
case number
    when 1 then rep1
    when 2 then rep2
    when 3 then rep3
    when 4 then rep4
    when 5 then rep5
    end as rep
from temptable cross join @numbers n
order by number asc, id asc


text:
Q: Delphi 7: Actual reason for a data breakpoint warning On Delphi 7, I recived a warning message: "Setting a Data Breakpoint on a stack location may cause your program or system to become unstable. Set breakpoint anyway?". The short description of this message does not explain the reason why the program (or system) may become unstable. It only says that it may happen.
I would like to ask you for a concrete explanation with the reason why/when the program (or system) will be unstable.

A: A Data Breakpoint is triggered by a write operation to memory at a specified location.  Detecting these operations, whether by use of a hardware breakpoint or other techniques, cannot - to my knowledge - cause a program, let alone an entire system, to become unstable.
There are however problems with creating data breakpoints in the stack area.  These problems can lead to debugger behaviours which are almost certainly undesirable and could be considered "instability", due to the volume and frequency of breakpoints rendering the debugger unusable.
But this is the only extent to which the "system" or the "program" can be made unstable.
The error message is most likely using abbreviated language which is arguably misleading in an attempt to convey this in terms which are suitable for a short, terse error message, since the actual, accurate explanation is both harder to explain and perhaps less likely to be understood by many developers.
It is also possible that placing a Data Breakpoint in the stack did have the potential to cause wider system problems pre-Win32 (I don't know for sure, but I can imagine it is possible - it was certainly easier for a program failure to crash an entire system under Win16); i.e. that this message is a hang-over from Delphi 1 and was simply not updated to reflect the greater protection that processes enjoy under Win32.


text:
Q: Is there a proper way to manage temporary files in Spring MVC context? I mean I'm deleting them when I'm done but I want to cover all the possibilities and rule out the chance of leaving garbage behind.
I read about File.createTempFile but it only deletes the temp file after the VM has been stopped...

A: If you can specify the folder where your files are stored you can create a scheduled task that runs each hour and deletes the files older than one hour.
Take a look at the @Scheduled annotation.


text:
Q: Replace text but not if contain specific characters? In JavaScript, I am using the below code to replace text that matches a certain string. The replacement wraps the string like this: "A(hello)". It works great but if there are two strings that are the same, for example: "Hello hi Hello", only the first one will get marked and if I am trying twice, it will get marked double, like this: "A(A(Hello)) Hi Hello".
A solution to this could be to not replace a word if it contains "A(" or is between "A(" and ")"; both would work.
Any idea how it can be achieved?
Note: I cant use replaceAll because if there is already a word that is replaced and a new word is added, then the first one will be overwritten. Therefore I need a solution like above. For example,If I have a string saying "Hello hi", and I mark Hello, it will say "A(Hello) hi", but if I then add Hello again to the text and replace it, it will look like this: A(A(Hello)) hi A(Hello).
Here is what I got so far:
let text = "Hello hi Hello!"
let selection = "Hello"
let A = `A(${selection})`
let addWoman = text.replace(selection, A)

A: You can use a negative lookahead assertion in your pattern that fails the match if we A( before full word Hello:
(?<!A\()\bHello\b

And replace it with A($&)
RegEx Demo
Code:

let text = "Hello hi Hello!";
let selection = "Hello";
let A = `A(${selection})`;
let re = new RegExp(`(?<!A\\()\\b${selection}\\b`, "g");
let addWoman = text.replace(re, A);

console.log(addWoman);

console.log(addWoman.replace(re, A));

A:
A solution to this could be to not replace a word if it contains "A(" or is between "A(" and ")"; both would work.

To avoid re-matching selection inside a A(...) string, you can match A(...) and capture it into a group so as to know if the group matched, it should be kept, else, match the word of your choice:

let text = "Hello hi Hello!"
let selection = "Hello"
let A = `A(${selection})`
const rx = new RegExp(String.raw`(A\([^()]*\))|${selection.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')}`, 'g')
let addWoman = text.replace(rx, (x,y) =>  y || A)
console.log(addWoman);
// Replacing the second time does not modify the string:
console.log(addWoman.replace(rx, (x,y) =>  y || A))

The regex will look like /(A\([^()]*\))|Hello/g, it matches

*

*(A\([^()]*\)) - Group 1: A and then ( followed with zero or more chars other than ( and ) and then a ) char

*| - or

*Hello - a Hello string.


text:
Q: "This page contains both secure and nonsecure items" Themes & SSL So I have this website that will be accessed via an SSL connection ("https://mystupidwebsite/etc...")
I am using themes in conjunction with a single css file. when the page is rendered though, the CSS link tag in the header still has the http://mystupidwebsite/etc... full path.
How do I get it to regester the css file correctly, with the https or use relative paths?
thanks,
Nate
Edit: Oh! I just found my issue. Themes are correctly adding the css with a relative path. There was a link tag in the master page that was using absolute paths to the same css. sorry for wasting your time!

A: use relative pathing

A: Just link to /path/to/style.css instead of with the full http://example.com/path/to/style.css. This assumes you've got the same content being served to HTTPS and HTTP requests. If not, you'll need to make an alias or symbolic link or something.


text:
Q: Simple jacorb program I am following this tutorial to implement a server and client using jacorb. I used the same code and in step 2 when I want to compile the generated server.java class I got this error
javac server.java
server.java:11: cannot find symbol
symbol: class serverOperations
    extends serverOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
            ^
1 error

A: Add the directory containing the generated stub and skeleton code to your classpath. The JacORB jar is also required
javac -cp /path/to/stubcode:jacorb.jar:. Server.java

A: I would recommend asking questions about JacORB on the jacorb-developer list (http://www.jacorb.org/contact.html)


text:
Q: Where do you find higher rated weapons? All the outfitted parts in Elite: Dangerous have a level and a class, broadly describing their performance.
So you have size 1 (small), 2 (medium) and so on for size ratings and A, B, C etc for class ratings (A being best but super expensive). Size counts more than class, so a 2-anything will be better than a 1 anything, and an A2 will be better than a B2.
Where can I find high class weapons?
I'm currently in an Eagle with 3 small mounts - shouldn't I be able to mount 3 A1 guns eventually (when I can afford them)? The problem is that (even in high tech systems) I haven't seen any size 1 guns better rated than F.
In particular is like to find gimballed size one guns better than a G rating.

A: You can't. Currently, the class ranking of weapons doesn't seem to mean anything at all. Your choices of weapons are strictly limited by type, size, and targeting method. There aren't higher class small fixed pulse lasers, for example, there is only one variety of small fixed pulse laser.
What I think is going on here, is the game is ranking weapons based on their overall stats, regardless of power cost, size, or targeting method. For example, a huge plasma accelerator is class A, a medium railgun is class B, and a small fixed pulse laser is class F. There's not a class D small fixed pulse laser, because that's not how that class stat works. You can check out all possible weapons that you can find in the Elite Shipyard.


text:
Q: Inheritance, deriving from a derived class I am trying to create a class from a class that is already derived from another class. (bit confusing) It adds one extra attribute in the newest "PricedApt" class that is "price". The desired constructor call is as follows
   PricedApt p = new PricedApt("jill", 900, true, "jack", 1050.00);

The class is missing its constructor and im trying to create it but not sure whats wrong.
This is the (already derived (2nd) class)
public class RentalApt extends Apartment{

      private String tenant;
      private boolean rented;

      public RentalApt(String owner, int size, boolean rented, String who){
        super(owner,size);
        tenant = who;
        this.rented = rented;
      }

My code for the (3rd) class that I have attempted is
public class PricedApt extends RentalApt {

private double price;

public PricedApt(String owner, int size, boolean rented, String who, double priceTag) {
  super(owner,size,who);
  price = priceTag;
}

}

Can anyone point me in the right direction as to what I am doing incorrectly? The compilation error I'm receiving is cannot find symbol (line 2 column 3).

A: For one, RentalApt has a four-argument constructor, but its subclass PricedApt is calling super() with only three arguments.
Try changing
super(owner,size,who);

to:
super(owner,size,rented,who);


text:
Q: Get % of how much of a javascript file is commented out I'm wanting to check if files are more than 50% commented out with javascript style commenting of //. My idea is to count the number of lines in the file and then count the number of // and do some simple math.
It get's tricky if someone uses multiline comments though /* ... */
What's a better way to go about this?

A: See if this shell script works for you:
#!/bin/bash

if [ $# -eq 0 ]; then
    echo "You have to specify a file. Exiting..."
    exit 1
fi

if [ ! -r $1 ]; then
    echo "File '$1' doesn't exist or is not readable. Exiting..."
    exit
fi

# count every line
lines=$(wc -l $1 | awk '{print $1}')
echo "$lines total lines."

# count '//' comments
commentType1=$(sed -ne '/^[[:space:]]*\/\//p' $1 | wc -l | awk '{print $1}')
echo "$commentType1 lines contain '//' comments."

# count single line block comments
commentType2=$(sed -ne '/^[[:space:]]*\/\*.*\*\/[[:space:]]*/p' $1 | wc -l)
echo "$commentType2 single line block comments"

# write code into temporary file because we need to tamper with the code
tmpFile=/tmp/$(date +%s%N)
cp $1 $tmpFile

# remove single line block comments
sed -ie '/^[[:space:]]*\/\*.*\*\/[[:space:]]*/d' $tmpFile

# count multiline block comments
commentType3=$(sed -ne ':start /^[[:space:]]*\/\*/!{n;bstart};p; :a n;/\*\//!{p;ba}; p' $tmpFile | wc -l | awk '{print $1}')
echo "$commentType3 of lines belong to block comments."

percent=$(echo "scale=2;($commentType1 + $commentType2 + $commentType3) / $lines * 100" | bc -l)
echo "$percent% of lines are comments"


text:
Q: Preprocessor Macro for target not working I added a "Preprocessor Macro" TEST=1 to my Xcode target for all build configurations.
Was expecting I could now use it like this:
#if TEST
print("testing")
#else
print("not testing")
#endif

When running the target the compiler always uses print("not testing") though.
I also tried adding a "User-Defined Setting" OTHER_SWIFT_FLAG -DTEST as well as adding -DTEST to "Other Linker Flags". With the same result.
What am I doing wrong?

A: Found it:
Had to use "Active Compilation Conditions".


text:
Q: Function integrate() in R provides abnormal output I am generating two distributions (say, mean1, sd1 and mean2, sd2), using convolution on them and then calculating the integral for the newly generated distribution from a given threshold (a given maximum value) to Inf. Here, I am using functions from library distr.
Interestingly, when integrating, if my original distributions present values fairly larger than the threshold the output of the integral = 0 (should be = 100, indicating that the whole distribution falls after the threshold)
MWE
library(distr)

# Two distributions
mean1 <- 560
sd1   <- 4.1

mean2 <- 1570  # values to be tested: # 1570 # 1571 # 1970
sd2   <- 3.219

# Getting Normal Distribution for both groups
Np1  <- Norm(mean = mean1, sd = sd1)
Np2  <- Norm(mean = mean2, sd = sd2)

# Convolution of distributions
conv <- convpow(Np1 + Np2, 1)

# Sanity check
plot(conv)

# Distribution function
f.Z  <- d(conv)

# This works well with any values.
min_threshold <- 1925.3
integrate(f.Z, 0, min_threshold, abs.tol = 0L)$value * 100

# The statement below provides abnormal output depending on the tested value presented above for mean2:
max_threshold <- 1968.9
integrate(f.Z, max_threshold, Inf, abs.tol = 0L)$value * 100

Here, I would expect that any value for mean2 > 1570 would have 100 as output, indicating a 100% chance of the distribution being after the max_threshold. Instead, output sharply decreases after 1570 until it reaches 0. Would anyone understand this behavior? Am I missing something here?
My machine has Windows 10, 64, R version 4.0.3, and library distr 2.8.0.
This code is based on the code provided here:
integrate() in R gives terribly wrong answer
Many thanks!


text:
Q: How to count distinct records Could anybody please help me on SQL command?
I have a table (tbl_sActivity) that have below data:

user_id | client_id | act_status |
  1           |     7        |
       cold     |
  1           |     7        |
     dealed   |
  22         |     5        |
       cold     |
  1           |     6        |
       cold     |
  1           |     6        |
      warm    |
  1           |     6        |
       hot       |
  1           |     6        |
     dealed   |
  1           |     8        |
      warm    |
  1           |     8        |
     dealed   |
  21         |     4        |
      warm    |
  21         |     4        |
     dealed   |

The out put should be

user_id | Count_C_id |
   1          |
      3             |
   21        |
      1             |
   22        |
      1             |

I've searched from net and learnt that MS ACCESS cannot use COUNT(DISTINCT) function. So I'm stuck at this stage for days.

A: Try this one. The "trick" is to have a subquery first to get all the distinct combinations of user and client IDs and then do the grouping per user:
SELECT
    user_id
  , COUNT(*) AS count_distinct_clients
FROM
    ( SELECT DISTINCT
          user_id,
          client_id
      FROM tbl_sActivity
    ) AS tmp
GROUP BY
    user_id ;

A: Recommendation is to make query without using sub-query.
Please find the below code which will be faster and accurate then subquery.
// Temp Table
CREATE TABLE #TempStudent(userId  int, c_id int , Name  varchar(MAX) )

SELECT max(userid) as UserId, count(c_id) as C_ID from #TempStudent
GROUP BY userId


text:
Q: Prevent Mail.app from sending read receipts? I just recently realised that Mail.app sends out "read receipts" without my knowledge if someone sends an email with a "Disposition-Notification-To" header to my work (MS Exchange) email account. This definitely seems to happen on Mail's side and not on the Exchange server's side where I made sure to turn that functionality off (also in the 'Mobile Devices' settings).
There doesn't seem to be any GUI to turn this behaviour off in Mail.app, but maybe someone out there knows of a hidden preference that can be set? Note that if I read my email using the iOS Mail app, then no read receipt is being sent.

A: There are two header tags related to receipts:

*

*Return-Receipt-To This is asking for a verification that the mail got to your inbox.  I was surprised that mail responded by sending the original message back to me. macOS 10.10.5  I see this as a minor privacy issue in most circumstances. Could be used to tell if your work computer was powered on and mail app running.

*Disposition-Notification-To This asks for what you did with the email. Mojave gives you some options. I'd display what you have then delete it.
To control, Disposition-Notification-To,  you may use terminal comments document on this web page
https://miln.eu/mailreceipt/, see below, or install Mail Receipt which is a free macOS application that adds delivery notification and read receipt requests to your e-mails. https://miln.eu/mailreceipt/
As far as I know, you cannot change how mail responds inbound "Return-Receipt-To". Mail will always echo back your message to the sender. You can control how mail responds to "Disposition-Notification-To" via commands or an app
Terminal commands:
I'd display what you have then delete it. To view existing UserHeaders enter the following Terminal.app command:
defaults read ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist UserHeaders

To set a Disposition-Notification-To header via UserHeaders enter the following Terminal.app command:
defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist UserHeaders '{"Disposition-Notification-To" = "email@address"; }'

To remove all UserHeaders enter the following Terminal.app command:
defaults delete ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist UserHeaders

Via the free Mail Receipt macOS app.


text: Q: What's the best non-dp algo for knapsack? I have an equivalent of knapsack problem where multiplication is substituted for addition. Can't find any algo for multiplication-type of problem, so naturally I switched to logarithms, but now I can't use dp-solution to knapsack. What's my best move? Thanks.


text:
Q: How to use the `provider` and retrieve the data in `controller` I am trying to use a provider to set and get a value in the controller. But I am not clear on how to use the provider here.
Can any one help me to use the provider with config option. I would like to know about the relationship between provider and config as well.
Here is my try, which throws error:
var app = angular.module('plunker', []);

app.value("person", {'name':"arif"});

app.constant("env", {url:"production"});

app.provider("book", function(){ //declaring provider
  var version;
  return {
    setVersion : function(value){
      version = value;
    },

    $get : function(school){
      return {
        "newVersion" : "title" + ':' + version
      }
    }
  }
});

app.config(function(newBook){ //setting a new value
    newBook.setVersion = "4.0";
});

app.controller('MainCtrl', function($scope, person, env, book) {
  $scope.name = env.url;
  $scope.value = person.name;
  $scope.version = book; //i am not getting the new value here.
});

Live Demo

A: As mentioned in my comment...
app.config(function(bookProvider){
    bookProvider.setVersion("4.0");
});

I had to remove the missing school injection to get it to work but you should get the picture.
Fixed ~ http://plnkr.co/edit/6Sb6rOSvA7ihvTLPTujY?p=preview
See https://docs.angularjs.org/guide/providers#provider-recipe for more information on the provider recipe.
See https://docs.angularjs.org/api/auto/service/$provide#provider for the .provider() docs, specifically...

NOTE: the provider will be available under name + 'Provider' key.


text:
Q: Pandas copy and pasting I'm new to Panda and have neen trying to do the following, using all sorts of commands and basically getting nowhere fast. I have a csv file that has 10 columns, the first 4 columns are descriptive columns and the other 6 hold numerical values. What I need to do is create a file that has the 4 descriptive columns, a new column with the title of the numerical value in it, plus the numerical values all pasted to a single column. I don't know if I've explained that well enough, but here's a visual explanation:
Existing file:
Year Type  Account Group  gross  nett discount
1999 A     ABC      1      100    80     2%
2000 B     XYZ      2      1000   800    5%

New file:
Year  Type  Account  Group Value_Type Amount
1999   A    ABC      1      gross     100
1999   A    ABC      1      nett       80
1999   A    ABC      1      discount   2%
2000   B    XYZ      2      gross     1000
2000   B    XYZ      2      nett       800
2000   B    XYZ      2      discount    5%

What would be the best way to achieve this?

A: You want to pandas.melt your dataframe:
>> df = pd.melt(df, id_vars=["Year", "Type", "Account", "Group"], value_vars=["gross", "nett", "discount"])
>> df
   Year Type Account  Group  variable value
0  1999    A     ABC      1     gross   100
1  2000    B     XYZ      2     gross  1000
2  1999    A     ABC      1      nett    80
3  2000    B     XYZ      2      nett   800
4  1999    A     ABC      1  discount    2%
5  2000    B     XYZ      2  discount    5%

This function takes the identifiers columns as is (id_vars) and creates a row for each value in the value_vars columns.
EDIT: To match your output, just sort the rows:
>> print(df.sort_values(["Year", "Type", "Account", "Group"]))
   Year Type Account  Group  variable value
0  1999    A     ABC      1     gross   100
2  1999    A     ABC      1      nett    80
4  1999    A     ABC      1  discount    2%
1  2000    B     XYZ      2     gross  1000
3  2000    B     XYZ      2      nett   800
5  2000    B     XYZ      2  discount    5%


text:
Q: How to delete all snapshots in lxd cluster? I am trying to find a fast method, how to delete all snapshots in lxd cluster. The only way I see is using lxc delete container/snap for each snap. Am I missing something?
Thanks


text:
Q: Adding a form to TabPage inside a TabControl I've create a form in VB.NET that can be initialised multiple times and in order to keep all the open forms organised, I need to use TabControl.
How can I add this form dynamically to a TabPage in the TabControl (similar to a browser)?
Thanks.


text:
Q: group by clause in LINQ I have been through the below code but dont understand how group clause makes the grouping
Please help in this . I am new to c# .
public static List<Student> GetStudents()
        {
            // Use a collection initializer to create the data source. Note that each element
            //  in the list contains an inner sequence of scores.
            List<Student> students = new List<Student>
        {
           new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 72, 81, 60}},
           new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
           new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {99, 89, 91, 95}},
           new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {72, 81, 65, 84}},
           new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {97, 89, 85, 82}}
        };

            return students;

        }
List<Student> students = GetStudents();

            // Write the query.
            var studentQuery =
                from student in students
                let avg = (int)student.Scores.Average()
                group student by (avg == 0 ? 0 : avg / 10);

I dont understand how StudentQuery has been generated .
Thanks in advance .

A: Grouping refers to the operation of putting data into groups so that the elements in each group share a common attribute.The GroupBy divides students into groups - those with average 0-9, 10-19, 20-29, 30-39, etc. You should look at
http://msdn.microsoft.com/en-us//library/bb546139.aspx
p.s. the
 group student by (avg == 0 ? 0 : avg / 10);

seems to be excessive to me. You can change it to simplier
 group student by (avg / 10);

pps: I prefer the other style of LINQ, but it's totally a personal choice. The other style would be
var studentQuery = students.GroupBy(x => x.Scores.Average() / 10);


text:
Q: Assembly: Compute Execution Time of Instructions How do you compute the execution time of instructions? Is it just done by checking what the chip manufacturers say in terms of how many clock cycles an action may take to complete? Is there anything else i should know about this? Feels like i'm missing something....

A: The RDTSC instruction is extremely accurate as far as I know.
I think if you are seeking the exact cycle counts, then in the case of short boostable sections you may run into the issues of simultaneity that Mysticial mentioned...
But if ultra-ultra-ultra-ultra-precision is not an obstacle... that is to say, if you can survive knowing that for certain scenarios your result is off by... I dunno... say 9 to 80 cycles... then I'm pretty sure you can still get very accurate results with RDTSC... especially when one considers that 9 to 80 divided by 3.2 billion is a very tiny number :)
The numbers 9 and 80 were chosen a bit arbitrarily (and maybe you aren't on a 3.2ghz cpu speed either) since I dunno exactly what the error amount is... but I'm pretty sure its in that ballpark :)
Here's the RDTSC excerpt of a timer function I use:
//High-Rez Setup
__asm
{
    push        eax
    push        edx
    rdtsc
    mov         [AbsoluteLow],eax
    mov         [AbsoluteHigh],edx
    pop         edx
    pop         eax
}

actually I'll go ahead and post the whole thing... this code assumes that the type "double" is a 64-bit floating point number... which might not be a universal compiler / architecture assumption:
double              AbsoluteTime;
double              AbsoluteResolution;
ulong               AbsoluteLow;
ulong               AbsoluteHigh;

void Get_AbsoluteTime (double *time)
{
    //Variables
    double  current, constant;
    double  lower, upper;
    ulong   timelow, timehigh;

    //Use the Intel RDTSC
    __asm
    {
        push    eax
        push    edx
        rdtsc
        sub     eax, [AbsoluteLow]
        sbb     edx, [AbsoluteHigh]
        mov     [timelow], eax
        mov     [timehigh], edx
        pop     edx
        pop     eax
    }

    //Convert two 32bit registers to a 64-bit floating point
    //Multiplying by 4294967296 is similar to left-shifting by 32 bits
    constant     = 4294967296.0;
    lower        = (double) timelow;
    upper        = (double) timehigh;
    upper       *= constant;
    current      = lower + upper;
    current     /= AbsoluteResolution;
    current     += AbsoluteTime;
    *time        = current;
}

void Set_AbsoluteTime (double time, double scale)
{
    //Variables
    double  invScale;

    //Setup
    AbsoluteTime = time;

    //High-Rez Setup
    __asm
    {
        push    eax
        push    edx
        rdtsc
        mov     [AbsoluteLow],eax
        mov     [AbsoluteHigh],edx
        pop     edx
        pop     eax
    }

    //Fetch MHZ
    if (1)
    {
        //Local Variables
        int      nv;
        ulong    mhz;
        char     keyname[2048];

        //Default assumption of 3.2ghz if registry functions fail
        mhz = 3200;

        //Registry Key
        sprintf (keyname, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
        nv = Reg_Get_ValueDW (keyname, "~MHz", (ulong *)&mhz);

        //Transform into cycles per second
        mhz *= 1000000;

        //Calculate Speed Stuff
        AbsoluteResolution = (double) mhz;
        invScale  = 1.0;
        invScale /= scale;
        AbsoluteResolution *= invScale;
    }
}

You wanna call Set_AbsoluteTime somewhere before using the Get functions... without the first initial call to Set, the Gets will return erroneous results... but once that onetime call is made you are good to go...
here's an example:
void Function_to_Profile (void)
{
    //Variables
    double   t1, t2, TimeElapsed;

    //Profile operations
    Get_AbsoluteTime (&t1);
    ...do stuff here...
    Get_AbsoluteTime (&t2);

    //Calculate Elapsed Time
    TimeElapsed = (t2 - t1);

    //Feedback
    printf ("This function took %.11f seconds to run\n", TimeElapsed);
}

void main (void)
{
    Set_AbsoluteTime (0.000, 1.000);
    Function_to_Profile();
}

if for some reason you wanted time measurements to flow backwards at half-speed (maybe handy for game-programming), the initial call would be:
Set_AbsoluteTime (0.000, -0.500);
the first parameter to Set is the base time that gets added to all results
I'm pretty sure these functions are more accurate than the most high-rez Windows API timers that currently publicly exist... I think on fast processors they have an error smaller than 1 nanosecond but I'm not 100% sure on that :)
they are accurate enough for my purposes, but do note that the standard initialization of the 40 pre-amble bytes (composed of 'current', 'constant', 'lower', 'upper', 'timelow', 'timehigh') that most C compilers would set to 0xCC or 0xCD will eat some cycles... as will the math performed at the bottom of every Get_AbsoluteTime call...
so for really pristine accuracy you would be best framing whatever it is you want to profile in RDTSC "inlines"... I would make use of the extended x64 registers to store the answer for later subtraction operations instead of messing around with slower memory access...
like for example something like this... this is mainly the concept by the way, because technically VC2010 doesn't allow you to emit x64-Assembly via the __asm keyword :(
...but I think it will give you the conceptual road to travel:
typedef unsigned long long ulonglong;
ulonglong Cycles;

__asm
{
    push rax
    push rdx
    rdtsc
    mov r9, edx
    shl r9, 32
    and rax, 0xFFFFFFFF
    or  r9, rax
    pop rdx
    pop rax
}

...Perform stuff to profile here

__asm
{
    push rax
    push rdx
    rdtsc
    mov r10, edx
    shl r10, 32
    and rax, 0xFFFFFFFF
    or  r10, rax
    sub r10, r9
    mov qword ptr [Cycles], r10
    pop rdx
    pop rax
}

printf ("The code took %s cycles to execute\n", ULONGLONG_TO_STRING (Cycles));

with that code I think the final answer of the number of cycles that elapsed will be in r10, a 64bit register... or in Cycles, a 64bit unsigned integer... with just a handful of cycles of error caused by the bit shifting and stack operations... provided that the code being profiled doesn't shred r9 and r10 hehe... I forget what the most stable extended-x64 registers are...
also the "and rax, 0xFFFFFFFF" may be extraneous because I can't remember if RDTSC zeroes out the upper 32bits of RAX or not... so I included that AND operation just in case :)

A: This is a non-trivial task. The easiest way is to just look up the results of what others have found.
For example, Agner Fog as a great reference for this information on current x86/x64 processors: http://www.agner.org/optimize/instruction_tables.pdf
If you actually want to measure instruction latencies and throughput yourself, you will need very in-depth knowledge of how processors work. And then you'll have to dive into assembly coding. Writing micro-benchmarks to measure these things is almost a field in itself as there's a lot of reverse engineering that's needed.
And of course, in the end - performance of an application depends on many more factors than just instruction latencies/throughput...


text:
Q: Want to filter out failure Message from my robot framework output files I want to filter failure messages from output files generated after executing my testcases in Robot Framework. I have tried modules like from robot.api import ExecutionResult but it gives me only only count of Passed and Failed Testcases.
I have also tried other Robot framework Libtraries like import robot.errors to filter out all error messages but didn't get any luck. Below is my code block:
`
#!/usr/bin/python
from robot.api import ExecutionResult
import robot.errors
from robot.result.visitor import ResultVisitor
xmlpath = "<output.xml PATH>"
result = ExecutionResult(xmlpath)
result.configure(stat_config={'suite_stat_level': 2,
                              'tag_stat_combine': 'tagANDanother'})
stats = result.statistics
print stats.total.critical.failed
print stats.total.critical.passed
print stats.total.critical.passed + stats.total.critical.failed

class FailureCollector(ResultVisitor):
    def __init__(self):
        self.failures = []

    def visit_test(self, test):
        if not test.passed:
        self.failures += [test]

failure_collector = FailureCollector()
result.visit(failure_collector)
print failure_collector.failures
#the above print gives me all failed testcases as a list Eg: ['test1:My example Testcase1','test2:My example Testcase2' ]`

Any example to get this work done will be very helpful.

A: I have tried a lot to get my expected output by using Robot Framework APIs but didn't get proper solution. Finally I got my solution by using import xml.etree.ElementTree as ET module. By using xml.etree.ElementTree module I am parsing my robot result.xml file and getting my work done.
`
import xml.etree.ElementTree as ET
import re

tree = ET.parse('<output.xml file Path>')
root = tree.getroot()
testplans = <Testplans as a list>

i = 0
err_dict = {}
for testplan in testplans:
  full_err_list = []
  err_list = []
  for suite_level_1 in root:
      try:
        if suite_level_1.tag == "suite":
          for suite_level_2 in suite_level_1:
            if suite_level_2.tag == "suite" and suite_level_2.attrib['name'] == testplan:
              for suite_level_3 in suite_level_2:
                if suite_level_3.tag == "suite":
                  for test in suite_level_3:
                    if test.tag == "test":
                      for kw_level_5 in test:
                        if kw_level_5.tag == "kw" and kw_level_5.attrib['name'] == '<specific keyword under which you expect your result(error or Success message >':
                          for msg in kw_level_5:
                            if msg.tag == 'msg':
                              err_str = msg.text
                              #print err_str
                              mat = re.match(r'\$\{FinalResult\}\s=\s(.*)',err_str)
                              if mat and mat.group(1) != 'Succeeded.':
                                i=i+1
                                #print mat.group(1), i
                                err = mat.group(1)
                                full_err_list.append(err)
                                if err not in err_list:
                                    err_list.append(err)
      except:
        print "Errors found"
        break
      err_dict[testplan] = err_list
  print "\n##########  "+testplan+"  ##########\n"
  print "Total no of failures", len(full_err_list)
  for err_name in err_list:
    print err_name, "===>>", full_err_list.count(err_name)
##The above will print the error name and its count in specific testPlan`


text:
Q: Error: connect ECONNREFUSED 127.0.0.1:3000 when starting my app with nodemon I'm very new to Node.js and I installed nodemon globally, but while when I start my app with npm start command in terminal I do get the message:
vinnytwice@Vinnys-iMac fixit_server_node % npm start

> fixit_server_node@1.0.0 start
> node server.js

App executing to port  3000

while if I use the command nodemon start in terminal I get:
vinnytwice@Vinnys-iMac fixit_server_node % nodemon start
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node start index.js`
[nodemon] clean exit - waiting for changes before restart

not showing any execution on any port, and in fact when hitting an endpoint I get Error: connect ECONNREFUSED 127.0.0.1:3000.
If instead I start it with the command nodemon server.js then it does work.
Why npm start fired the server.js file and nodemon start doesn't? Is there something I shaven't set properly?

A: nodemon isn't a replacement of npm, they are totally different.
You can crudely think of nodemon being a drop in for node.

nodemon is a replacement wrapper for node. To use nodemon, replace the word node on the command line when executing your script.

Source: https://www.npmjs.com/package/nodemon
Hence if your npm script has,
"start": "node server.js"

Add another npm script,
"dev": "nodemon server.js"

You would want to use npm start in production environment and use npm run dev in development environment
You are seeing the ECONNREFUSED error because in your package.json there is a field,
"main": "index.js"

when you execute nodemon start, nodemon picks up this value and it actually runs node start index.js as shown in your logs.

If no script is given, nodemon will test for a package.json file and if found, will run the file associated with the main property

Source: https://www.npmjs.com/package/nodemon
Your index.js doesn't setup the server and hence when you try to access 127.0.0.1:3000 to hit your endpoints nothing is running there and hence you get ECONNREFUSED error

A: Notice this line
starting `node start index.js`

The output of your command nodemon start states that the file index.js is executed instead of server.js. You need to check your package.json file to see what is the main file of the program.
From the npm page of nodemon here

If you have a package.json file for your app, you can omit the main
script entirely and nodemon will read the package.json for the main
property and use that value as the app.
nodemon will also search for the scripts.start property in
package.json (as of nodemon 1.1.x).


text:
Q: Voting economy: balancing credits properly Many websites today (including stackoverflow) and games allow people to perform voting, give feedback, enable additional features etc, according to a score: eg. reputation, or MMORPG credits.
As a programmer that will probably need to implement a community based website in the near future, I am interested in knowing about the existence of basic algorithms and decisions to be made so that everything is balanced. For example, the fact that one vote up grants 10 reputations and one down grants -2 was arbitrary or properly weighted ? How to decide the price of a given item and the rewards in a MMORPG, so that everything is balanced? I guess that WoW designers relied on their experience, but I am also sure that this experience can be found somewhere written down. Although this is a social problem, the pricing of a given feature and the reward for a given task are technical/mathematical ones, as you need to give a value to each feature according to some mathematical criteria (although not easy to devise, I guess)
Of course, this question could bring us far in terms of theory of economics, but I am sort of hoping that there are well defined and known simplified patterns and rules for this issue. I just don't know the keywords to query for.

A: Probably the most important thing to point out here is that this is a social problem not a technical one.
By that I mean that you could use the exact same system as SO on an MMORPG and it would flop or have really undesirable side effects. Whether a system works or not depends on the community you drop it into and the intended purpose. It can also depend on some luck whether people latch onto it or not. You may get early negative behaviour that sets the tone for future negativity and discourages positive involvement. Or it could go completely the other way.
There is no magic formula that made the vote/rep weighting what it is on SO other than long discussions about how to encourage certain behaviour and then some testing and fine-tuning. For example, a downvote costs 1 rep and is -2 rep to the recipient. The guiding principle was that downvotes should cost. After that, it was trial by error.
You might want to read The Value of Downvoting, or, How Hacker News Gets It Wrong and Vote Fraud for some of Jeff's and Joel's thoughts on that subject. Joel's Tech Talk on Stackoverflow at Google is also enlightening.

A: Voting is actually a very difficult problem. There are so many models of voting, and they all produce different results. For example, choosing your one favorite candidate versus ranking candidates produces a different result. Choosing your LEAST favorite candidate produces a different result. Organizing choices into good/bad produces different results.
Balancing then becomes something that can be done by asking the community. It's very difficult to balance games of that magnitude, simply because even your most exhaustive tests wont cover all of the cases. Having a properly established forum where users can give their opinions as well as having testers who watch out for balancing issues is probably the best way to go.
Oh, and if you want an abstract about the voting problem I mentioned, it's here:
http://www.cs.rochester.edu/~lane/computational-politics.html


text:
Q: Can't read values Inheritance in java Im writing a simple program to illustrate classes and inheritance in java. The program is Bank that has 2 classes Account and Operation where Operation extends Account. Now in main I declared the values in Account and then I started calling the operations from Operation class. now whenever Operation calls the values in Account it return 0 for int and null for string though I added value to it.
Here is the Account:
public class Account {

 private String Name;
 private int ID;
 private double Money;

Account()
{

}
Account (String n, int i, double m)
{
    Name = n;
    ID = i;
    Money = m;
}

public void setMoney(double m)
{
    Money = m;
}

public double getMoney()
{
    return Money;
}

public int getID()
{
    return ID;
}

public String getName()
{
    return Name;
}

public void Check()
{
    System.out.println("Your Name is: " + Name + " Your ID is: " + String.valueOf(ID) + " Your Balance is: " + String.valueOf(Money));
}

}

Here is the Operation class:
import java.util.Date;

public class Operation extends Account{

private Date TransactionDate;

public void Withdraw(double amount)
{
    double Money = getMoney();
    if (amount > Money)
        System.out.println("The amount is insufficient");
    else
    {
        Money = Money - amount;
        TransactionDate = new Date();
        setMoney(Money);
        System.out.println("The available money is " + String.valueOf(Money) + " at " + String.valueOf(TransactionDate));

    }
}

public void Deposit(double amount)
{
    double Money = getMoney();
    if (amount < 0)
        System.out.println("You cant add minus");
    else
    {
        Money = Money + amount;
        TransactionDate = new Date();
        setMoney(Money);
        System.out.println("Your credits are: " + String.valueOf(Money) + " at " + String.valueOf(TransactionDate));
    }
}

public void Check()
{
    String Name = getName();
    int ID = getID();
    double Money = getMoney();

    System.out.println("Your Name is: " + Name + " Your ID is: " + String.valueOf(ID) + " Your Balance is: " + String.valueOf(Money));
}
}

Here is the main:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

 public class Main {

/**
 * @param args
 * @throws IOException
 * @throws NumberFormatException
 */
public static void main(String[] args) throws NumberFormatException,
        IOException {
    // TODO Auto-generated method stub

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Enter your ID");
    int ID = Integer.parseInt(br.readLine());
    System.out.println("Enter your Name");
    String Name = br.readLine();
    System.out.println("Enter your Money");
    double Money = Double.parseDouble(br.readLine());

    Account a = new Account(Name, ID, Money);
    a.Check();

    Operation o = new Operation();

    while (true) {
        System.out.println("\n-----------------------------------");
        System.out
                .println("Enter 1 to withdraw, 2 to Deposit, 3 to Check, 4 to exit ");
        int operation = Integer.parseInt(br.readLine());
        switch (operation) {
        case 1:
            System.out.println("enter the amount");
            double withdrawMoney = Double.parseDouble(br.readLine());
            o.Withdraw(withdrawMoney);
            break;
        case 2:
            System.out.println("enter the amount");
            double Depositmoney = Double.parseDouble(br.readLine());
            o.Deposit(Depositmoney);
            break;
        case 3:
            o.Check();
            break;
        case 4:
            break;
        default:
            System.out.println("enter between 1 and 4 only");
        }

        if (operation == 4)
            break;
    }

}

}

I really don't know why Operation cant read the values I added to Account since Operation extends Account can you please explain it to me the reason and how to fix it.
Thanks in advance.

A: You have two separate objects -- one an Account, and one an Operation.
An instance of your Operation class has a name, ID and money - but they're not the same name, ID and money as other instances of Account or Operation.
One way to fix it would be to add a constructor to Operation:
class Operation {
    Operation(String n, int i, double m) {
        super( n, i, m );
    }
    ...
}


text:
Q: Unknown column 'Extent2.IdentityUser_Id' in 'field list' I got this error message Unknown column 'Extent2.IdentityUser_Id' in 'field list' when I try to customize Application User.
Full error:

Unknown column Extent2.IdentityUser_Id' in 'field list'

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: MySql.Data.MySqlClient.MySqlException: Unknown column 'Extent2.IdentityUser_Id' in 'field list'
Line 96: var user = await UserManager.FindByNameAsync(model.UserName);

I have existed Mysql db with user table. I can not to use other table. I have to keep MyUser table and I add some table follow Asp.Net Identity definitions:
In IdentiyModels.cs :
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext(): base("KadContext")
            {
            }

            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
            protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);

                modelBuilder.Entity<IdentityUser>().ToTable("ad_users").Property(p => p.Id).HasColumnName("id");
                modelBuilder.Entity<IdentityUser>().ToTable("ad_users").Property(p => p.UserName).HasColumnName("user_name");
                p.PasswordHash).HasColumnName("user_password");
                modelBuilder.Entity<ApplicationUser>().ToTable("ad_users").Property(p => p.Id).HasColumnName("id");
                modelBuilder.Entity<ApplicationUser>().ToTable("ad_users").Property(p => p.UserName).HasColumnName("user_name");

                modelBuilder.Entity<IdentityUserRole>().ToTable("ad_userroles");
                modelBuilder.Entity<IdentityUserLogin>().ToTable("ad_userlogins");
                modelBuilder.Entity<IdentityUserClaim>().ToTable("ad_userclaims");
                modelBuilder.Entity<IdentityRole>().ToTable("ad_roles");
            }
        }

I want to hook into OWIN Self Hosting to create Authencation for login features
In AccountController.cs :
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var user = await UserManager.FindByNameAsync(model.UserName);
    var identity = await SignInManager.CreateUserIdentityAsync(user);
    AuthenticationManager.SignIn(identity);

    return RedirectToLocal(returnUrl);
}

I only to use AuthencationManager to manage Authencation after I check user permission from LDAP server. So that I want to hook ASP.NET Identity OWIN on MVC 5 system.
Does anyone see this error? I need a solution to go through it.

I found this way I want can not reach . Due to ASP.NET Identity OWIN on MVC 5 System need a sets of tables User, Roles, Claims. If you want to custom them should follow here http://www.jamessturtevant.com/posts/ASPNET-Identity2.0-Custom-Database/

*

*I also am trying to hook like an external system (ex google, facebook...) .  I think I must create an temp request from external system with full information after request ASP.Identity  OWIN allow create Authentication User.

Does anyone have full solution for that!?


text:
Q: Verificar contraseña C# Generando un contraseña quiero verificar que tenga al menos un carácter, un número y un carácter especial. Mi método contrasenaSegura siempre me devuelve 'false' aunque cumpla todos los requisitos.
class Contrasenia {
    private const String CRITERIOS_CARACTERES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private const String CRITERIOS_NUMERICOS = "0123456789";
    private const String CRITERIOS_ESPECIALES = "!\"#$%&'()*+,-./:;=?@[]^_`{|}~";

    public String GenerarContrasena() {
        Char castearEnterosAutogenerados;
        String contrasenaGenerada = "";
        Char[] caracteresExcluidos = { 'á', 'é', 'í', 'ó', 'ú', 'Á', 'É', 'Í', 'Ó', 'Ú', 'ñ', 'Ñ' };
        int[] enterosGenerados = new int[8];
        Random numeroEnteroRandom = new Random();

        do {
            for (int contador = 0; contador < enterosGenerados.Length; contador++) {
                enterosGenerados[contador] = numeroEnteroRandom.Next(32, 138); //RANGO IMPRIMIBLES: 126, CON EXCLUIDOS : 138
                if (enterosGenerados[contador] > 126) {
                    enterosGenerados[contador] = numeroEnteroRandom.Next(0, 12);
                    contrasenaGenerada += caracteresExcluidos[enterosGenerados[contador]];
                }
                else {
                    castearEnterosAutogenerados = (Char)enterosGenerados[contador];
                    contrasenaGenerada += castearEnterosAutogenerados;
                }
            }
        } while (ContrasenaSegura(contrasenaGenerada) == false);
        return (contrasenaGenerada);
    }
    public Boolean ContrasenaSegura(String contraseñaSinVerificar) {
        Boolean cumpleCriterios = false;

        if (contraseñaSinVerificar.Contains(CRITERIOS_CARACTERES)) {
            if (contraseñaSinVerificar.Contains(CRITERIOS_NUMERICOS)) {
                if (contraseñaSinVerificar.Contains(CRITERIOS_ESPECIALES))
                    cumpleCriterios = true;
            }
        }
        return (cumpleCriterios);
    }
}

¿Dónde de ubica el error?

A: Tu mejor aliado en estas situaciones serian las expresiones regulares y su metodo IsMatch.
using System.Text.RegularExpressions;
public Boolean ContrasenaSegura(String contraseñaSinVerificar) {
    //letras de la A a la Z, mayusculas y minusculas
    Regex letras = new Regex(@"[a-zA-z]");
    //digitos del 0 al 9
    Regex numeros = new Regex(@"[0-9]");
    //cualquier caracter del conjunto
    Regex caracEsp = new Regex("[!\"#\\$%&'()*+,-./:;=?@\\[\\]^_`{|}~]");

    Boolean cumpleCriterios = false;

    //si no contiene las letras, regresa false
    if(!letras.IsMatch(contraseñaSinVerificar)){
        return false;
    }
    //si no contiene los numeros, regresa false
    if(!numecaracEspros.IsMatch(contraseñaSinVerificar)){
        return false;
    }

    //si no contiene los caracteres especiales, regresa false
    if(!caracEsp.IsMatch(contraseñaSinVerificar)){
        return false;
    }

    //si cumple con todo, regresa true
    return true
}

Antes de llegar a return true; puedes agregar otras validaciones como por ejemplo que cumpla con un minimo de caracteres.

A: Aunque la solución de utilizar expresiones regulares es correcta, respondiendo a tu pregunta, creo que el problema lo tienes en este tipo de expresiones:
contraseñaSinVerificar.Contains(CRITERIOS_CARACTERES)

Lo que comprueba el método Contains es si una cadena está dentro de otra, es decir, estás mirando realmente si la cadenas CRITERIOS_CARACTERES aparece completa al menos una vez en la cadena contraseñaSinVerificar, que normalmente va a ser siempre false.
Lo que deberías hacer es comprobar si alguno de los caracteres está dentro de la cadena que estás buscando, algo así:
 foreach (char character in contraseñaSinVerificar)
     if (CRITERIOS_CARACTERES.IndexOf(character) >= 0)
         return true;
 return false;

Por supuesto, yo lo haría dentro de una función con dos parámetros: la cadena a verificar y la cadena que contiene todos los caracteres y comprobaría para los tres tipos de esta forma:
 return ExistsCaracter(ContraseñaSinVerificar, CRITERIOS_CARACTERES) &&
        ExistsCaracter(ContraseñaSinVerificar, CRITERIOS_NUMERICOS) &&
        ExistsCaracter(ContraseñaSinVerificar, CRITERIOS_ESPECIALES);

Por supuesto, añade verificaciones del tipo cadena vacía / nula y demás sospechosos habituales.


text:
Q: Cython wrap c lib with setup.py build_clib I decided to refactor my C api wrapper and dive deeper into libraries argument in setuptools.setup
My project structure is following:
|setup.py
|my_pkg
|--|ext_c_lib
|--|--|include
|--|--|--|c_file.h
|--|--|--|c_types.h
|--|--|src
|--|--|--|c_file.c
|--|cy_lib
|--|--|pxd_include
|--|--|--|__init__.py
|--|--|--|c_file.pxd   # functions redefined `with cdef exten from "c_file.h"`
|--|--|--|c_types.pxd  # types redefined `with cdef exten from "c_types.h"`
|--|--|__init__.py
|--|--|utils.pyx       # uses types from c_types.pxd
|--|--|cy_file.pyx     # uses funcs from c_file.c/c_file.pxd

utils.pyx:
from my_pkg.cylib.pxd_include.c_types cimport SOME_CUSTOM_TYPE
...

cy_file.pyx:
from my_pkg.cylib.pxd_include.c_file cimport c_func

cdef cy_func(arg):
    arg += 1
    return c_func(arg)

setup.py:
...
extensions = [Extension('my_pkg.cy_lib.utils', ['my_pkg/cy_lib/utils.pyx']),
              Extension('my_pkg.cy_lib.cy_file', ['my_pkg/cy_lib/cy_file.pyx',
                                                  'my_pkg/ext_c_lib/src/c_file.c']),]

setup(name='my_pkg', ext_modules=extensions, include_dirs=['my_pkg/ext_c_lib/include'])

As ext_c_lib does not depend on me and releases quite rare I would like to build it as an external library with python setup.py build_clib and then use it in cython files, so I could get rid of pxd files and compiling c_file.c once, even if I add separate cython file that uses functions from c_file.c. Is that possible?
I expect something like:
setup.py:
...
external = ('external', {'sources': ['my_pkg/ext_c_lib/src/c_file.c']})
extensions = [Extension('my_pkg.cy_lib.utils', ['my_pkg/cy_lib/utils.pyx']),
              Extension('my_pkg.cy_lib.cy_file', ['my_pkg/cy_lib/cy_file.pyx']),]

setup(name='my_pkg', libraries=external,
      ext_modules=extensions, include_dirs=['my_pkg/ext_c_lib/include'])

utils.pyx:
from external cimport SOME_CUSTOM_TYPE
...

cy_file.pyx:
from external cimport c_func

cdef cy_func(arg):
    arg += 1
    return c_func(arg)

Of course this code does not compile as I get external.pxd not found


text:
Q: Efficient TFS branching strategy advice Our company (internal projects) used version control (TFS, now 2015) for simply keeping an audit trail of released code - I have brought in the use of branching and merging and its completely changed the way we look at bottlenecks in the development pipeline and has generally been well received, but now I am looking for the next step.
Our code consists of one large piece of software and several other accompanying business applications.
We have four environments we keep up at all times, and our 'pipeline' is like so.

*

*Developer does work locally.

*Pushes code to a 'Development' environment (so we can all look at the code, see how well it integrates in the environment e.t.c)

*When testing is ready we push to 'Test' - this is code that has been approved to be moved up the pipeline and therefore the
environment is a lot more stable than 'Development'.

*Next, we pass it to the UAT server, which is essentially a mimic of the live server, to be as stable and representative of a live release
as possible. Code approved to move here is NOT frequent.

*Finally, production environments.

Now I simply took the approach of having a branch for each environment, allowing for easy compares, for people to quickly grab the source and whatnot, and to see the progression of the codebase up the chain.
MAIN -> STAGE -> TEST -> DEV
This is one single, linear line, and we can simply view the history of the MAIN branch to see all the different released builds.
From the dev branch we splinter off into our local branches, and any hotfixes come directly off the UAT branch.
This works for us - but it works in the sense a procedural program could work - it may not be the most effective approach.
I'm just very curious as to whether there are better ways to do this, and after reading loads of stuff online I feel like people don't split their branches by environment but I don't really understand how that works better? Even though it is a pain to merge four times to release some code (although most of the time it is a rather slow pipeline, we have weekly releases).
Any help much appreciated.

A: You are correct when mentioned that the more complex the branching strategy the more overhead to maintain.
But if the situation demands there are not escaping. If you have not gone through the branching strategy document by ALM rangers for TFS, please take a look. It should help you.
I think the strategy you are following is not an linear branching but rather the one in the below image.
In a more complex enterprise software the branching strategy boils down to this.

A: I think it's a lot of overhead to maintain different branches for each environment as you rightly mentioned above (especially the number of merges). The simplest branching strategy is the one shown below (similar to what we use):
               Main
             |     |
             |     |
            DEV  Release

The development would happen in the DEV branch, once it is ready for UAT we merge it into MAIN and then create a Release branch. You can use the DEV branch for the next release development at this point and all the bug fixes for the current release will happen in the release branch now. The Release branch will be used for the PROD deployment as well.
As for whether this would work for you or not will depend on your specific needs but 80% of the projects I worked with uses the above branching strategy.


text:
Q: Performance of using cursor PLSQL I have to get a count using a cursor.
the basic cursor is
get *
from table

In here there are three types of data I want to get the count of.
sysdate < start_date
sysdate > startdate and sysdate < enddate
sysdate > enddate

I have 2 ways of doing this.

*

*Loop the above cursor and use a if condition to get the counts.

*Create 3 separate cursors with the conditions and directly get the count
As I have a lot of data what way would be good in perspective of performance ?

A:

*Don't use a cursor at all.

Use conditional aggregation. That's almost surely faster than any cursor based approach.
SELECT count(CASE
               WHEN sysdate < start_date THEN
                 1
             END) count1,
       count(CASE
               WHEN sysdate > startdate
                    AND sysdate < enddate THEN
                 1
             END) count2,
       count(CASE
               WHEN sysdate > enddate THEN
                 1
             END) count3
       FROM elbat;


text:
Q: Morita equivalence and Hopf algebras Lately I've worked on an example that for a group $G$ the $G$-graded vector spaces $G$-vect and $G$-rep, the category of representations on $G$,  are Morita equivalent.
I did that by taking the finite dimensional vector spaces vect$_k$ ($k$ a field) as a right module category over $G$-vect. Then I showed that $\mathrm{Fun}_{G-\mathrm{vect}}(\mathrm{vect}, \mathrm{vect})$ is equivalent to $G$-rep and by that those two are Morita equivalent.
It holds that $$k[G]-\mathrm{mod} \cong G-\mathrm{rep}$$ and $$k[G]-\mathrm{comod} \cong G-\mathrm{vect}.$$
One can now ask if a similar Morita equivalence holds for an arbitrary finite dimensional Hopf algebra $H$. It is known that $H-\mathrm{comod} \cong H^*-\mathrm{mod}$. So the question basically is:
Are $H-\mathrm{mod}$ and $H^*-\mathrm{mod}$ Morita equivalent?
As modules over a Hopf algebra are defined as vector spaces with an action (in my case at least) one can again take the vector spaces $\mathrm{vect}$ as the module category. But afterwards in my original proof I used especially representation-properties which I now don't have anymore.
Has someone worked with this before?
I'm grateful for anything - tips on how to handle this, literature-tips or maybe even concrete tips on the proof (but I think maybe my question is too wide for this).


text:
Q: Parallel Recursive Bitonic Sort slower than Serial (OpenMP) My OpenMP (C) parallel code is slower than the serial bitonic sort code and although I have done all the possible combinations I could think of, I can't find the problem.
Here is part of the code:
void recBitonicSortOpenMP( int lo, int cnt, int dir ) {
   if (  cnt >  1 ) {
         int k = cnt / 2;
         #pragma omp parallel sections
         {

         #pragma omp section
         recBitonicSortOpenMP( lo,     k, ASCENDING );

         #pragma omp section
         recBitonicSortOpenMP( lo + k, k, DESCENDING );

         }
         bitonicMergeOpenMP( lo, cnt, dir );

   }

}

It is an implementation of Bitonic Sort.

A: For recursive problems like this use OpenMP tasks, not nested parallelism and sections.
http://cs.umw.edu/~finlayson/class/fall16/cpsc425/notes/24-sorting.html gives you a good example to follow...

A: You should try to parallelize the imperative version of the algorithm. I think the recursive version is an inherently serial problem.
There are many pragmas useful to parallelize "For" cycles.
http://www.openmp.org/specifications/
Two version of the algorithm:
https://www.cs.duke.edu/courses/fall08/cps196.1/Pthreads/bitonic.c


text:
Q: Will a Cloud Function finish if HTTP request is cancelled? I have a Python 3.7 Cloud Function that is triggered via HTTP request.
Function execution can take up to several seconds (2-5).
In some cases, the HTTP request is sent using Javascript from the website's front end.
My questions is, will the Cloud Function finish it's execution normally even if the browser window (that triggered the HTTP request using JS) is closed or user navigates to another page. The function returns "ok" but in that case it doesn't have a destination where to return it.

A: The function code doesn't do anything differently based on what happens to the client after the request is sent.  In fact, it is not even possible to try to cancel the function's execution after the request has been sent.
Closing the connection doesn't affect the outcome from the function's point of view.  If a client closes the connection before the response is received, it will just not receive any response generated by the function, so you can not be certain if the client acted on any information returned by the function.


text:
Q: TS2345: Argument of type 'RolesGuard' is not assignable to parameter of type 'CanActivate'
error TS2345: Argument of type 'RolesGuard' is not assignable to
  parameter of type 'CanActivate'.   Types of property 'canActivate' are
  incompatible.
      Type '(req: any, context: ExecutionContext) => any' is not assignable to type '(context: ExecutionContext) => boolean |
  Promise | Observable'.
app.useGlobalGuards(new RolesGuard(new Reflector()));

This is how my code looks like.
app.useGlobalGuards(new RolesGuard(new Reflector()));

import { Guard, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import { merge, reduce } from 'rxjs/operators';

import { from } from 'rxjs/observable/from'
import { Reflector } from '@nestjs/core';
import { getManager } from "typeorm";
import { MODULES, FEATURES } from '../constant';

@Guard()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) { }

  canActivate(req, context: ExecutionContext): Promise<boolean> {
    const { parent, handler } = context;
    const permissions = this.reflector.get<string[]>('Permission', handler);
    if (!permissions) {
      return new Promise((res, rej) => { res(false) });
    }
    .
    .
    .
    .
    //if there are more than two set of permissions
    if (permissions.length > 3) {
      let perms = Array.from(permissions);
      perms.splice(2, 1);
      let whereClause = perms.reduce((acc, val, index) => {
        let paramNo = index + 2;
        if (index % 2 === 0) {
          return `${acc}(module=$${paramNo}`;
        } else {
          return `${acc} AND feature=$${paramNo}) OR `
        }
      }, "");
      .
      .
      .
    }

    return entityManager.query(sql, params).then(res => {
      let perms = <Array<any>>res;
      let type = permissions[2].toLowerCase();
      if (type === 'view') {
        return perms.reduce((acc, val) => { return (val['canview'] || val['canedit']) || acc }, false);
      } else if (type === 'edit') {
        return perms.reduce((acc, val) => { return val['canedit'] || acc }, false);
      } else {
        return false;
      }
    });
  }
}

A: The signature of your interface is wrong. For some reason you've added a redundant req parameter.
From the NestJS docs, this is the official example of what a guard should look like:

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    return true;
  }
}

Notice how canActivate only has one argument - context: ExecutionContext. This is also fairly obvious from the error message.
So you should be able to fix your problem by removing req.


text:
Q: Extra Carriage Returns while reading CSV I have some CSV files that I am trying to parse using Java. I first extract a single row from the CSV file and send it to another method for processing with the following code:
for (String tempFile : filesToBeRead) {
        File csvFile = new File(tempFile);
        Scanner scanner =  new Scanner(csvFile);
        scanner.useDelimiter("[\n\r]");
        scanner.next();
        while(scanner.hasNext()) {
            String temp = scanner.next();
            System.out.println(temp);
//          dataStorage.enterRow(temp);

            }
        }

The output of the above code is:
AI277|DEL|MUB|05-12-2013|0600|4.10|5500|Y|EB

AI279|DEL|MUB|10-12-2013|0630|4.30|4900|Y|E

AI289|DEL|MUB|10-12-2013|0830|4.00|5650|Y|EB

AI278|DEL|MUB|17-12-2013|1830|4.20|5300|Y|E

AI278|DEL|MUB|20-12-2013|1430|3.45|6500|N|EB

Where as the output should have been:
AI277|DEL|MUB|05-12-2013|0600|4.10|5500|Y|EB
AI279|DEL|MUB|10-12-2013|0630|4.30|4900|Y|E
AI289|DEL|MUB|10-12-2013|0830|4.00|5650|Y|EB
AI278|DEL|MUB|17-12-2013|1830|4.20|5300|Y|E
AI278|DEL|MUB|20-12-2013|1430|3.45|6500|N|EB

What exactly is happening and where is this extra carriage return (\r) coming from even though the regex is set appropriately?

A: The below regex would match one or more newline character or carriage return,
"[\n\r]+"

Just set the above regex as delimiter. That is change this scanner.useDelimiter("[\n\r]"); line  to ,
scanner.useDelimiter("[\n\r]+");


text:
Q: How to use throw from within do block? I would like to throw error from within do block, if that is possible
I have a function getWeatherBy, it is signed as a throwing function. My code elsewhere in the app is depending on this throwing. I have inside of this function a JSONDecoder.decode that is throwing function itself, I have that inside of a do block. However, if there is an error with JSONDecoder, I would like to throw error from getWeatherBy, but since that throwing is happening inside of a JSONDecoder, it is being catched there.
Sorry for the messy code. I am still a newbie, any ideas how to make this code better is more than welcomed!
func getWeatherBy(city: String, completion: ((WeatherRecord) -> ())?) throws {
        let trimmedCityName = (city as NSString).replacingOccurrences(of: " ", with: "+")

        let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(trimmedCityName.lowercased())&appid=\(self.OpenWeatherAPIkey)&units=metric")
        guard url != nil else { return }
        print(url!)

        let networkTask: URLSessionDataTask = URLSession.shared.dataTask(with: url!) {
            (data, response, error) in
            guard let data = data else { return }

            do {
                let decoded = try JSONDecoder().decode(WeatherData.self, from: data)
                if (decoded.main != nil) {
                    if (decoded.coord?.lat != nil) {
                        DispatchQueue.main.async {
                            let record = WeatherRecord(temperature: Float(decoded.main!.temp), date: Date(), coordinates: CLLocationCoordinate2D(latitude: decoded.coord!.lat, longitude: decoded.coord!.lon), distance: 0.0)

                            if completion != nil {
                                completion!(record)

                            }
                        }
                    }
                } else {
                    throw serviceError.cityNotFound
                }

                if (decoded.message != nil) {
                    print("Message: \(decoded.message!)")

                    DispatchQueue.main.async {
                        if (String(describing: decoded.message!).contains("Your account is temporary blocked") == true) {

                        }

                        if (decoded.message! != "Nothing to geocode") || String(describing: decoded.message!).contains("Your account is temporary blocked") != false {

                        }
                    }
                }
            } catch DecodingError.keyNotFound(let key, let context) {
                Swift.print("Could not find key \(key) in JSON: \(context.debugDescription)")
            } catch DecodingError.valueNotFound(let type, let context) {
                Swift.print("Could not find type \(type) in JSON: \(context.debugDescription)")
            } catch DecodingError.typeMismatch(let type, let context) {
                Swift.print("Type mismatch for type \(type) in JSON: \(context.debugDescription) \(context)")
            } catch DecodingError.dataCorrupted(let context) {
                Swift.print("Data found to be corrupted in JSON: \(context.debugDescription)")
            } catch let error as NSError {
                NSLog("Error in read(from:ofType:) domain= \(error.domain), description= \(error.localizedDescription)")
            }
        }

A: The most common way is to add an error with / without new Result
func getWeatherBy(city: String, completion: ((WeatherRecord? , Error?) -> ()))

you can't throw from an asynchronous method immediately


text:
Q: Discord Bot, that gives role to a new members Bot is simply don`t work :/ The bot doesnt give any errors & roles. I will be grateful for any help
import discord
from discord.ext import commands
from discord.utils import get

client =  discord.Client()

@client.event
async def on_ready():
    print('Bot is ready')

@client.event
async def on_member_join(member):
    role = discord.utils.get(member.server.roles, id="role_id")
    await client.add_roles(member, role)

client.run('TOKEN')

A: Enabling intents should solve your problem.
Firstly, enable the Server Members Intent by following the instructions here.
Next, implement these intents while initializing your Client object.
import discord

intents = discord.Intents.default()
intents.members = True

client = discord.Client(intents=intents)

I'm not sure what version of discord.py you're running, but in the most recent one, you add roles with await Member.add_roles()
@client.event
async def on_member_join(member):
    role = discord.utils.get(member.guild.roles, id="role_id")
    await member.add_roles(role)

If you're on an older version of Discord.py, ignore the above snippet.


text:
Q: Перемещение данных между lua и c++ Собственно ситуация такая: у меня есть библиотека для lua (написана на c++) которая предоставляет доступ к некоему объекту из c++ кода (допустим, вектору). При этом этот объект аллоцирует память в куче, а сам объект я размещаю в userdata lua, примерно так:
std::vector<int> *buf = reinterpret_cast<std::vector<int> *>(lua_newuserdata(state, sizeof(std::vector<int>)));
new (buf) std::vector<int>(10);

Помните: то, что выше - это вызов C++ из Lua! Когда я вызываю из C++(!) скрипт на lua, который возвращает мне подобный объект (userdata с размещенным в нем std::vector) в с++ я произвожу нечто подобное:
std::vector<int> out;
auto *vec = reinterpret_cast<std::vector<int>*>lua_touserdata(state, -1));
if (vec) {
  out = std::move(*out);
}

Как видите, я использую move чтобы избежать ненужного копирования. Так вот, все вроде работало прекрастно, пока не потребовалось собрать прилагу под windows. В результате я начал получать segmentation fault из-за того, что out был поврежден. Как-будто, несмотря на move данные выделенные в куче были освобождены по выходу из скрипта. Собственно вопрос: насколько безопасно перемещать таким образом данные?
PS lua-5.1.5
PSS также забыл упомянуть, что для избежания утечек памяти объекту в lua был добавлен метод __gc в котором просто вызывается деструктор условного вектора. Он отрабатывает по завершению всего скрипта


text:
Q: Playing video with AVPlayer like in FullScreen in Portrait I want to play video with AVPlayer like in FullScreen like in Landscape device orientation but from Portrait orientation.
For that I need to rotate videoLayer. I tried to do that with code
 theLayer.transform = CATransform3DMakeRotation(CGFloat(M_PI_2), 0.0, 0.0, 1.0);

but videoLayer does not start from 0;0 coordinates. It starts some where in the center.
Also, I set that
   videoPlayerSceneLayer?.frame = CGRectMake(0, 0, bounds.size.height, bounds.size.width)

So, how can I solve that?