Q: How to disable a link button in gridview when clicked I have two LinkButton's called Approve and Reject in my GridView and I want my Approve LinkButton to be Disabled when click on it. I tried the following code but it's not working.
protected void gvManagerTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
        if (e.CommandName == "ApproveRow")
        {
            GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
            LinkButton lnkbtn = (LinkButton)row.FindControl("lbApprove");
            lnkbtn.Enabled = false;

            int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
            int TimeSheetId = Convert.ToInt32(e.CommandArgument);

            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

            using (SqlConnection con = new SqlConnection(CS))
            {
                SqlCommand cmd = new SqlCommand("spApproveTimeSheet ", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@TimeSheetId", TimeSheetId);

                con.Open();
                cmd.ExecuteNonQuery();

                GetManagerTimeSheets();
            }
         }

}

A: You need to Rebind the grid with disabled control, but also you need to check the status in itembound event and disable. For that you can use session or hidden field.
protected void rg_OnItemCommand(object source, GridCommandEventArgs e)
{
   // your logic
   hdFlag.value = "val" // id of the data item to hide if more than one use array
  // rebind logic for gird
}

protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
  if(hdFlag.value == "id")
  {
    // Find the control and hide
  }
}

A: Well you haven't shown your aspx link button so i assuming that your link button is this
<asp:LinkButton id="linkBtn" runat="server" text="Approve"  OnClientClick="Disable(this);"/>

Now you should add a javascript function like this on the page::
<script>
function Disable(link)
{
link.disabled = result;
}
</script>

Now when you click on the page your button will get disabled.

A: try this
 LinkButton lbApprove = (LinkButton)e.Row.Cells[0].Controls[0];


Q: What is the difference between private static variable and private instance variable in a singleton class? What is the difference between private static variable and private instance variable in a singleton class?
I see no semantic difference.
EDIT: Not asking if the variable holding the instance of itself should be static, but other data members.

A: The way I see it, there is only "no semantic difference" if you assume that the singleton is implemented using a static reference to the single instance. The thing is, static is just one way to implement a singleton — it's an implementation detail. You can implement singletons other ways, too.

A: There is no difference really (besides initialization blocks mentioned already). But on the other hand you are not really gaining anything also. You still need to take thread safety into consideration and you still need to make sure you have only one instance of your singleton at a time. The only difference would be if you wanted to publish that member via a public static method. But why on earth would you want to do that - I have no idea.
For me personally it would also be a bit of a "code smell". I mean someone made a singleton and still declared its member as static? What does it tell me? Is there something I don't know? Or maybe there's something wrong with the implementation and it has to be static (but why?!). But I'm a bit paranoid. From what I am also aware of there are no performance reasons why this would be a good option.

A: I'm not sure what you are looking for, so I'll write something and see what you have to say.
public class Elvis {
  private static final Elvis INSTANCE = new Elvis();
  private double weight; // in pounds

  private Elvis() { weight = 300.; } // inaccessible

  public static Elvis getInstance() { return INSTANCE; }

  public double getWeight() { return weight; }
  public void setWeight(double weight) { this.weight = weight; }
}

Since there is only one Elvis, you could have made weight a static variable (with static getter and setter).  If you make all variables static, then there is no point in defining a singleton INSTANCE since you just have a class with only static variables and methods:
public class Elvis {
  private static double weight; // in pounds
  static { weight = 300.; } // Could just have set the weight directly above,
                // but a static block might be useful for more complex examples.

  public static double getWeight() { return weight; }
  public static void setWeight(double weight) { this.weight = weight; }
}

I guess this should be avoided since it looks more like a header file in C than OO.
Some might have recognized the Elvis reference from J. Bloch "Effective Java".  The recommendation in that book is to implement the singleton pattern with an enum with one member:
public enum Elvis {
  INSTANCE;

  private double weight = 300.;

  public double getWeight() { return weight; }
  public void setWeight(double weight) { this.weight = weigth; }
}

Note that it looks somewhat non-standard here with the varying weight since you usually expect enum instances to be immutable.

A: There are differences, though.
For instance, you can't use a static block to initialize the former.

A: Probably it is better to implement it in the singleton, since that way you can override the singleton for tests and similar. Also, you keep your static state in a single place.


Q: Getting protein sequences by accessing Uniprot (with Python) I have a list of protein id's I'm trying to access the protein sequences from Uniprot with python.
I came across this post :Protein sequence from uniprot protein id python but gives a list of elements and not the actual sequence:
Code
import requests as r
from Bio import SeqIO
from io import StringIO

cID='P04637'

baseUrl="http://www.uniprot.org/uniprot/"
currentUrl=baseUrl+cID+".fasta"
response = r.post(currentUrl)
cData=''.join(response.text)

Seq=StringIO(cData)
pSeq=list(SeqIO.parse(Seq,'fasta'))

which gives output:
output
[SeqRecord(seq=Seq('MQAALIGLNFPLQRRFLSGVLTTTSSAKRCYSGDTGKPYDCTSAEHKKELEECY...SSS', SingleLetterAlphabet()), id='sp|O45228|PROD_CAEEL', name='sp|O45228|PROD_CAEEL', description='sp|O45228|PROD_CAEEL Proline dehydrogenase 1, mitochondrial OS=Caenorhabditis elegans OX=6239 GN=prdh-1 PE=2 SV=2', dbxrefs=[])]

I was just curious on how I can actually get the sequence itself.

A: [record.seq for record in pSeq]
edit:
You'll want str(pSeq[0].seq)


Q: Checkout git submodule in Azure Pipeline with SSH I try to checkout the git submodules via ssh instead of https (default if you use "Checkout submodules") in an Azure DevOps Pipeline. With the option in the picture it works - but for the developers it's annoying to enter the password all the time if they are working with the repository.

For that I used the following instructions to add the ssh key.
I created a public and a private key, and copied the known_host entry.
That's my YAML file snippet:
stages:
- stage: DeployBackend
jobs:
  - job: SSH
    steps:
      - task: InstallSSHKey@0
        inputs:
          knownHostsEntry: $(known_host)
          sshPublicKey: $(public_key)
          sshKeySecureFile: 'private_key_file'
  - job: Deploy
    steps:
      - checkout: self
        submodules: true
      - script: |
          -- here I run all docker commands to build the container and push it to Azure --
        displayName: "Deploy"

If I use the SSH keys to clone the repository to my local computer I have no issues. But if I run the pipeline it will crash at the submodule checkout:

Please make sure you have the correct access rights and the repository
  exists. fatal: clone of
  'git@ssh.dev.azure.com:v3/repoLink'
  into submodule path '/home/vsts/work/1/s/app/submoduleFolder' failed
  Failed to clone 'app/submoduleFolder'. Retry scheduled Cloning into
  '/home/vsts/work/1/s/app/submoduleFolder'... Host key verification
  failed. fatal: Could not read from remote repository.

That's the .gitmodules file in the repo - it works without any issues locally:
[submodule "app/subModuleName"]
    path = app/subModuleName
    url = git@ssh.dev.azure.com:v3/***/subModuleName
    branch = master

I even wrote the id_rsa, known_hosts and id_rsa.pub files into .ssh with a script, but it seems like they are not even used for ssh verification.

A: The solution is to do all the tasks in one job. Variables are not shared between different job instances.
This works:
jobs:
    - job: jobName
      steps:
        - task: AzureKeyVault@1
          inputs:
            azureSubscription: '***'
            KeyVaultName: '***'
          displayName: "Read Secrets from KeyVault"
        - task: InstallSSHKey@0
          inputs:
            knownHostsEntry: $(known_host)
            sshPublicKey: $(public_key)
            sshKeySecureFile: 'private_key_file'
          displayName: "Create SSH files"
        - script: |
            git clone --recurse-submodules git@ssh.dev.azure.com:v3/****
            git submodule update --init --recursive
            docker login -u $(userName) -p $(password) ***
            docker build ****
            docker push ****
          displayName: "Build and Push Docker Container"

A: An alternative is to edit the .gitmodules path to be a relative url, eg url = ../subModuleName:
[submodule "app/subModuleName"]
    path = app/subModuleName
    url = ../subModuleName
    branch = master

The url is now relative to the parent repo's url. So when the ado pipeline clones it via https, it uses the same for the submodule. Developers can clone the repo using either https or ssh, and the submodule will use the same - no need to enter passwords.


Q: Can I use a local path to json with Google Maps API Per the documentation here:
Can I replace:
map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');

with a local path such as:

C:\path\file.json ?

or must it be hosted on a server?
Thanks

A: In general, this used to be not allowed by design. It's a violation of the sandbox.
From Wikipedia -> Javascript -> Security:
JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-relatedactions, not general-purpose programming tasks like creating files.
However, it's now possible in current browsers using the FILE API specification.
This should in theory allow you to read it using the FileReader interface, although you might need to use something like JSON.parse() (or $.parseJSON if you're using JQuery) to then interpret it in the way you need. Lots more detail and examples of how to do this are here:
http://www.html5rocks.com/en/tutorials/file/dndfiles/


Q: Real Analysis - Riemann Integral I am having some difficulty with this problem:
Let $I := [a,b]$ and let $f: I\to\mathbb ℝ$ be continuous on $I$. Also let $J := [c,d]$ and let $u: J\to\mathbb ℝ$ be differentiable on $J$ and satisfy $u(J)\subseteq I$. Show that if $G: J\to\mathbb ℝ$ is defined by
 $$ G(x) :=\int_a^{u(x)} f(t)\,dt $$
for $x$ in $J$, then $G'(x) = (f \circ u)(x)u'(x)$ for all $x\in J$.
Should I use the Leibniz rule to approach this problem?

A: Hint: $f$ is continuous, so $F(x) = \int_a^x f(t)\,dt$ is differentiable with $F' = f$. Now apply the chain rule to compute $G' = (F \circ u)'$.
Edit (in response to comment): The first claim follows from the fundamental theorem of calculus. That $G(x) = F(u(x))$ is true by definition - just plug $u(x)$ into $F$. That $G$ is differentiable follows from the fact that's it's the composition of two differentiable functions and the derivative is computed with the chain rule: $G'(x) = F'(u(x))u'(x) = f(u(x))u'(x)$.


Q: How can I get the element that is clicked on with a click handler added in a forEach? I need to detect element count number
I have 10 poster elements and I have a forEach loop
I need the poster number that I clicked on, for example if I click on the seventh poster posternumber should be 7
    poster.forEach(p => {
            p.addEventListener('click',function(){
                videoTag.src = xResult[movieLanguageUrl][/*posternumber*/];
           });
    });

A: Check out the signatur of your forEach consumer function. The secound argument is the index.
poster.forEach((p, idx) => {
    p.addEventListener('click',function(){
        videoTag.src = xResult[movieLanguageUrl][idx];
    });
});

Check out this link.

A: Get the index value on the second parameter of the forEach function and it should work:
poster.forEach((p, index) => {
    p.addEventListener('click', () => {
        videoTag.src = xResult[movieLanguageUrl][index + 1];
   });
});


Q: How to make Greek-containing tokens in minted, without XeTeX or LuaTeX? I would like to use mixed Latin/Greek tokens (variable names) like helloδ in minted. To stay compatible with arXiv I cannot use XeTeX or LuaTeX.
Outside of minted, working with textgreek is my favourite way of getting good Greek characters. Is there a way to get the textgreek characters into a minted frame without using the escapeinside mechanism that interrupts the token lexing process? Here's a minimal example of what I don't want:
\documentclass{article}
\usepackage{minted}
\usepackage{textgreek}
\begin{document}
\begin{minted}[escapeinside=||]{mask}
hello|\textdelta|
\end{minted}
\end{document}

You can see that minted has broken up the variable name into a Latin part and a Greek part. The fancyvrb line generating the above output is
\PYG{n+nt}{hello}\PYG{esc}{\textdelta}

Simply changing the appearance of \PYG{esc} to match the rest of the token is not a good solution because the token helloδ may appear in different settings and require different appearances throughout the text. I would much rather know how to generate
\PYG{n+nt}{hello\textdelta}

directly. Any other solutions are welcome too, of course.

A: It works fine for me:
\documentclass{article}
\usepackage{minted}
\usepackage{textgreek}

\begin{document}
δ
\begin{minted}[escapeinside=||]{mask}
helloδ
\end{minted}
\end{document}

A: The problem is neither minted nor pygments, but rather the TeXShop installation defaults. The solution is to set the first line (or any of the first 20 lines) in the .tex file to
% !TEX encoding = UTF-8 Unicode

to force the editor to handle the file in UTF-8. The details are in the TeXShop menu point "Help - File Encodings and TeXShop".


Q: How to keep scroll position when pressing back button in angular 13, I'm already using RouteReuseStrategy I have a long list of items inside a big scrollable div. Each time when a user click on an item to see the details of item then click the back button, it starts at the very top of the div. It is not user friendly to our users. Any ways to let the browser scroll to the previous position when pressing the back button?
Thank you very much!
I'm already know the position of scroll but i couldn't set it. Always the position of scroll reset to 0

A: Add scrollPositionRestoration: "enabled" to your routing module as option.
@NgModule({
  imports: [RouterModule.forRoot(routes, {
  scrollPositionRestoration: "enabled", //--> add this
})],
  exports: [RouterModule]
})


Q: INSERT INTO query not working in Express.js I'm having trouble inserting data into a MySQL database. Select queries work fine, so I'm assuming that it's something stupid that I've missed, either in the Express code, or, in my HTML. The page I'm running the query from is located at localhost:8080/add, and I'm trying to INSERT INTO.  Here's my code:
Javascript
app.get('/add', function(req, res) {
    res.sendFile(path.join(__dirname + '/Views/add.htm'));
});

app.post('/add', function(req, res) {
    var fName = req.body.fName;
    var email = req.body.email;
    var id = req.body.id;
    var post = {id: id, user: fName, email: email};
    console.log(post);//This holds the correct data

    connection.query('INSERT INTO user VALUES ?', post, function(err, result) {
        if (!err) {
            console.log('Successfully added information.');
        } else {
            console.log('Was not able to add information to database.');
        }
    });
});

My HTML is simply a submit button and 3 input fields, within in a POST method form. Again, I can connect to the database and read from it with a select query, I just cannot insert into it.

A: Look at the documentation here https://github.com/mysqljs/mysql#escaping-query-values.
connection.query('INSERT INTO posts SET ?', post, function(err, result) {
        if (!err) {
            console.log('Successfully added information.');
        } else {
            console.log(result);
            console.log('Was not able to add information to database.');
        }
});

Valid mysql statement is SET instead of Values.


Q: How to get PhpStorm to understand different SQL dialects in HEREDOC in the same project My PHP 7.3 application connects to MS SQL Server or MariaDB, depending on being run under Windows or Linux.
For my queries, I sometimes write queries in SQL Server syntax and sometimes in MySQL syntax. For code validation etc. I use PhpStorm's language injection via HEREDOC
Of course, only the dialect that is configured in the project, is validated correctly.
Example:
switch ($dt_type) {
    case 'MSSQL':
        $sql_string = <<<SQL
            [MSSQL query here]
        SQL;
    case 'MYSQL':
    case 'MSSQL':
        $sql_string = <<<SQL
            [MYSQL query here]
        SQL;
}

I configured the MSSQL dialect in my project, so PhpStorm (correctly, expectedly) marks my MySQL queries as invalid and quirks the syntax highlighting.
Is there a way to tell PhpStorm, that a specific string should be validated with a different SQL dialect, for example by declaring it in a comment just before that string declaration? I tried the @lang annotation, and language injection comments.. without any success.
I am aware it might not be possible, but maybe someone knows a trick?

A: SQL is used to apply the current SQL Dialect for that file (in case if you do not know: you can configure the IDE to have different dialects on per file/folder basis).

To have two dialects in the same file:

*

*Do not use SQL as an identifier if you will be changing it across the project (as it will use current SQL Dialect for that file).
I mean: you can use it, not an issue; but do not get lost/confused if you change the dialect later for that folder/file or for the whole project.

*Create and use more specific identifiers instead that will instruct the IDE to use a specific dialect there.
It's easy: just clone and adjust a bit a Language Injection rule for the bundled SQL identifier:

*

*Settings (Preferences on macOS) | Editor | Language Injections

*Clone existing rule for <<<SQL and adjust as needed (or create new one from scratch using the right type)

As you may see from this example, string for PostgreSQL complains on syntax (there is no DB attached to the project, hence unknown table table):

In-place language injection via @lang also works. NOTE that the injection must be placed just before the string content, not before the variable etc.
$sql1 = /** @lang MySQL */'SELECT * FROM `table`';
$sql2 = /** @lang PostgreSQL */'SELECT * FROM `table`';


Q: Problema de lógica He creado un JS que manda los archivos de un formulario a un PHP para que lo mande a una carpeta.
En dicho JS, si el archivo seleccionado pesa más de 1MB, lo divide en trozos de lo mismo, 1MB y los manda poco a poco.
Necesito poder colocar BIEN la barra de progreso para que se complete al haber completado TODOS los eventos.
Ejemplo: Si mando un archivo de 7MB, mandará 7 miniarchivos, con lo cual, serían 7 eventos, que cuando se completase cada uno, la barra de progreso aumentaría un x% dependiendo del número de miniarchivos que se manden, en este caso 14.28%, mas o menos.
El problema está en la lógica de la estructura del código, que no doy con ello para poder poner la estructura tal y como he querido definir arriba. Esto es lo que tengo hasta ahora:
var chunk, txt, start, part, BYTES_PER_CHUNK, end;

function selectFile(){
    let file = _("file1");

    if('files' in file){
        for(let i=0;i < file.files.length;i++){
            let x = file.files[i];
            start = 0;
            part = 0;
            BYTES_PER_CHUNK = 1048576;

            //despliegue del temp
            txt = createElement();
            document.body.append(txt);

            //logs
            if ('name' in x) {
                txt.getElementsByClassName('txt_file_name')[0].innerHTML = 'Name: '+x.name;
            }
            if ('size' in x) {
                txt.getElementsByClassName('txt_file_size')[0].innerHTML = 'Size: '+x.size;
            }

            uploadComplete(x);
        }
    }
}

function uploadFile(chunkFile, part, x){
    let xhr = new XMLHttpRequest();
    let bar = txt.getElementsByClassName('progressBar')[0];
    xhr.upload.addEventListener("progress",(event)=>{uploadProgress(event, bar, x)}, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open("POST", "upload.php"+"?"+"file="+x.name+"&num=" + part);
    xhr.setRequestHeader('Cache-Control','no-cache');
    let fd = new FormData();
    fd.append("file1", chunkFile);
    xhr.send(fd);
    return;
}

function uploadComplete(x) {
    let pol =[];
    start = 0;
    end = BYTES_PER_CHUNK;
    part = 0;
    while( start < x.size ) {
        chunk = x.slice(start, end);
        console.log(start);
        uploadFile(chunk, part, x);
        start = end;
        end = start + BYTES_PER_CHUNK;
        part++;
        pol.push({part:part,start:start,end:end});
    }
    console.log(pol);
}

function uploadProgress(event, bar, x) {
    //let total_size = x.size;
    let slice = parseInt(x.size/(1024*1024));

    _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
    let percent = (event.loaded / event.total) * 100;
    bar.value = Math.round(percent);
    _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function uploadFailed(event) {
    _("status").innerHTML = "Upload failed";
}

function uploadCanceled(event) {
    _("status").innerHTML = "Upload canceled";
}

function createElement(){
    let dv = document.createElement('div');
        dv.setAttribute('class', 'demo');
    let p1 = document.createElement('p');
        p1.setAttribute('class', 'txt_file_name');
    let p2 = document.createElement('p');
        p2.setAttribute('class', 'txt_file_size');
    let pr = document.createElement('progress');
        pr.setAttribute('class', 'progressBar');
        pr.setAttribute('value', '0');
        pr.setAttribute('max', '100');

        dv.append(p1);
        dv.append(p2);
        dv.append(pr);

    return dv;
  }

function _(el) {
    return document.getElementById(el);
  }

Cada vez que subo un archivo al formulario, activa un onchange que ejecuta la función selectFile. En dicha función se ve cuántos archivos hay, los itera, crea un elemento nuevo en el DOM para ver su nombre, peso y carga, y llama a la función uploadComplete(x);
Dentro de uploadComplete, podeis ignorar el array pol ya que lo uso como control. Ahí divido cada archivo en partes de 1MB cada uno y los mando respectivamente a uploadFile().
Ahí hago la request y donde comienza, CREO, mi problema con la lógica, ya que hago los xhr.onprogress a partir del evento de cada miniarchivo.
Conclusión, que no se por dónde me pega el aire esta vez, estoy perdido.


Q: Cucumber ordering of Given, When, Then (Given, When, Then, When, Then) As an End-to-end Automation Tester I have always assumed that Given, When, Then statements (incorporated in the Gherkin Language when using Cucumber) should only ever appear in the order of 1. Given, 2. When, 3. Then.
i.e. A test should not follow, for example, Given, When, Then, When, Then.  And instead should follow Given, When, Then only.
The reason for this assumption was along the lines of a single test only testing one area of the application.
However, I noticed on some gherkin examples on the web, that they use the following ordering sometimes: Given, When, Then, When, Then.
Does anyone know if this moving back to Whens after writing a Then is acceptable best practice?  I appreciate the test will still work, just wondering if this is good or bad practice.

A: Although scenarios can be written in that way, it is not best practice. I for one, have made that mistake and it can cause problems in reports and maintenance.
One reason would be that When declares an action and Then verifies the result of that action. Having When - Then twice goes against the individual behavior of a scenario.
Can also get confusing for someone who reads the scenario :)
Here's a little post regarding this

A: There is alot of really bad Gherkin on the web. Also there is a range of opinions about what good Gherkin is.
My opinion is that When Then When Then is an anti-pattern. Its likely that one of the following is required

*

*You need a better Given to incorporate the first When Then

or

*You need to split the scenario in two.

In general most When's in scenario's become Given's in later scenario's, as you build on existing behaviour to define and create new behaviour.

A: Syntactically Interchangeable; Linguistically Different
The Gherkin syntax currently includes six keywords for describing feature steps:

*

*Given

*When

*Then

*And

*But

**
The keywords are there for human consumption and the ease of conveying business logic. However, the Gherkin language itself treats the keywords as interchangeable symbols, so you could just as grammatically (from a Gherkin point of view) write tortured English like:

But for a dollar held
  Then another dollar more
  Given ownership of two dollars am I.

This is perfectly valid Gherkin, but a terrible representation of counting money. So, if all the words are interchangeable, why have so many of them?
The wiki is quite clear that they provide a set of conventions to facilitate communication in a more natural style, and the wiki even gives a few examples of how the words are meant to be differentiated. The wiki also specifically says:

Cucumber doesn’t technically distinguish between these...[kinds] of steps. However, we strongly recommend that you do! These words have been carefully selected for their purpose, and you should know what the purpose is to get into the BDD mindset.

In other words, use the Gherkin terms to communicate in (relatively) natural language about your feature, and bury the arcana in step definitions. Use whatever keyword fits most naturally in the linguistic flow, and don't sweat a well-written scenario that doesn't rigidly adhere to a convention that may not apply in all cases.


Q: Template or function arguments as implementation details in doxygen? In doxygen is there any common way to specify that some C++ template parameters of function parameters are implementation details and should not be specified by the user ?
For example, a template parameter used as recursion level counter in metaprogramming technique or a SFINAE parameter in a function ?
For example :
/// \brief Do something
/// \tparam MyFlag A flag...
/// \tparam Limit Recursion limit
/// \tparam Current Recursion level counter. SHOULD NOT BE EXPLICITELY SPECIFIED !!!
template<bool MyFlag, unsigned int Limit, unsigned int Current = 0> myFunction();

Is there any doxygen normalized option equivalent to "SHOULD NOT BE EXPLICITELY SPECIFIED !!!" ?

A: It seems to me that the whole template is an implementation detail of a different interface:
template<bool MyFlag, unsigned int Limit, unsigned int Current = 0> myFunctionImpl();

template<bool MyFlag, unsigned int Limit> myFunction() {
   myFunctionImpl<MyFlag, Limit, 0>();
}

Now it becomes easier to document: myFunction() (and all it's arguments) are part of the interface, which does not include the iteration counter. myFunctionImpl() is the implementation of that interface and does not need to be documented at all (or only minimally with a comment stating that it is an implementation detail and user code should not depend on it or use it directly). If you want, you can enclose the implementation in an #ifdef block so that the doxygen preprocessor removes it and it does not appear in the generated documentation.

A: One option to convey that a parameter should not be specified would be to hide it in the documentation. For example you could conditionally compile out the internal parameters:
/// \brief Do something
/// \tparam MyFlag A flag...
/// \tparam Limit Recursion limit
template<bool MyFlag, unsigned int Limit
#if !defined(DOXYGEN)
        , unsigned int Current = 0
#endif
> myFunction();

This would prevent them from appearing in the documentation, but they would still be available to the implementation.


Q: How to remove black canvas from image in TensorFlow I'm currenly trying working with tensorflow dataset 'tf_flowers', and noticed that a lot of images consist mostly of black canvas, like this:
flower1
flower2
Is there any easy way to remove/or filter it out? Preferably it should work on batches, and compile into a graph with @tf.function, as I plan to use it also for bigger datasets with dataset.map(...)

A: The black pixels are just because of padding. This is a simple operation that allows you to have network inputs having the same size (i.e. you have batches containing images with the of size: 223x221 because smaller images are padded with black pixels).
An alternative to padding that removes the need of adding black pixels to the image, is that of preprocessing the images by:

*

*removing padding via cropping operation

*resizing the cropped images to the same size (e.g. 223x221)

You can do all of these operations in simple python, thanks to tensorflow map function. First, define your python function
def py_preprocess_image(numpy_image):
    input_size = numpy_image.shape  # this is (223, 221)
    image_proc = crop_by_removing_padding(numpy_image)
    image_proc = resize(image_proc, size=input_size)
    return image_proc

Then, given your tensorflow dataset train_data, map the above python function on each input:
# train_data is your tensorflow dataset
train_data = train_data.map(
                 lambda x: tf.py_func(preprocess_image,
                                      inp = [x], Tout=[tf.float32]),
                 num_parallel_calls=num_threads
             )

Now, you only need to define crop_by_removing_padding and resize, which operate on ordinary numpy arrays and can thus be written in pure python code. For example:
def crop_by_removing_padding(img):
    xmax, ymax = np.max(np.argwhere(img), axis=0)
    img_crop = img[:xmax + 1, :ymax + 1]
    return img_crop

def resize(img, new_size):
    img_rs = cv2.resize(img, (new_size[1], new_size[0]), interpolation=cv2.INTER_CUBIC)
    return img_rs


Q: DatabaseError: 1366 (HY000): Incorrect string value: '\xF0\x9F\x92\x96' I'm using MySQL 5.7.20. My schema, tables and columns are all supporting utf8mb4. I used the following:
ALTER SCHEMA `MyDB`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_general_ci ;
ALTER TABLE MyDB.Videos CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

I don't understand why I'm still getting the following error:
DatabaseError: 1366 (HY000): Incorrect string value: '\xF0\x9F\x92\x96' for column 'Content' at row 1

I can't figure out the reason, please help.

A: When I specified CHARSET='UTF8MB4'in my connection parameters, it worked.

A: Set is working
cursor.execute("SET NAMES 'UTF8MB4'")
cursor.execute("SET CHARACTER SET UTF8MB4")


Q: WP_Error handles errors, but how can I show success with a message? My script accesses an api to populate posts. I can add any errors to the WP_Error class, but can I add success messages to a global variable?

A: you could test for the absence of an error and then display a success message
if(!is_wp_error( $thing )) echo "yay!!";


Q: Hazelcast file persistence (MapStore implementation) I am using Hazelcast for clustered data distribution. I read in the documentation about data persistence, using the interfaces MapStore and MapLoader. I need to implement these interfaces and write the class name in the hazelcast.xml file.
Is there any example of implementation of these interfaces for file persistence with hazelcast? Does anyone know about any source code or jar file that I can download and work with?
Thanks

A: You can implement your own just using ObjectOutputStream  and ObjectInputStream.
You can create a directory with map's name.
store(key, value) operation creates a file with name key.dat, with content of serialized value.
load(key) method reads "key.dat" file into an object and returns.
Here usage examples of  ObjectOutputStream  and ObjectInputStream
http://www.mkyong.com/java/how-to-write-an-object-to-file-in-java/
http://www.mkyong.com/java/how-to-read-an-object-from-file-in-java/
Then you should add this implementation class to your class path and set it in your hazelcast.xml


Q: navLinkDayClick of FullCalendar Did anyone use navLinkDayClick of FullCalendar and call a custom event (by fetching data from database) based on the date selection?
I am using eventClick to populate the calendar data however I am unable to do so for individual dates after setting the navLinks to true.
Everything above navLinkDayClick works fine.

function FetchEventAndRenderCalendar() {method contains to fetch all event from database}

function FetchTotalAmount() { method calls a SP to get the total amount for that day of the calendar}. This also contains the method to generate the calendar which is given below.

function GenerateCalender(events) - events are the ones that are fetched in the first method.

function GenerateCalender(events) {
..................
..................
events: events,
eventClick: function (calEvent) {
var selectedCalendarEvent = calEvent;
$('#calendarModal #eventTitle').text(calEvent.title);
..................
..................
navLinks: true,
navLinkDayClick: function() {
how to use this to show the total amount for that day of the calendar when the date is selected?
}

A: navLinkDayClick in FullCalendar v3.8 -

navLinks: true,
navLinkDayClick: function (date) {
selectedDate = date.format("DD-MMM-YYYY");
selectedAmountEvent = amounts.find(item => item.paymentDate.format("DD-MMM-YYYY") === selectedDate);
var $AmountData = $('
');
$AmountData.append($('
').html('Payment Date: ' + selectedAmountEvent.paymentDate.format("DD-MMM-YYYY")));
if (selectedAmountEvent.totalAmount < 0) {
    $AmountData.append($('
').html('Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + ''));
}
else {
    $AmountData.append($('
').html('Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + ''));
}

$('#eventModal #AmountDetails').empty().html($AmountData);

$('#eventModal').modal();
}

amounts is an array holding the data.


Q: Swann DVR8-3000 - Mobile port setup Recently bought a Swann DVR8-3000 security camera kit for the house. I have it set up, working fine over the network, great.
I am trying to set it up so I can view camera's over my mobile phone, using Swann's SwannView app (from the Android Market).
The problem is, most instructions refer to a 'Mobile Port', which is meant to be in the DVRs Network setup options, or as a subheading under Devices. However, my DVR doesn't have this option (though I've been assured this product supports mobile access). The only ports I can setup in the Network Settings are HTTP Port (85 default) and Network Port (9000 default).
I am using Swanns DynDSN (swanndvr.net) to access the DVR (This setup has been tested, and apparently works). I've set up a user name and password for access, which works fine over network. uPnP is enabled on my router. The only thing I am not sure on is the 'mobile port'.
Does anyone have any information on what I can do?

A: I used "IP Camera viewer" from the Android Market by Robert Chow which sets up perfectly and easily. Select your DVR model from the drop down menus, it automatically selects port 9000. I allowed UpNP to open ports 85 and 9000. the DVR uses a static address so it doesn't change. I enter the actual address for our office and it opens fast and tracks ok, expensive/crappy TWC speeds aside. I'm also not using any DNS service.
The Swann viewer is not as good (I've read) as the IP Camera viewer which is excellent. I have used this program for a Foscam camera I have. I'm using Swann's program on my computers that I monitor the DVR remotely with, but am looking for an alternative. It keeps switching my desktop schemes to "Basic" and the list of prerecorded times is ridiculously small. Swann's software leaves me much to be desired.


Q: "Homosexual" or "Gay and Lesbian"? I have faced a problem with my writing which I could really do with some clarification on. My question applies to both British and American English (which is fairly standard on the internet).
Needless to say the context is a website whereby I allow the user to enter a sexuality and it is the English of choosing the sexuality option which is confusing me.
I see many people no longer mention "homosexual" and when you do a Google search for the right term ("homosexual or lesbian") you actually find that many seem to avoid the use of "homosexual" and even have undue prejudice towards it ( http://www.care2.com/causes/gay-and-lesbian-or-homosexual-does-it-matter.html ). Likewise I have noticed that many charities do not include "homosexual" in their material but instead "Gay and Lesbian" (LGBT). Added on top to this, I notice many websites no longer use "homosexual" either.
So is it better in modern English, taking cultural aspects into consideration, that "gay and lesbian" should be used rather than "homosexual"?

A: Does a dog have the Buddha nature?
Sexual orientation
Your question reads, "...the context is a website whereby I allow the user to enter a sexuality." Part of your confusion starts here: using precise language to define your problem will help you find a solution. "Sexuality" is not precise enough. On your website, you are allowing users to enter their sexual orientation: that is the precise term you need.
By being more precise, we see that the information that you are allowing the users to enter is emphatically not the labels that the users apply to themselves (such as homosexual, gay, or lesbian). Rather, you are allowing the users to enter the gender of people to whom the users are sexually oriented.
What does LGBT mean?
Your question makes a passing reference to LGBT but only mentions "Gay and Lesbian." "LGBT is an initialism that stands for lesbian, gay, bisexual, and transgender." (Wikipedia, emphasis added.) People who label themselves as gay or lesbian almost always recognize at least a few other labels with equal validity to gay or lesbian. The extremely-common initialism, LGBT, demonstrates that in addition to gay and lesbian, many people describe their sexual orientation as bisexual or some other label.
Therefore, your basic question is a false dichotomy: you do not need to choose between “Homosexual” or “Gay and Lesbian” because there are clearly many other options than those three terms. Furthermore, "Homosexual" and presumably "Heterosexual" as the two choices for your users do not include people who label themselves as bisexual, so "Homosexual" is not broad enough. Your proposed alternative of "Gay and Lesbian" presumably presented with a choice such as "Straight" is also under-inclusive.
For your website, neither of the options you have presented are adequate.
What is gender?
The issue, however, is even more complicated than attempting to create a fully-inclusive list of labels for sexual orientation. Transgender (the "T" in LGBT) is not a sexual orientation: it describes a person's gender identity. The overwhelming majority of people only think of gender as male or female. This black-and-white perspective of gender is often called something like a "binary gender" model.
Some people, however, do not cleanly fit into these two gender definitions. Easy, non-controversial examples that defy binary-gender labels: some people have male and female sexual organs; some people are genetically female (two X-chromosomes), but have the secondary sexual characteristics of a male (sexual organs, for example); and some people have two X-chromosomes and a Y-chromosome, which, genetically, is not exactly male nor female, and the person could develop the secondary sexual characteristics of a male, a female, or an intersex person. When these people are presented with two options for gender, male or female, which should they choose and why?
Which brings us back to people who identify as transgender. Is their gender male or female or something else?
Your question is explicitly about sexual orientation, so we do not need to answer most of the difficult questions within gender identity, but it is related to sexual orientation, so when choosing the language for your website, you must be aware of the basic issues of gender identity.
How to allow your users to enter their sexual orientation
If your goal is to allow your users to describe their sexual orientation exactly as each user would like to describe their sexual orientation, then the best option is to write "Sexual orientation:" and then have a text box that allows users to type anything they want to type.
Of course, if you want to sort data based on sexual orientation, you need standardized data. Allowing everyone to enter free-text will give you problems such as three people who all use the same label to describe their sexual orientation, but they typed it differently: bisexual, bi-sexual, and bi sexual. Computers are stupid, and the computer will see those three descriptions as different rather than as the same.
Therefore, you likely will want to give your users a set of options from which to choose. If we start with the belief that there are only two genders, male and female, then your best design would likely be to write, "Sexual orientation:" then have two checkboxes, male and female. Each user could choose male, female, or both.
For the overwhelming majority of websites, the above method is satisfactory, not perfect, but satisfactory. Because it assumes binary gender, it is under-inclusive, but because most people who make websites have not wrestled with the difficult and contentious issues of gender identity, for most people, trying to create standardized options other than male and female would require tremendous effort for relatively little return.
As described above, the binary gender model, however, is not particularly good. In a perfect world, the English language would have a more full vocabulary to describe gender and most people would be familiar with the options other than male and female. We do not live in that world.
The solution to the errors inherent in binary-gender descriptions and its impact on describing sexual orientation, depend on the reasons a website wants to collect sexual orientation information about its users. An easy option that is 100% inclusive of all sexual orientations is to have three check boxes: male, female, and other. "Other" is terribly imprecise, but it is more inclusive.
Without knowing why you want sexual orientation and how you will use the data, it is impossible for anyone here to give you a specific list of choices for your users.
Conclusion

*

*Neither of your proposed options are appropriate.

*It is essential that you clearly understand that you are asking your
users for their sexual orientation and you must clearly understand
the range of possibilities within sexual orientation.

*Gender identity cannot be separated from sexual orientation, so you
will need to accept that the binary-gender model is not accurate and develop
some understanding of the complexity of gender identity.

*Do not ask your users to label their sexual orientation. Labels
include homosexual, gay, or lesbian.

*Do allow your users to enter the gender (or gender identity) of the
persons to whom the users are sexually oriented.

A: Your original q was whether gay/lesbian is culturally preferable to homosexual. The brief answer is yet (but...) British organisations who campaign for equality are now using a qwertyuiop to cover all the bases: LGTBQI (you can look it up). While this is considered cutting-edge by its users, it actually excludes those of us who for reasons of age or political outlook reject one or more of these labels to describe ourselves, or who don't want to be associated with some of the sub-types in the list! A small minority do refer to themselves as homosexual, preferring this 'objective' description to words like gay, which imply a cultural standpoint at the same time. Finally, what do we do about the heterosexuals? Many of them would reject the word 'straight' as a kind of scornful dismissal. And don't forget the asexuals - some people have no libido and wonder what all the fuss is about.

A: in such a dilemma over the correct usage-it would be correct to offer three options for gender identity...male/female/others.as for sexual orientation:again three options with the third option having a pull out list,including all standard options as well as the option of not specifying any one of the choices listed


Q: Ruby thread safe thread creation I came across this bit of code today:
@thread ||= Thread.new do
  # this thread should only spin up once
end

It is being called by multiple threads. I was worried that if multiple threads are calling this code that you could have multiple threads created since @thread access is not synchronized. However, I was told that this could not happen because of the Global Interpreter Lock. I did a little bit of reading about threads in Ruby and it seems like individual threads that are running Ruby code can get preempted by other threads. If this is the case, couldn't you have an interleaving like this:
Thread A             Thread B
========             ========
Read from @thread    .
Thread.New           .
[Thread A preempted] .
.                    Read from @thread
.                    Thread.New
.                    Write to @thread
Write to @thread

Additionally, since access to @thread is not synchronized are writes to @thread guaranteed to be visible to all other threads? The memory models of other languages I've used in the past do not guarantee visibility of writes to memory unless you synchronize access to that memory using atomics, mutexes, etc.
I'm still learning Ruby and realize I have a long way to go to understanding concurrency in Ruby. Any help on this would be super appreciated!

A: You need a mutex. Essentially the only thing the GIL protects you from is accessing uninitialized memory. If something in Ruby could be well-defined without being atomic, you should not assume it is atomic.
A simple example to show that your example ordering is possible. I get the "double set" message every time I run it:
$global = nil
$thread = nil

threads = []

threads = Array.new(1000) do
  Thread.new do
    sleep 1
    $thread ||= Thread.new do
      if $global
        warn "double set!"
      else
        $global = true
      end
    end
  end
end

threads.each(&:join)


Q: Spotify API device list empty after short inactivity period I'm trying to use the Spotify API for a personal project.
My problem is that the "devices" endpoint that normally returns a list of my available devices (my phone) returns an empty array if I swipe out of the Spotify app for a short while before requesting the device list.
For example:
I open the Spotify app in my phone. I send a Postman request to the "devices" endpoint of the Spotify API and confirm that my phone is listed as an available device for playback. I then swipe out of the Spotify app, into another app and click around there for 30 seconds or so. I then send the same Postman request to the "devices" endpoint and receive an empty array. My phone is immediately forgotten after a short period of inactivity in the Spotify app, and thus any requests to play a song etc. fail since no available device is found.
Has anyone managed to force their device to stay on the API's radar, or found a way to "wake" their device before sending a request that targets it to the API?
I am currently using iOS.
Thanks.


Q: Android Polyline - Adding point by point I'm currently having a map, and each 10 meters I use LocationListener to refresh my location and get the new Latitude and Longitude. Now I wish that the route the user is taking will be displayed with a red line. So everytime the OnLocationChange() from LocationListener class is called, I want to update the map with a line between the last location and the new location.
So far I've added the following:
private void initializeDraw() {
    lineOptions = new PolylineOptions().width(5).color(Color.RED);
    lineRoute = workoutMap.addPolyline(lineOptions);
}

during the OnLocationChanged I call this:
drawTrail();

now what should I insert into this function so that each time it adds the newly attained location as a point and draws a line from the last to the new point.
Thanks

A: First translate Location into LatLng:
LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude());

Then add a point to existing list of points:
List<LatLng> points = lineRoute.getPoints();
points.add(newPoint);
lineRoute.setPoints(points);


Q: How to get the current (working) directory in Scala? How can I get the current directory (working directory) of the executing program in Scala?

A: Use this:
import scala.reflect.io.File
File(".").toAbsolute

A: I use new java.io.File(".").getAbsolutePath, but all the other answers work too. You don't really gain anything by using Scala-specific API here over regular Java APIs

A: import scala.sys.process._
val cwd = "pwd".!!  //*nix OS

A: Use this
System.getProperty("user.dir")
Edit:
A list of other standard properties can be found here. https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

A: Use java.nio:
import java.nio.file.Paths
println(Paths.get(".").toAbsolutePath)

Remark on scala.reflect.io.File: I don't see any reason to look into scala.reflect packages for such mundane tasks. Getting the current working directory has usually nothing to do with Scala's reflection capabilities. Here are more reasons not to use scala.reflect.io.File: link.

A: os-lib makes it easy to get the current working directory and perform other filesystem operations.  Here's how to get the current directory:
os.pwd

It's easy to build other path objects from os.pwd, for example:
os.pwd/"src"/"test"/"resources"/"people.csv"

The syntax is intuitive and easy to remember, unlike the other options.  See here for more details on how to use the os-lib project.


Q: PulseAudio Remote Control on Android What I'm looking for is a way to control pulseaudio from my phone.
I love Pulseaudio Volume Control (the desktop app which lets you control each application's volume level). The best thing would be an android app which connects to pavu. I guess that's not going to happen anytime soon, so this is why I'm asking for alternatives here.
What I've been thinking of but haven't done because it's so clumsy:

*

*connect to my computer via vnc as a second screen and have pavucontrol run there
--> not really elegant at all

*write my own android app and have it log in to my pc using ssh.
--> well, this takes time. Last resort.

Remote controlling only my music player for example is NOT an option. I have many applications running which play sound and I want to mix them all together, not with an app for each one of these. I'm talking about

*

*being on teamspeak

*playing some music

*having system sounds

*and the occasional notification from somewhere

at the same time. Doing it manually is just not an option.
Thanks for any ideas!

A: Been looking for the same sort of thing for the past few days. With only minor difficulties I was able to build reverb and get it working. I was able to control my laptop's pulseaudio after loading module-native-protocol-tcp. Next step is forwarding port 4713 from my router to my desktop so I can control that too.
The project hasn't been updated in about a year, and doesn't yet allow cookie authentication, so I might have to resurrect it.


Q: Colspan in Backendlayout not working (TYPO3 8.7 LTS) The 3 columns in my backendlayout should be equal size, independent of their content. In my case their width get determined by their content though. Glad about any hints!
Environment:

*

*TYPO3 8.7.0

*PHP 7.0.13

*MySQL 5.6.34
Installed Extensions:

*

*gridelements dev-master c5120b0e

*realurl 2.2.0

*slickcarousel 8.x-dev

*vhs 4.1.0
The TS was generated using the wizard. It is a 3 columns layout with 2 rows. The second row has 3 cols (colspan = 1) and the first one has 1 col (colspan = 3).
mod.web_layout.BackendLayouts {
MainTemplate {
    title = MainTemplate
    name = MainTemplate
    icon = EXT:amtemplate/ext_icon.png
    config {
        backend_layout {
            colCount = 6
            rowCount = 2
            rows {
                1 {
                    columns {
                        1 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.sliderarea
                            colPos = 1
                            colspan = 6
                        }
                    }
                }
                2 {
                    columns {
                        1 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.left
                            colPos = 2
                            colspan = 2
                        }
                        2 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.main_content
                            colPos = 0
                            colspan = 2
                        }
                        3 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.right
                            colPos = 3
                            colspan = 2
                        }
                    }
                }
            }
        }
    }
}
}

A: Worked here in 8.7.1 without any problems. Maybe you wann update to the latest release?

A: There are two different concepts you are mixing up here, namely colspan and width.
The colspan attribute is used to tell a cell of a table how many of the other cells of another row it should overlap. So this has nothing to do with fixed widths even though it might feel like that, when you got the same content in each cell or no content at all. As soon as you fill the table cells with different content, the width of each cell might differ even though some of these cells might use the same colspan value.
So colspan actually just defines the relation between the cells but not their width. Still the core somehow circumvents that behaviour by applying min and max width values to several parts of the page module via CSS, so the cells will stay within a certain width range.
Now that you have installed gridelements, there can not be such a range anymore, because there might be nested grid structures that have to consume way more space. So gridelements uses a CSS removing that range and thereby restores the default behaviour of HTML table cells.


Q: Android OpenGL ES app crashes logging back in I'm using OpenGL ES 2.0 on Android to make a basic game. I discovered that if I hit the home key on my device (emulator or real device) when the GLSurfaceView is present and then log back into the app from the Android home screen the app will crash. In contrast, if I I hit the back key while the GLSurfaceView is present which then takes me back to my MainActivity / MainView then everything is fine. I assume this has to do with how the GL Thread is managed, and when I close the app immediately the state is saved as opposed to being popped off the activity stack like when I hit the back button to go to my MainActivity.
My question is how should I best deal with destroying the GLSurfaceView state information? If the user hits the home key I want the information to reset and not be saved. Should I override onStop in the class that implements GLSurfaceView.Renderer and delete the GLSL program?
I can give a rough picture of how my activites are laid out below.
MainActivity class:
public MainActivity extends Activity
     GameView view;
     public onCreate ( ... ) { }
GameView class:
public GameView extends GLSurfaceView
  Renderer renderer;
  public onCreate (...) { // set EGL information and renderer };
Renderer class:
public Renderer implements GLSurfaceView.Renderer
    // implements the surface change, created, and draw methods

A: Make sure that your android version supports OpenGL ES 2.0 rendering on it's background state. Because whenever you press the home key app enters background state and gives background thread for your application, that may cause crashes. Mostly in iOS and android it is best to identify the app state and pause the rendering in background state.  Refer further in  this link Run Android OpenGL in Background as Rendering Resource for App?

A: I found out that I needed to override the 'onSurfaceDestroyed( SurfaceHandle handle) method in the class that extends GLSurfaceView and clean up my resources.
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
    super.surfaceDestroyed(holder);
    ResourceManager.getInstance().cleanUp();
}


Q: How to Update a MYSQL Column Based On Varying Conditions I need to update a MYSQL Table
Here is a very simple look at Table_A
ID  VALUE  RESULT
1   4      0
2   2      0
3   7      0

I want to update the RESULT Column based on conditions
So my query statement needs to look something like
UPDATE Tabel_A
SET RESULT = (if some condition) 1
             OR (if another condition) 2
             OR (if a different condition) 3

Or should I use something like
UPDATE Tabel_A
SET RESULT = (CASE 1) 1
             (CASE 2) 2
             (CASE 3) 3

I am not sure how to structure the query
Thanks

A: I'll prefer to use CASE here.
UPDATE TAble1
SET Result = CASE value
                WHEN 1 THEN x
                WHEN 2 THEN y
                ....
                ELSE z
            END

or
UPDATE TAble1
SET Result = CASE
                WHEN value = 1 THEN x
                WHEN value = 2 THEN y
                ....
                ELSE z
            END


Q: [Android - Kitkat ]Get/pick an image from Android's built-in Gallery app programmatically Try to pick only one particular image from the SD card.I am able to pick images from gallery and Photos app in kikat.But not getting file path when i pick image from recents am getting file path as null.
I tried https://stackoverflow.com/a/2636538/1140321.

A: This works for Kitkat
public class BrowsePictureActivity extends Activity{

private static final int SELECT_PICTURE = 1;

private String selectedImagePath;
private ImageView imageView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.browsepicture);
    imageView = (ImageView)findViewById(R.id.imageView1);

    ((Button) findViewById(R.id.button1))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,
                            "Select Picture"), SELECT_PICTURE);
                }
            });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            if (Build.VERSION.SDK_INT < 19) {
                selectedImagePath = getPath(selectedImageUri);
                Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
                imageView.setImageBitmap(bitmap);

            }
            else {
                ParcelFileDescriptor parcelFileDescriptor;
                try {
                    parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
                    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                    parcelFileDescriptor.close();
                    imageView.setImageBitmap(image);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * helper to retrieve the path of an image URI
 */
public String getPath(Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return uri.getPath();
}

}

You need to add permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


Q: only rotate button and not it's text on button click I rotate a button on click:
<button class="btn" type="button">Go</button>

css:
.btn:focus {
  transform: rotate(180deg);
}

now the problem is txt also rotates on btn click. How can I don't rotate the txt or rotate it 360 on button click?

A: Wrap the button text in a span, and rotate that on :focus of the button by another 180 degree:

.btn:focus {
  transform: rotate(180deg);
}

.btn:focus span {
  display: inline-block;
  transform: rotate(180deg);
}
<button class="btn" type="button">Go</button>

A: Wrap the text with a span and rotate it to the other direction:

.btn:focus {
  transform: rotate(180deg);
}

.btn:focus > span {
  display: block;
  transform: rotate(-180deg);
}
<button class="btn" type="button">
  Go
</button>


Q: SiteMapPath not working with route attribute in nodes I have this xml sitemap:
<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0"  xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0 MvcSiteMapSchema.xsd">
  <mvcSiteMapNode title="Home" controller="Home" action="Index" key="home">
    <mvcSiteMapNode title="Access Control" route="AccessControl_default" controller="Home" action="Index" key="access-control">
      <mvcSiteMapNode title="My dashboard" route="AccessControl_default" controller="Dashboard" action="Index" key="dashboard"/>
       <mvcSiteMapNode title="Personnel" route="AccessControl_default" clickable="false" key="personnel">
        <mvcSiteMapNode title="Groups" route="AccessControl_default" controller="Personnel" action="Groups" key="groups"/>
        <mvcSiteMapNode title="Members" route="AccessControl_default" controller="Personnel" action="People" key="people"/>
      </mvcSiteMapNode>
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>

This is the targeted route defined in area route configuration:
context.MapRoute(
    "AccessControl_default",
    "accesscontrol/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new[] { "UI.WebPortal.Areas.AccessControl.Controllers" }
);

Then navigation menu tree is shown with @Html.MvcSiteMap().SiteMap() but breadcrumb is not working when using @Html.MvcSiteMap().SiteMapPath(). Is it because I'm using routing explicitly? and what could be the solution?

A: While you use areas, just add area="...." to nodes under them.
...
<mvcSiteMapNode title="Groups" route="AccessControl_default" area="AccessControl" controller="Personnel" action="Groups" key="groups"/>
...


Q: iPhone -- [UITextField sizeToFit] does not always account for cursor When I call sizeToFit on a UITextfield that is being edited, the size reacts in an inconsistent way to the cursor.  Sometimes it accounts for it; sometimes it doesn't.  If it doesn't, part of the first letter is clipped.
Has anyone found a way around this?

A: I just ran into this problem (it's fixed in iOS 5). My solution was to add a 4-point padding to the width:
[textField_ sizeToFit];
textField_.frame = CGRectMake(textField_.frame.origin.x,
                              textField_.frame.origin.y,
                              CGRectGetWidth(textField_.frame) + 4,
                              CGRectGetHeight(textField_.frame));

A bit tedious but got the job done for me.


Q: Mismatch between the processor architecture I have an issue with these two famous warnings which are raised during compilation of our solution. There are many forums about these already and I read those, but they still don't solve my issue completely...
1. There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "XXX", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.
2. Referenced assembly 'XXX' targets a different processor than the application.
The reason why these appear in our case is clear. Our solution is compiled as AnyCPU and we want to keep it this way, as we do not want to compile it twice (once as x86 and second as x64). However, we use external DLL which is either x86 or x64 (it is not delivered as AnyCPU).
We develop the application on 64bit windows, so we use the x64 DLL version as reference in the visual studio during development. When we deliver the application to end-users, the installer is customized to copy the proper DLL based on the platform of the target system, e.g. when it is installed on 64bit windows, it copies the x64 DLL version and when it is installed on 32bit windows, it copies the x86 DLL version. Therefore, we know that everything is finally ok, and we can ignore those messages. And therefore, I just want to make them disappear:-)
The first warning can be supressed by the following tag in the project file:
  <PropertyGroup>
    <ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
  </PropertyGroup>

But I did not find anywhere how to get rid of the other message? Is this possible as well?
I know that this is just small issue and I can live with that. However, there is something like "Warning Free Build Initiative" going on in my company, so I'd like to get rid of all warnings we have.
Thank you in advance for any hints,
Tomas


Q: Delete AWS Cloud formation stack with resources created by it Based on this page I can do:
aws cloudformation delete-stack \
    --stack-name my-stack

It says I can attach the command:
[--retain-resources <value>]
Does that mean that if I don't specify that line, all the resources created by the stack will be removed? I'm trying to delete everything generated by the stack, which is a lot.
How can I achieve this?
Thanks

A: Yes, those resources will be kept if you specify the [--retain-resources <value>], if you dont Cloudformation will delete all the resources in the stack name (including the nested stacks as well) you are providing given you have permissions to do. If any of the resources inside the cloudformation stack has retain policy set they won't be deleted.

During deletion, AWS CloudFormation deletes the stack but does not delete the retained resources.

From the same page aws cloudformation delete-stack
You might wanna read this too How do I retain some of my resources when I delete an AWS CloudFormation stack?
You can specify the retain policy as well in cloudformation template.


Q: Where did this snowclone, of the Wiltshire snowclones, actually come from? I've been watching Citation Needed again, and I came across this bit from Episode 1x03:

TOM: And today we are talking about Stephania Folini.
GARY: Of course! Stephania Folini, of the Wiltshire Folinis...

This isn't the last time this snowclone, of the Wiltshire snowclones, was used in the Technical Difficulties' career - Episode 1x09 has the Wiltshire Yamalo-Nenets - and I'm sure it wasn't the first time either, although I don't feel like trawling through their Reverse Trivia podcast right now to make sure.
Now I know what and where Wiltshire is (it's a county in England), but I want to know why Wiltshire? Is it a Monty Python bit? Some other British comedian? Did the Technical Difficulties make it up whole cloth?
For the record, I've also heard it without reference to Wiltshire. In Episode 5x05 of Leverage (the one with the cheerleaders), Sophie pretends to be "Amber von Cleve, of the Cleveland von Cleves" and "Debra Scott, of the Scotsdale Scotts" to  two different Congresspersons. Sophie Deveraux (and her actor) being English probably had something to do with that, now that I think of it.

A: It is certainly not made up by the podcast. Let me start by explaining the saying when it's not being used ironically or sarcastically.
Back in the day (100+years ago) in Britain when people didn't move their home around much, and there was a strict class system, most areas of the country had a few prominent upper-class families. If you met someone from that area with that name you could reasonably bet they were related to the family. For example if you run into someone called Edith Crawley in Yorkshire they are probably related to the Crawley family. If you are yourself upper class you probably know someone from that family and this gives you an immediate connection.
However family names are not unique, so if you were to run into someone called Edith Crawley outside of Yorkshire they might or might not be related to that family. To establish if this is the case, when they introduced themselves you would traditionally ask "of the Yorkshire Crawleys?", meaning "are you related to the prominent Crawley family of Yorkshire?". This also has the benefit of establishing whether Edith is part of a prominent upper-class family, or another (probably less prestigious) family that happens to have the same name, which would have a bearing on how you treated her. Of course she might be from another prestigious Crawley family somewhere else, in which case Edith might reply "No, of the Wiltshire Crawleys".
I do not know enough upper-class people to know if this was actually done in real life or is merely a trope of fiction, although it was intended seriously in most of the fiction where I have encountered it. These days it is either used ironically or to indicate the speakers snobbishness (because by asking the question they betray their own fixation on whether other the person is related to an important family or not).
In the example you cite it is of course being used sarcastically. Folini is not a traditional British name, and so it is unlikely that there is a prominent upper-class family in Wiltshire with the name Folini. Although in these days of world travel who knows.


Q: What's the distribution of $(n_1+n_2+n_3)/\sqrt{N_1N_2N_3}$ with $n_i$ running from $0$ to $N_i - 1$ I am wondering what's the distribution of $$\frac{n_1+n_2+n_3}{\sqrt{N_1N_2N_3}} \text{ with } n_i=0,\ldots,N_{i}-1$$ A quick check using matlab gives that the histogram of this sequence follows a Gaussian distribution. I am wondering how I can prove this analytically.
Thanks for your response in advance!

A: If $A,B,C$ are independent random variables, uniformly distributed over $(0,a),(0,b),(0,c)$, the characteristic function of $A+B+C$ is given by
$$ \frac{i(1-e^{iat})}{at}\cdot \frac{i(1-e^{ibt})}{bt}\cdot \frac{i(1-e^{ict})}{ct} $$
and the PDF of $A+B+C$ can be recovered by (Fourier) inversion, i.e. by computing
$$ \frac{1}{2\pi}\int_{-\infty}^{+\infty}\frac{i(1-e^{iat})}{at}\cdot \frac{i(1-e^{ibt})}{bt}\cdot \frac{i(1-e^{ict})}{ct} e^{-itx}\,dt, $$
usually through the residue theorem. We may also notice that the PDF of $A+B$ is the convolution of the PDFs of $A$ and $B$, hence it is a continuous and piecewise-linear function. Similarly, the PDF of $A+B+C$ is a $C^1$, piecewise-quadratic function.
If $A,B,C\sim U\left(-1,1\right)$ the PDF of $A+B+C$ is explicitly given by $$\frac{(3-x)|3-x|-3(1-x)|1-x|-3(1+x)|1+x|+(3+x)|3+x|}{32}$$
and the following diagram provides a comparison between the PDF of $A+B+C$ (blue) and the PDF of the standard normal distribution (purple). Indeed they are pretty close, as the Berry-Esseen theorem ensures.

Actually a better Gaussian approximation of the PDF of $A+B+C$ is $\sqrt{\frac{7}{16\pi}}\exp\left(-\frac{7x^2}{16}\right)$.
We may deal with discrete distributions along the same lines, I just picked continuous distributions since the Fourier inversion theorem has a more compact form.


Q: What does this error "Thread 1: EXC_BAD_ACCESS (code=2, address=0x30d51fff8)" mean? How do I fix it import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var triviaLabel: UILabel!

    @IBOutlet weak var trueButton: UIButton!

    @IBOutlet weak var falseButton: UIButton!

    @IBOutlet weak var progressBar: UIProgressView!

    var quiz = [Question(text: "Blah blah", answer: "True"),
                Question(text: "Ha ha", answer: "True"),Question(text: "Bruh bruh", answer: "False")]

    var questionNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        updateQuestion()
    }

    @IBAction func answerButtonPressed(_ sender: UIButton) {
        let userAnswer = sender.currentTitle
        let actualAnswer = quiz[questionNumber].answer
        if userAnswer == actualAnswer {

        } else {

        }

        if questionNumber < quiz.count-1 {
            questionNumber += 1
        }else {
            questionNumber = 0
        }
        updateQuestion()
    }

    func updateQuestion() {
        triviaLabel.text = quiz[questionNumber].text // Get the error here
        updateQuestion()
    }
}

The build succeeds and the app launches but there comes a blank screen and the error occurs. I tried mapping the label again with the storyboard. I speculate that there is some problem with the label declaration or connection.


Q: Should Context be injected with Dagger? I know it is possible to inject Context with Dagger. We can see examples here and here.
On the other end, there are numerous posts about not placing context on a static variable to avoid leaks.
Android Studio (lint) also warms about this:

Do not place Android context classes in static fields; this is a
  memory leak (and also breaks Instant Run)

I understand that by injecting a Context with Dagger, we are placing it on a singleton class, so context is somehow static. Doesn't this go against the lint warning?
Injecting the context seems to create cleaner code, since you don't have to pass it to several classes (that don't need it) so that they can further pass it to other classes that need it for some reason (getting a resource for instance).
I am just concerned that this may cause some undesired leak or breaks lint in some way.

A: You should never store/reference activity context (an activity is a context) for longer than the lifetime of the activity otherwise, as you rightly say, your app will leak memory. Application context has the lifetime of the app on the other hand so is safe to store/reference in singletons. Access application context via context.getApplicationContext().

A: If you are aware of Android lifecycles and are careful to distinguish the Application Context and the Context of Activities and Services then there is no fault injecting the Context using Dagger 2.
If you are worried about the possibility of a memory leak you can use assertions to prevent injection of the wrong Context:
public class MyActivityHelper {
     private final Context context;

     @Inject
     public MyActivityHelper (Context context) {
         if (context instanceof Application) {
              throw new IllegalArgumentExecption("MyActivityHelper requires an Activity context");
         }
     }
}

Alternatively you could use Dagger 2 Qualifiers to distinguish the two so you don't accidentally inject an app Context where an Activity Context is required. Then your constructor would look something like this:
@Inject
public class MyActivityHelper (@Named("activity") Context context) {

Note also, as per David's comment, a Dagger 2 @Singelton is not necessarily a static reference.


Q: Allow visits only via domain, block by ip address I am trying to block people from accessing my server via my ip address.  Ideally I would like them to only be able to access it using my domain name.  I have searched Google and unable to find anything.  Is there a way to do this in nginx and/or Apache?

A: On Apache2, create a VirtualHost based on the name of the domain, and an other without nameServer option (which means all names not found in the configuration, like IP). The default should be the first loaded by Apache2.
You can do redirects from default to domain, or serve what page you want as it is separated from your domain VirtualHost

A: <Location /warname>
                SetEnvIF X-Forwarded-For "(,| |^)11\.11\.111\.111(,| |$)" DenyIP
                Order allow,deny
                Deny from env=DenyIP
                Allow from all
        </Location>
CustomLog /opt/apache/logs/DenyIP_access.log common env=DenyIP


Q: Can a factory method pattern use different overloads I have a use case where I need to build a factory class that returns different concrete types based on an enum being passed. However, each of those types require different constructor parameters. So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all?
I'm thinking something like
class CarFactory
{
  public ModelS TeslaMaker (List<Battery> batteries){/*return ModelS*/}
  public Mustang FordMaker (Engine engine) {/*return a Mustang*/}
}

instead of say
    class CarFactory
    {
      public Car GetCar(CarType carType) //where CarType is an enum (Ford=0,Tesla=1)
      {
        switch(carType)
        {  case CarType.Ford: return new Mustang(); }//just an example
      }
    }

EDIT:
In my case I actually need to return a family of classes. So, if it's a Tesla, return a ModelS, a ModelSService, ModelSWarranty, etc. So I'm going to go with the Abstract Factory approach which will wrap the suggestions given here.

A:
So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all?

It doesn't make any sense to have a factory with specific methods. If your client code has to decide which specific method should it use, why wouldn't it call the specific car's constructor directly? In your example, factory methods would merely be wrappers over specific constructors.
On the other hand having a single factory method that is called with an enum gives your client a chance to decide dynamically which car should it create, the decision could for example be based on a database query.
There are some possible ways around your current approach.
One option would be to have a hierarchy of classes that represent constructor parameters. You don't even need the enum then because the parameter type is enough to infer which specific car should be created:
public abstract class CarCreationParams { }

public class FordCreationParams : CarCreationParams
{
    public Engine engine;
}

...

public class CarFactory
{
    public Car GetCar( CarCreationParams parms )
    {
        if ( parms is FordCreationParams )
            return new Ford( ((FordCreationParams)parms).engine );
        ...

Another option would be to think whether you really need your Fords to be created with external engines (aggregation) or rather they own their engines (composition). In the latter case, you would expose parameterless constructors to your specific car types:
public class Ford : Car
{
     public Engine engine;

     // car is composed of multiple parts, including the engine
     public Ford()
     {
          this.engine = new FordEngine();
     }

which makes the implementation of the factory much easier.

A: No that is not a good example of factor pattern. Rather if your Car class is dependent on different types of Components you can have factories for those too. E.G For Car and Engine you can have like:
    public interface ICar
    {
        IEngine Engine { get; set; }
    }

    public class Mustang : ICar
    {
        private IEngine _engine = EngineFactory.GetEngine(EngineType.Mustang);
        public IEngine Engine
        {
            get { return _engine; }
            set { _engine = value; }
        }
    }

    public class CarFactory
    {
        public ICar GetCar(CarType carType)
        {
            switch (carType)
            { case CarType.Ford: return new Mustang(); }
        }
    }

Similarly for Engine
    public interface IEngine { }

    public class MustangEngine : IEngine
    {

    }

    public class EngineFactory
    {

        public static IEngine GetEngine(EngineType engine)
        {
            switch (engine)
            { case EngineType.Mustang: return new MustangEngine(); }
        }
    }

A: In case you need different parameters for object creation(batteries for Tesla or Engine for Ford) you can choose between different solutions:
 - pass all of these parameters while creating a factory  - it will be specific factory for all types of car with such available details;
class SpecificCarFactory
{
  public SpecificCarFactory(IList<Battery> batteries, IList<Engine> engines)
  {
    //save batteries etc into local  properties
  }
  public Car GetCar(CarType carType)
  {
    switch(carType)
    {  case CarType.Ford: return new Mustang(_engines.First()); }
  }
}

*

*encapsulate parameters into class object and get them from factory method parameter;
class CarFactory
{
      public Car GetCar(CarDetail carDetail) //where CarDetails                  encapsulates all the possible car details
      {
             switch(carDetail.type)
             {  case CarType.Ford: return new Mustang(carDetail.Engine);//just an example
             }
      }
}

A: Yes, It is factory pattern.
factory pattern says to create factories of Object but let subclass decide the way to instantiate the object .
This is true in your case your deciding based on type of Enum


Q: How to set/remove attributes dynamically in c#? I am using from attribute validation in my project.
[Required(ErrorMessage = "DepartmentCode is Required")]
public string DepartmentCode { get; set; }

In some case DepartmentCode isn't required. How can I dynamically ignore Validation in my case?

A: Take a look at: Remove C# attribute of a property dynamically
Anyway I think the proper solution is to inherit an attribute from RequiredAttribute and override the Validate() method (so you can check when that field is required or not). You may check CompareAttribute implementation if you want to keep client side validation working.

A: Instead of dynamically adding and removing validation, you would be better served to create an attribute that better serves this purpose.
The following article demonstrates this (MVC3 with client-side validation too):
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx

A: I would remove the RequiredAttribute from your model and check it once you've hit your controller and check it against whatever causes it to not be required.
If it falls into a case where it is required and the value is not filled in, add the error to the ModelState manually
ModelState.AddModelError("DepartmantCode", "DepartmantCode is Required");
You would just lose the validation on the client side this way

A: I've got round this issue in the model, in some cases it's not ideal but it's the cheapest and quickest way.
public string NonMandatoryDepartmentCode
{
    get
    {
        return DepartmentCode;
    }
    set
    {
        DepartmentCode = value;
    }
}

I used this approach for MVC when a base model I inherited contained attributes I wanted to override.


Q: Why do Spark jobs require so much memory? I am experiencing memory issues when running PySpark jobs on our cluster with YARN. YARN keeps killing my executors for running out of memory, no matter how much memory I give them, and I cannot understand the reason for that.
Example screenshot:
Screenshot from SparkUI
The amount of data that one task is processing is even slightly lower than the usually recommended 128 MB, and yet it gets killed for exceeding 10 GB (6 GB executor memory + 4 GB overhead). What is going on there?
The only answer that I keep bumping in everywhere I look is to increase the memory allocation even more, but, obviously, there is a physical limit to that at some point (and we do want to run other MapRed/Spark jobs simultaneously), so rather than increasing the memory allocation mindlessly, I would like to understand why so much memory is used.
Any help on that will be greatly appreciated! If you need any additional input from me, I'll be glad to provide it, if I can.
UPDATE: Found the culprit. By carefully restructuring and analyzing the code I managed to localize the code which is running out of memory. I use a rather complicated UDF there. I'll try and rework that bit of code, maybe it will solve the problem.


Q: PDOException There is no active transaction al hacer un test en laravel 9 estoy haciendo un test en laravel 9, usando RefreshDatabase y primero intentando correr unos seeders que utilizo para importar datos y rellenar tablas de areas, area_groups y area_cities, todo esto funciona bien, pero quiero hacer test de rellenado de formularios livewire, y para eso necesito importar datos de dichas areas, pero obtengo el error

PDOException
There is no active transaction

si elimino el trait RefreshDatabase y dejo solamente el InteractsWithDatabase el test se ejecuta sin problemas, sin embargo, al finalizar el test, la base de datos no se vacía, y se supone que es para eso el RefreshDatabase
este es mi test
class UserProfileRegistrationTest extends TestCase
{
    use RefreshDatabase;
    use InteractsWithDatabase;

    public function test_user_can_register_profile()
    {
        $this->seed();
        $user = User::factory()->create();

        $this->actingAs($user);
        Livewire::test(UserProfileInformationForm::class)
            ->set(['username' => 'tabimuse1',
                'occupation' => 'Doctor',
                'name' => 'tabimuse',
                'last_name' => 'last name',
                'self_introduction' => 'test self introduction',
                'gender' => 'Male',
                'area_city_id' => 67,
                'website' => 'https://www.facebook.com',
                'instagram_id' => 'tabimuse',
                ])
            ->call('save');
    }
}

A: finalmente tuve que declarar una variable protegida antes de ejecutar los tests para que pueda hacer el seed
protected bool $seed = true;

con esto ya no es necesario utilizar el InteractsWithDatabase y utilizo solamente el RefreshDatabase


Q: Graphics rendering in thread game loop. Changing data on arrays I have two objects of 2D int arrays called:
originalMap and rendedMap which they contain numbers that correspond to the puzzle game map.
From the thread class i obtain the map array from the class call Puzzle.java and modifying the one.
   int [][] rendedMap = Puzzle.getRendedMap().getMap();
   int [][] originalMap = Puzzle.getMapObj().getMap();

This is my thread loop:
drawPuzzle(canvas, map); takes the canvas and the array and draws a map.
    while(running){
            if(!holder.getSurface().isValid())
                continue;

                    canvas = holder.lockCanvas();

                    if(runSolution && movements.size()>0){
                        executeSolution();
                        drawPuzzle(canvas, rendedMap);
                        if(finished){//checks if the execution finished
                            runSolution=false;
                        }
                    if(message.equals("No more actions") ||
                                    message.equals("Out of bounds, try again!")){
                            System.out.println(message);
                            drawPuzzle(canvas, originalMap);
                    }
                    }else{
                        drawPuzzle(canvas, originalMap);
                    }

                    drawMovements(canvas);
                    holder.unlockCanvasAndPost(canvas);
    }
}

And this is the method that i modify the array:
public void executeSolution(){

    numOfPlanets = 2;

    for(int x=0;x<rendedMap.length-1; x++){
        for(int y=0;y<rendedMap[x].length-1; y++){
            //Checks where the robot is and saves its initial position
            if(rendedMap[x][y]>=7 && rendedMap[x][y]<=9){
                initX=x; initY=y; initial=true;
                System.out.println("Initial X: "+initX +" Y: "+initY );
                direction = rendedMap[x][rendedMap[x].length-1];
                System.out.println("Direction: "+direction );
            }
        }//end inner for
    }//end for

    if(movements.size()>0){
        for(int i=0; i<movements.size();i++){

            if(movements.get(i).getColour().equals("none")){
                if(movements.get(i).getMotion().equals("straight")){
                    if(direction==RIGHT){
                        if(rendedMap[initX][initY+1]==0){
                            finished=true;
                            message = "Out of bounds, try again!";
                            return;
                        }else{
                            rendedMap[initX][initY+1]= rendedMap[initX][initY+1]+6;
                            rendedMap[initX][initY]=rendedMap[initX][initY]-6;
                        }
                    }
                }//action if
            }//color if
        }//movements for loop

        if(numOfPlanets > 0 ){
            finished = true;

            message ="No more actions";
        }
    }//movements if statement
}

My problem is when i render the renderMap array for some reason originalMap changes as well and when i am trying to draw back the originalMap it doesn't change back.
I have even print them out and checked line by line and they are the same.
Any tips what might cause this?
I spend like days to figure it out.

A: if(direction==RIGHT) {
    if(rendedMap[initX][initY+1]==0) {
        finished=true;
        message = "Out of bounds, try again!";
        return;
    } else {
        rendedMap[initX][initY+1]= rendedMap[initX][initY+1]+6;
        rendedMap[initX][initY]=rendedMap[initX][initY]-6;
    }
}

check your rendedMap array is been initialized because this can often lead to contextual errors, especially within the android IDE.

A: if(!holder.getSurface().isValid())
                continue;

                    canvas = holder.lockCanvas();

                    if(runSolution && movements.size()>0){
                        executeSolution();
                        drawPuzzle(canvas, rendedMap);
                        if(finished){//checks if the execution finished
                            runSolution=false;
                        }
                    if(message.equals("No more actions") ||
                                    message.equals("Out of bounds, try again!")){
                            System.out.println(message);
                            drawPuzzle(canvas, originalMap);
                    }
                    }else{
                        drawPuzzle(canvas, originalMap);
                    }

                    drawMovements(canvas);

recall your drawPuzzle beforte surface view is locked down as the else causes it may not be executed in that contextual loop, as I said befor it is a problem that is comon with our organization apps
hope this helps! do hesistate to ask for more assistence
sorry for english I am indian


Q: Django m2m_changed signal with additional model I have a model looking like this:
class Recipe(models.Model):
    name = models.CharField(_('Name'))
    components = models.ManyToManyField(RecipeComponent, through='alchemy.RecipeComposition')
    total_weight = models.FloatField(_('How much recipe will weight'))

class RecipeComponent(models.Model):
    name = models.CharField(_('Name'))

class RecipeComposition(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    component = models.ForeignKey(RecipeComponent, on_delete=models.CASCADE)
    number = models.FloatField(_('Defines how much of the component you need'), default=1)

I have to do some calculations (for example total weight) of the recipe after any updates in RecipeComposition.
Trying to do like this unfortunately doesn't help:
@receiver(m2m_changed, sender=Recipe.components.through, weak=False)
def recipe_components_changed(sender, **kwargs):
    print("meow >^-_-^<")
    # some calculations for recipe.total_weight here

Found question with same problem but it's old (3 yrs ago) and has no correct answer. There is a link to ticket 17688 there which is opened 6 yrs ago but still not solved.
I do not want to use post_save like this:
@receiver(post_save, sender=RecipeComposition)

because in this case when new Recipe created total_weight will be recalculated after each component added.
Are there any other ideas how to make this work?