text:
Q: Decompiled Java class producing different output Out of curiosity I just decompiled below code using DJ Java Decompiler as well using CAVAJ Java Decompiler
( Java version is 1.7 )
here is the normal source code :

    byte a = 10;
    a = (byte) (a +1);

    byte b = 10;
    b = b++;

    byte c = 10;
    c +=c;

    System.out.printf("a=%d \t b=%d \t c=%d\n",a,b,c);

Which shows output as: a=11        b=10      c=20

And here is the decompiled one:
    byte a = 10;
    a++;
    byte b = 10;
    b++;
    b = b;
    byte c = 10;
    c += c;
    System.out.printf("a= %d \t b = %d \t c = %d\n", new Object[] {
        Byte.valueOf(a), Byte.valueOf(b), Byte.valueOf(c)
    });

Which when used as source code output as: a=11        b=11      c=20

To be more clear it has nothing to do with byte same thing happening for int as well and I even checked above codes in online compiler IDEONE and giving the same output as mine.
So, is the decompiler producing wrong code or is something else ??

A: I will give you short answer: yes, it seems, that the decompiler is producing wrong code.
Because this one:
byte b = 10;
b = b++;

has strongly predicted behavior (b will not change).
UPD: Furthermore, no one of decompilers can give you 100% warranty of the correctness of generated decompiled code.
UPD-2: Are you sure, that you provide us actual version of your code? Because this one:
byte aa = 10;
a = (byte) (a +1);

of course is a mistake. It even will not compile :)
UPD-3 Well, I need to say, that Jad decompiler (Jad 1.5.8g for Windows 9x/NT/2000 on Intel platform) produces the same code:
    byte b = 10;
    b++;
    b = b;

...
    java.lang.System.out.printf("a=%d \t b=%d \t c=%d\n", new java.lang.Object[] {...

But this is not surprising: Cavaj Java decompiler uses Jad as its Java decompiling engine.
Conclusion: Consider this behavior as a feature/bug of Jad decompiler, which is far from a perfection.

A: This is not about decompiler. When you compile a code using java compiler, in some cases, the compiler changes your code and optimize it to another code that does not change the result. Your code is:
byte a = 10;
a = (byte) (a + 1);

In this case, java compiler knows that there is no need to type cast between byte and byte and because of it, the compiler tries to remove your typecast and in this process, it replaces your code with closest code that it can understand. This is the compiler output:
byte a = 10;
a++;

So, this is not about decompile process. The java compiler changes your code.


text:
Q: Microsoft JScript runtime error: Object doesn't support property or method 'getElementsByTagName' in IE9 I've a page with a TreeView control and the parent node is checked, the child nodes will be checked as well. It was done using javascript. But when the page is opened is IE9 and trying to check the parent node, I will get an error of:
Microsoft JScript runtime error: Object doesn't support property or method 'getElementsByTagName'
function AreAllSiblingsChecked(chkBox)
{
 var parentDiv = GetParentByTagName("div", chkBox);
 var childCount = parentDiv.childNodes.length;
 for(var i=0;i<childCount;i++)
 {
             var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
             //if any of sibling nodes are not checked, return false
             if(prevChkBox.checked)
             {
                return true;
             }
 }
 return false;
}

//utility function to get the container of an element by tagname
function GetParentByTagName(parentTagName, childElementObj)
{
 var parent = childElementObj.parentNode;
 while(parent.tagName.toLowerCase() != parentTagName.toLowerCase())
     {
         parent = parent.parentNode;
     }
 return parent;
}

Appreciate if someone can help me to solve this! thanks in advance...

A: In IE9, childNodes[] returns text nodes (comments or whitespace) as well as child tags.  Text nodes do not support getElementsByTagName().  There's a good summary of the underlying DOM model here.
The easiest fix is just to check for the existence of the method before using it:
function AreAllSiblingsChecked(chkBox)
{
     var parentDiv = GetParentByTagName("div", chkBox);
     var childCount = parentDiv.childNodes.length;
     for(var i=0;i<childCount;i++)
     {
         if (parentDiv.childNodes[i].getElementsByTagName) {
             var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
             //if any of sibling nodes are not checked, return false
             if(prevChkBox.checked)
             {
                return true;
             }
         }
     }
     return false;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get image directly? Follwing webpage includes light adult contents. Please do not click link if you don't want it.

*

*go to : http://www.hqasians.com/tgp/bigasiantits/MaiNishida/at.htm

*you can see several thumb images.

*click one of them. you can see large image.

*Check current page url. It will be like ~~~~~~~~~~~~~~~~/tgp/bigasiantits/MaiNishida/images/01.jpg

*you can know how to access another image by changing last .jpg name of whole url

*change 01.jpg to 02.jpg and enter.

*But, you will encounter website's main page not 02.jpg.

Is this security way to block direct access by that site ?
Is there any work-around way to get image directly?

Following is my codes.
InputStream bmis;
bmis = new URL(params[0]).openStream();
final Drawable image =
new BitmapDrawable(BitmapFactory.decodeStream(new FlushedInputStream(bmis)));

if(image != null)
{
activity.setContentView(imageSwitcher);

imageSwitcher.setImageDrawable(image);

}

A: I'm only guessing here, but I think what this site does is to check the "Referer" field from the HTTP request header to check whether the request came from within the site, or from outside.
It isn't a secure way of blocking direct access. In fact, there's an workaround, but I don't think the site rules allow me to write it here, so, you'll have to figure out yourself.

A: It's because of the Referrer. You have to be referred by that main page to open the picture.
Sorry I'm not sure how to use Android, but C# code should look like this:
   static void Main(string[] args)
    {
        for (int i = 1; i <= 15; i++)
        {
            HttpWebRequest request =
                WebRequest.Create(
                    string.Format("http://www.hqasians.com/tgp/bigasiantits/MaiNishida/images/{0:00}.jpg", i)
                    ) as HttpWebRequest;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Referer = "http://www.hqasians.com/tgp/bigasiantits/MaiNishida/at.htm";
            request.Method = "POST";
            WebResponse response = request.GetResponse();
            string inputFile = string.Format("{0}.jpg", i);
            Console.WriteLine(response.ResponseUri.AbsoluteUri);
            using (Stream file = File.OpenWrite(inputFile))
            {
                CopyStream(response.GetResponseStream(), file);
            }
        }
    }

    /// <summary>
    /// Copies the contents of input to output. Doesn't close either stream.
    /// </summary>
    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[8 * 1024];
        int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    }

The CopyStream method is got from here: How do I save a stream to a file in C#?


text:
Q: The idiom "be first in Maths" I came across the idiom "be first in Maths". But I couldn't find any with other school subjects.
Is it possible to say "be first in Geography/Physics"? Or the preposition "in" goes only whith Maths?
When did this idiom "be first in Maths" come to be?

A: The short answer is that it is equivalent to:

Be (ranked) first in math

And so it is possible to be first in other subjects, so long as there is some way to rank participants.

A: In this situation, "Maths" is referring to the group (i.e. Maths class), not the subject of the lesson.

*

*You can be first in the group - first in Maths.

*You can be the best at the subject - best at Maths.

*You can also be the best in the group - best in Maths.

*But you can't be the first at the subject - first at Maths. X
The same rules apply for other classes/subjects.

A: At first I thought you were right, but after that I realised that it was "first", not "good".
We do not say "be first in/at" but we say "be first for".
Definition of "for" by Dictionary.com

with the object or purpose of

e.g. to run for exercise.

be first [with what? Math.] for Math

Nevertheless, it is still possible to use in/at for similar cases.

be good at Math

your Math is good

be good in Math

you are good in Math (class/lesson)


text:
Q: Java - Can Calendar.getInstance() be used to differentiate past and future events I have an Event class. I am using a GregorianCalendar to store the date of the Event. If I want to find which events have already occurred before today and which events are in the future, does Calendar.getInstance() give the present date which I can then use to compare?

A: Yes, you can use Calendar.before() and Calendar.after(). Like So:
if(Calendar.getInstance().before(myEvent)){
   // do before stuff
} else if(Calendar.getInstance().after(myEvent)) {
   // do after
} else {
   // do right now
}

A: Taken off the first search https://www.google.com/search?q=Calendar.getInstance()

Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:

 Calendar rightNow = Calendar.getInstance();


text:
Q: How do I keep the column names in a data frame when I am trying to drop all of the rows that don't start with specific names? I need to drop the majority of the companies in a historical stock market data CSV. The only companies I want to keep are 'GOOG', 'AAPL', 'AMZN', 'NFLX'. Note that there are over 20 000 companies listed in the CSV. I also want to filter out these companies while only using certain columns in the CSV. The columns are: 'ticker', 'datekey', 'assets', 'eps', 'pe', 'price', 'revenue'.
The code to filter out these companies is:
list = ['GOOG', 'AAPL', 'AMZN', 'NFLX']

for tickers in list:
    df1 = df[df.ticker == tickers]
    df1.to_csv("20CompanyAnalysisData1.csv", mode='a', header=False)

    continue

This code is successfully able to write only the columns that I want to the new CSV and only list the data of the companies that I want.
The problem: The new CSV isn't printed with the column names which make it really confusing to have to go and list them manually especially when I will be adding more data columns.
Example of CSV I'm reading from (with data columns):
ticker,dimension,calendardate,datekey,reportperiod,lastupdated,accoci,assets,assetsavg,assetsc,assetsnc,assetturnover,bvps,capex,cashneq,cashnequsd,cor,consolinc,currentratio,de,debt,debtc,debtnc,debtusd,deferredrev,depamor,deposits,divyield,dps,ebit,ebitda,ebitdamargin,ebitdausd,ebitusd,ebt,eps,epsdil,epsusd,equity,equityavg,equityusd,ev,evebit,evebitda,fcf,fcfps,fxusd,gp,grossmargin,intangibles,intexp,invcap,invcapavg,inventory,investments,investmentsc,investmentsnc,liabilities,liabilitiesc,liabilitiesnc,marketcap,ncf,ncfbus,ncfcommon,ncfdebt,ncfdiv,ncff,ncfi,ncfinv,ncfo,ncfx,netinc,netinccmn,netinccmnusd,netincdis,netincnci,netmargin,opex,opinc,payables,payoutratio,pb,pe,pe1,ppnenet,prefdivis,price,ps,ps1,receivables,retearn,revenue,revenueusd,rnd,roa,roe,roic,ros,sbcomp,sgna,sharefactor,sharesbas,shareswa,shareswadil,sps,tangibles,taxassets,taxexp,taxliabilities,tbvps,workingcapital
A,ARQ,1999-12-31,2000-03-15,2000-01-31,2020-09-01,53000000,7107000000,,4982000000,2125000000,,10.219,-30000000,1368000000,1368000000,1160000000,131000000,2.41,0.584,665000000,111000000,554000000,665000000,281000000,96000000,0,0.0,0.0,202000000,298000000,0.133,298000000,202000000,202000000,0.3,0.3,0.3,4486000000,,4486000000,50960600000,,,354000000,0.806,1.0,1086000000,0.484,0,0,4337000000,,1567000000,42000000,42000000,0,2621000000,2067000000,554000000,51663600000,1368000000,-160000000,2068000000,111000000,0,1192000000,-208000000,-42000000,384000000,0,131000000,131000000,131000000,0,0,0.058,915000000,171000000,635000000,0.0,11.517,,,1408000000,0,114.3,,,1445000000,131000000,2246000000,2246000000,290000000,,,,,0,625000000,1.0,452000000,439000000,440000000,5.116,7107000000,0,71000000,113000000,16.189,2915000000
A,ARQ,2000-03-31,2000-06-12,2000-04-30,2020-09-01,-4000000,7321000000,,5057000000,2264000000,,10.27,-95000000,978000000,978000000,1261000000,166000000,2.313,0.577,98000000,98000000,0,98000000,329000000,103000000,0,0.0,0.0,256000000,359000000,0.144,359000000,256000000,256000000,0.37,0.36,0.37,4642000000,,4642000000,28969949822,,,-133000000,-0.294,1.0,1224000000,0.493,0,0,4255000000,,1622000000,0,0,0,2679000000,2186000000,493000000,29849949822,-390000000,-326000000,2000000,-13000000,0,-11000000,-341000000,95000000,-38000000,0,166000000,166000000,166000000,0,0,0.067,1010000000,214000000,572000000,0.0,6.43,,,1453000000,0,66.0,,,1826000000,297000000,2485000000,2485000000,296000000,,,,,0,714000000,1.0,452271967,452000000,457000000,5.498,7321000000,0,90000000,192000000,16.197,2871000000

The code is then listed in the new CSV like this:
4290,AAPL,1998-02-09,4126000000.0,0.003,,0.171,1578000000.0
4291,AAPL,1998-05-11,3963000000.0,0.004,,0.276,1405000000.0
4292,AAPL,1998-08-10,4041000000.0,0.006999999999999999,,0.33899999999999997,1402000000.0

I then need to go in and manually add the column titles so that the final CSV (edited by me) looks like:
index,ticker,datekey,assets,eps,pe,price,revenue
4289,AAPL,1997-12-05,4233000000.0,,-1.9380000000000002,0.141,
4290,AAPL,1998-02-09,4126000000.0,0.003,,0.171,1578000000.0
4291,AAPL,1998-05-11,3963000000.0,0.004,,0.276,1405000000.0

How can I make this work when I have hundreds of data categories that I am using and can't input them manually?

A: list = ['GOOG', 'AAPL', 'AMZN', 'NFLX']
first = True

for tickers in list:
    df1 = df[df.ticker == tickers]
    if first:
        df1.to_csv("20CompanyAnalysisData1.csv", mode='a', header=True)
        first = False
    else:
        df1.to_csv("20CompanyAnalysisData1.csv", mode='a', header=False)
    continue

or more compactly
list = ['GOOG', 'AAPL', 'AMZN', 'NFLX']
needheader = True

for tickers in list:
    df1 = df[df.ticker == tickers]
    df1.to_csv("20CompanyAnalysisData1.csv", mode='a', header=neadheader)
    needheader = False
    continue

A: Assign the column names before saving the file (and remove header=False), as below:
list = ['GOOG', 'AAPL', 'AMZN', 'NFLX']

for tickers in list:
    df1 = df[df.ticker == tickers]
    df1.columns=['index','ticker','datekey','assets','eps','pe','price','revenue']
    df1.to_csv("20CompanyAnalysisData1.csv", mode='a')

    continue


text:
Q: formulario con php espero estén bien :).
Bueno estaba intentando validar un login a lo cual ya me resulta pero el mensaje de error que le puse al else me imprime en la web, no debería ser asi. El mensaje ya se debería ver cuando ingreso datos incorrectos. Espero me puedan ayudar se los agradecería mucho :). El primero es donde realizo la validación y el otro es el formulario.
> Validación

    <?php
include('db.php');
$usuario=$_POST['usuario'];
$contraseña=$_POST['contraseña'];
session_start();
$_SESSION['usuario']=$usuario;

$conexion=mysqli_connect("localhost","root","","bdtienda");

$consulta="SELECT*FROM usuario where nombre='$usuario' and contraseña='$contraseña'";
$resultado=mysqli_query($conexion,$consulta);

$filas=mysqli_num_rows($resultado);

if($filas){

    header("location:pagina.php");

}else{
    include("index.php");
    ?>

No ingreso

    <?php
}
mysqli_free_result($resultado);
mysqli_close($conexion);

> Formulario

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>login</title>
    <link rel="stylesheet" href="css/login.css">
    <link rel="stylesheet" href="css/cabecera.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css">

   <form action="validar.php" method="post">

Sistema de login

Usuario <input type="text" placeholder="ingrese su nombre" name="usuario">

Contraseña <input type="password" placeholder="ingrese su contraseña" name="contraseña">

   <input type="submit" value="Ingresar">

   </form>

A: El problema que tienes es que nada mas entrar a  la web estas realizando la consulta.
para solucionarlo debes:
1- asignar la propiedad name al boton login

<input type="submit" name="btnlogin" value="Ingresar">

*preguntar en el código php si se ha hecho click en el boton.

<?php
session_start(); //esta linea siempre primero al crear el documento
include('db.php');

if(isset($_POST[btnlogin])){

  $usuario=$_POST['usuario'];
  $contraseña=$_POST['contraseña'];

  $conexion=mysqli_connect("localhost","root","","bdtienda");
  $consulta="SELECT*FROM usuario where nombre='$usuario' and contraseña='$contraseña'";
  $resultado=mysqli_query($conexion,$consulta);

  $filas=mysqli_num_rows($resultado);

  if($filas){

    $_SESSION['usuario']=$usuario;
    header("location:pagina.php");

  }else{
    include("index.php");
    echo "
No ingreso
";

  }
  mysqli_free_result($resultado);
  mysqli_close($conexion);
}

NOTA: debes replantear la lógica del login


text:
Q: Function argument as filename Addig a file to MediaPlayer is easy:
mp = MediaPlayer.create(Myctivity.this, R.raw.sound);

But what if I have the filename as an argument coming from a function like this?
  public void CreateSound(String filename, float volume)
    {
        mp = MediaPlayer.create(Myctivity.this, R.raw.???);
             mp.setVolume(volume, volume);
           try {
            mp.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
           mp.start();
    }

A: This thread mentions
 int resID=getResources().getIdentifier(fname, "raw", getPackageName());

which takes a file name and fetches the ID. (OBS: Before using the file name it's converted to lower case)
This can then be passed to the MediaPlayer:
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);


text:
Q: How to configure nginx to redirect traffic if cookie is set, then decide on percentage probability the destination I need some help for a use case that I want to implement in nginx proxy that I could not find a direct solution in nginx manual.
Use case:
I have one old website that I replatformed in new technology.
I want to redirect(serve via new site) all users that don't are not using the old website (I can tell this if they are missing a cookie ex old_web_cookie)
Then for all users in the category above (new users that never visited the site at all, or opened private browsers), want to split them by 80% of them still visit the old web, and 20% of them receive responses of new web.
Architecture
Current architecture for test purpose is super simple, one nginx proxy and 2 docker containers. One containing web and a new one newweb
part of my nginx.conf
server {
    server_name test.dev;

    access_log /var/log/nginx/access.log json_combined;

    client_max_body_size 20M;

    listen 80;
    listen 443 ssl http2;
    http2_push_preload on;
    ssl_certificate /etc/letsencrypt/live/test.dev/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/test.dev/privkey.pem;

    location / {
      // HERE I want to implement the code that I am asking about
      if ($http_cookie ~* "old_web_cookie") {
         // so all users that are using the old web (web) i want still to be served from it
         proxy_pass http://web:8080;
      } else {
         // split traffic 80% go to web (old web)
         proxy_pass http://web:8080;
         // 20% of traffic here go to http://newweb:9080
         proxy_pass http://newweb:9080;
      }

      // rest is not interesting for the question
      proxy_set_header  X-Real-IP $remote_addr;
      proxy_set_header  X-Forwarded-For $remote_addr;
      proxy_set_header  X-Forwarded-Host $remote_addr;
    }
  }

In my nginx.conf file above, I put pseudocode explaining the logic I want to implement but that of course doesn't work.
First I noticed that nginx does not have else statement, and secondly don't know how to do something like 20% of users use this location (proxy) 80% this other one


text:
Q: How to download AMI from Amazon EC2 .? I would like to download a Amazon EC2 AMI
Can i know the procedure for downloading a AMI from Amazon EC2 account.
How do I do this?

A: I think this is what you are looking for
https://aws.amazon.com/ec2/vm-import/


text:
Q: javascript function does not work I am currently in the middle of the development of a website. If a user presses a button an javascript function needs to be called. I simplified this function to:

     <input type="text" name="textfieldCustomer">

     <input type="text" name="textfieldSoftware">

     <input type="text" name="textfieldHardware">

     <input type="text" name="textfieldDescription">

     <input type="button" name="button" value="go to function" onClick="newProd('a number',textfieldCustomer.value,textfieldSoftware.value,textfieldHardware.value,textfieldDescription.value)">

when the user presses the button in Internet explorer, the function works perfectly! Unfortunately the function does not work in Chrome or Safari.
Does anyone have any idea what is going wrong?

A: The form fields are not supposed to be defined as global variables. Maybe in IE they are but that's not a behavior you can depend on. Try this:
onClick="newProd('a number',
    this.form.textfieldCustomer.value,
    this.form.textfieldSoftware.value,
    this.form.textfieldHardware.value,
    this.form.textfieldDescription.value)">

Oh, and add a form to wrap the inputs of course.
Demo: http://jsfiddle.net/kdUMc/

A: In my eyes there  are two big mistakes in your code. First, the access to inputs fields is wrong. It needs a connection to an instance variable, like 'document'. The second one, the form tag is missing. If you wrap the input fields into a form tag you can access the values as Esailija has posted.


text:
Q: How to use Real time chart in react? I'm currently building a realtime chart to test it out. I wrote something to receive data as an example, but it doesn't work. Below is my code.
import { StreamingPlugin, ChartStreaming } from 'chartjs-plugin-streaming'
import {
  Chart as ChartJS,
  LinearScale,
  CategoryScale,
  RadialLinearScale,
  BarElement,
  PointElement,
  LineElement,
  ArcElement,
  Legend,
  Tooltip
} from 'chart.js'
import {
  Chart,
  Line,
  Pie,
  Doughnut,
  Radar,
  getDatasetAtEvent,
  getElementAtEvent,
  getElementsAtEvent,
} from 'react-chartjs-2'
ChartJS.register(
  LinearScale,
  RadialLinearScale,
  CategoryScale,
  BarElement,
  PointElement,
  LineElement,
  ArcElement,
  StreamingPlugin,
  Legend,
  Tooltip
)

const data =
{
  datasets :
  [
    {
      label : "real",
      backgroundColor : "rgb(255, 99, 132)",
      borderColor: "rgb(255, 99, 132)",
      fill : false,
      lineTension : 0,
      borderDash: [8,4],
      data : [],
      showLine: true,
    }
  ]
}
console.log(data.datasets[0].data)
const RealTime_ChartTest_options =
{
  elements :
  {
    line :
    {
      tesion: 0.5
    }
  },
  scales :
  {
    xAxes: [
      {
        type: "realtime",
        realtime: {
          onRefresh: function () {
            data.datasets[0].data.push({
              x: Date.now(),
              y: Math.random() * 100
            }
            );
          },
          delay: 300,
          refresh: 300
        }
      }
    ],
    yAxes: [
      {
        scaleLabel: {
          display: true,
          fontFamily: "Arial",
          labelString: "Moment",
          fontSize: 20,
          fontColor: "#6c757d"
        },
        ticks: {
          max: 100,
          min: 0
        }
      }
    ]
  }
}

const App = ()=>
{
  retrun(
   <Line data={data} options={RealTime_ChartTest_options} />
  )
}

As a result, the Y-axis and labels are displayed correctly, but the values are not stored in the data in real time and the graph is not drawn.
What am I doing wrong in the code?

A: This is because your scale config is wrong, you are using V2 syntax while using V3, changing it to this should resolve the issue:
scales: {
  x: {
    type: "realtime",
    realtime: {
      onRefresh: function() {
        data.datasets[0].data.push({
          x: Date.now(),
          y: Math.random() * 100
        });
      },
      delay: 300,
      refresh: 300
    }
  },
  y: {
    max: 100,
    min: 0
  }
}

For all changes please read the migration guide


text:
Q: GCC Generated a Misaligned "ldrd" Instruction When compiling this C++ code:
#include "../SM64DS_2.h"

//@021026a0, hooks: 0x020bddb8, 0x020bde0c
void CancelPowerups(Player& player)
{
    if(player.isFreezeFramePeach)
    {
        player.isFreezeFramePeach = false;
        player.EndMusic(0x33);
    }
    if(player.isDashyToad)
    {
        player.isDashyToad = false;
        player.EndMusic(0x33);
    }
}

//hook: 0x020b98f8
void EnableFreezeFramePeach(Player& player)
{
    //TODO: Show message on first use
    player.isFreezeFramePeach = true;
    player.flowerPowerTimer = 600;
    player.SetMusic(0x33);
}

//hook: 0x020b9904
void EnableDashyToad(Player& player)
{
    //TODO: Show message on first use
    player.isDashyToad = true;
    player.flowerPowerTimer = 600;
    player.SetMusic(0x33);
}

//hook: 0x020e4f10
void WorkDashyToadPart1(Player& player)
{
    //TODO: Deal with speed of walking animation
    if(player.isDashyToad)
    {
        player.horzSpeed /= 2;
        player.isSpeedHalfed = true;
        if(player.walkOnWaterTimer == 61)
            ++player.walkOnWaterTimer;
    }
}

//hook: 0x020e52e8
void WorkDashyToadPart2(Player& player)
{
    if(player.isSpeedHalfed)
    {
        player.horzSpeed *= 2;
        player.isSpeedHalfed = false;
        player.dashyToadParticleSysID = Particle::System::New(player.dashyToadParticleSysID,
                                                              0x4a,
                                                              player.pos.x,
                                                              player.pos.y + Fix12i(72),
                                                              player.pos.z,
                                                              nullptr,
                                                              nullptr);
    }
}

with the following flags for gcc
arm-none-eabi-g++ -MMD -MP -MF /c/Users/Joshua/Documents/desmume-0.9.11-win64/SM64DSe/SM64DSe/ASMPatchTemplate/build/PeachToadAbilities.d -g -Wall -O2 -march=armv5te -mtune=arm946e-s -fomit-frame-pointer -ffast-math  -iquote /c/Users/Joshua/Documents/desmume-0.9.11-win64/SM64DSe/SM64DSe/ASMPatchTemplate/include -I/c/devkitPro/libnds/include -I/c/devkitPro/devkitARM/include -I/c/devkitPro/devkitARM/arm-none-eabi/include -I/c/Users/Joshua/Documents/desmume-0.9.11-win64/SM64DSe/SM64DSe/ASMPatchTemplate/build -DARM9 -nodefaultlibs -I. -fno-builtin -c --std=c++14 -fno-rtti -fno-exceptions -Wa,-adl=PeachToadAbilities.lst -c /c/Users/Joshua/Documents/desmume-0.9.11-win64/SM64DSe/SM64DSe/ASMPatchTemplate/source/C_PeachToadAbilities/PeachToadAbilities.cpp -o PeachToadAbilities.o

(Note particularly that the architecture is ARMv5TE and the CPU is an ARM946E-S)
The following ASM is generated for the last function:
push    {r4, lr}
mov     r4, r0
mov     r1, #0x0
ldrd    r2, [r4, #0x5c]
ldr     ip, [r0, #0x98]
ldr     r0, [r0, #0x280]
lsl     ip, ip, #0x1
str     ip, [r4, #0x98]
ldr     ip, [r4, #0x64]
sub     sp, sp, #0x10
strb    r1, [r4, #0x27d]
add     r3, r3, #0x48000
str     r1, [sp, #0x8]
str     r1, [sp, #0x4]
str     ip, [sp]
mov     r1, #0x4a
bl      _ZN8Particle6System3NewEjj5Fix12IiES2_S2_PK11Vector3_16fPNS_8CallbackE
str     r0, [r4, #0x280]
add     sp, sp, #0x10
pop     {r4, pc}

For context, this is a piece of a ROM hack of a Nintendo DS game. The Player structure is 4-byte aligned, and at offset 0x5C is the player's position, which is a structure of 3 Fix12<int> (A Fix12<int> is a structure of 1 4-byte integer.).
The problem is that gcc generates an "ldrd" instruction that cannot be proven to access an 8-byte aligned address (It shouldn't know where "player" is and besides, 0x5C is not a multiple of 8.). The ARM documentations that I've looked at say that for ARMv5, loading a misaligned doubleword is undefined behavior. However, no$gba and DeSmuME assume that such an access when the address is 4-byte aligned still loads an 8-byte value from that address. Is this correct behavior for ARMv5TE on an ARM946E-S CPU? (I haven't tested this on an actual DS because I don't have a flash card.)

A: I have also seen this with ARMv5TE and ARM946E-S and GCC 6 ( was OK in 5). In my case, the code was loading two consecutive elements of an array, but there is no way for the compiler to prove that the array pointer passed in was 8-byte aligned. I will try to generate a simple example and report this. You should do the same in the hope it will be fixed.

A: Most probably the class instances are aligned to certain bytes (64 bytes for example), and the header isn't a multiple of eight bytes, hence the member variables are packed in a location starting at an "unaligned" address so that combined with an "unaligned" offset such as 0x5c, the address is guaranteedly 8 bytes aligned.
Compilers aren't perfect, but I cannot imagine them doing such trivial mistakes.
So don't worry.


text:
Q: How to deploy the contents of container build by docker-compose after all containers are ready to remote server? I have a fine working docker-compose for my local environment to work and play around with. the docker compose will add my website, mysql, and some other things in order to make everything work.
All the necessary files are now in one of my docker containers, and i can
docker cp container_name:/var/www/html/. dist/

to have my files on my local machine in the dist directory, where I am able to transfer the files to my server.
The next step is to automate the whole process, for what i want to use Jenkins.
Its not the first time that I use Jenkins, but for some reason I cannot get this to work.
I checkout my project from SCM into Jenkins, and be able to run docker-compose up --build, but when i dont use the -d parameter it will become stuck in this command line, since docker-compose up --build will only terminate with CTRL+C, therefore I use the -d parameter.
Afterwards i use
docker cp container_name:/var/www/html/. dist/

to move the files into my Jenkins directory, but here lies the next problem: Since I use the -d parameter the docker cp command does not wait for the docker-compose up --build to be completely finished.
So I tried to use something like
docker-compose logs -f -t | sed '/^Almost ! Starting web server now$/ q'

after the build command to determine a point in the build process where I am confident that all the files and installations made by custom docker_run.sh etc. files are already executed.
But it doesn't work. Either the job never ends and gets stuck or my command doesn't exactly wait for the "Almost ! Starting web server now" line in the docker-compose logs and will directly copy the files without the docker_run.sh having done its modifications inside of the container.
This is my current jenkins shell script inside the deployment job for my project.
# Create a dist directory
mkdir dist

# Build Docker
docker-compose up -d --build

# Wait for the logs to output "Almost ! Starting web server now"
docker-compose logs -f -t | sed '/^Almost ! Starting web server now$/ q'

# Copy files from container to jenkins directory "dist"
docker cp container_name:/var/www/html/. dist/

# Stop the containers, as I dont need them anymore
docker-compose down

# Go into the dist folder
cd dist

# Send files to remote
rsync -aHAXx --numeric-ids -e "some_parameters_here" . ssh_user@ssh_ip:httpdocs

I expect docker-compose to start by jenkins and that jenkins waits until it is ready, then cp the files to jenkins directory, then sends to remote server.
Actual result, as stated above, is either a never ending job of Jenkins, or Jenkins sending the files from docker without docker being 100% built.

A: Here is an excerpt of one of our groovy based pipeline build steps with the sensitive bits replaced. This pipeline actually has 14 containers in it:
Under pipeline --> configure, select either pipeline script or pipeline from scm.
pipeline.groovy
pipeline {
  environment {
    registry = "fqdn.to.our.private.docker.repo"
  }
  agent any
  stages {
    stage('Cloning Git') {
        steps {
            git(
                branch: 'develop',
                credentialsId: 'jenkins-user-ssh-key-credentials-id',
                url: 'jenkinsuser@git_repo_server:/path/to/project/repo'
            )
        }
    }
    stage('Building Container1 image') {
      steps{
        script {
          container1Image = docker.build(registry + "/container1_name:tag", "-f path/to/dockerfile/for/this/container/Dockerfile ./docker/build/context/in/the/checked/out/repo/for/this/container")
        }
      }
    }
    stage('Deploy Container1 Image to Docker Repository') {
        steps {
            script {
            docker.withRegistry('https://fqdn.to.our.private.docker.repo', 'jenkins-credentials-to-access-the-docker-repo') {
                    container1Image.push()
                }
            }
        }
    }
    stage('Building Container2 image') {
      steps{
        script {
          container2Image = docker.build(registry + "/container2_name:tag", "-f path/to/dockerfile/for/this/container/Dockerfile ./docker/build/context/in/the/checked/out/repo/for/this/container")
        }
      }
    }
    stage('Deploy Container2 Image to Docker Repository') {
        steps {
            script {
            docker.withRegistry('https://fqdn.to.our.private.docker.repo', 'jenkins-credentials-to-access-the-docker-repo') {
                    container2Image.push()
                }
            }
        }
    }
  }
}


text:
Q: How to use named routes along with consumer in provider? I'm trying to route to a different page at a particular condition in consumer. Although after implementation, I'm getting the following error:
!_debugLocked: is not true.
Consumer<MyModel>(builder: (context, model, _) {
  if (model.data?.val != null)
    Navigator.of(context).pushNamed('/myRoute');
      return Container(
          child: model.isLoading
                 ? CircularProgressIndicator()
                 : Icon(
                     Icons.camera,
                     color: Theme.of(context).primaryColor,
                  ),
               )
            }


text:
Q: Error when using Custom User class inherited from IdentityUser I am using asp.net core 2.2.
When using a custom class for app user inherited from IdentityUser, register & password sign-in fails with message "SqlException: Invalid column name 'ApplicationUserId'."
Statrup.cs
 services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

Application User class
 public class ApplicationUser : IdentityUser
 {
 }

The database is standard identity generated with no custom columns added.

A: Try modifying your ApplicationDbContext like this:
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }
    }

Your default ApplicationDbContext is using IdentityUser as its user storage not ApplicationUser.


text:
Q: passing challenge (java i/0) try catch. i have passed all but one test case first : Java has built-in mechanism to handle exceptions. Using the try statement we can test a block of code for errors. The catch block contains the code that says what to do if exception occurs.
This problem will test your knowledge on try-catch block.
You will be given two integers x,y and  as input, you have to compute x/y . If  and  are not  bit signed integers or if  is zero, exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions.

i have passed all but one test case where it wants java.lang.ArithmeticException: / by zero for when the user inputs a 0. my catch outputs System.out.println("java.util.InputMismatchException");
how can i pass the last test case?
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    try{
        Scanner scan = new Scanner(System.in);
        int input1 = scan.nextInt();
        int input2 = scan.nextInt();
        scan.close();
        System.out.println(divideInput(input1,input2));
    }catch(Exception e){
         System.out.println("java.util.InputMismatchException");
    }

 }

  public static int divideInput(int input1, int input2)
  {
     int sum;
     sum = input1 / input2;
     return sum;
  }
}

A: Instead of catching every exception in one block:
catch(Exception e){
    // stuff
}

You can split out specific types of exceptions.
catch(ArithmeticException e){
    // stuff for ArithmeticException
}
catch(InputMismatchException e){
    // stuff for InputMismatchException
}

A: According to my understanding, you want to catch the ArithmeticException.
What I'm seeing in your code should work, but probably the site is executing only the method divideInput(.., ..).
I think you can wrap the code with try-catch block within divideInput method:
public static int divideInput(int input1, int input2) {
    try {
        return input1 / input2;
    } catch (Exception e) {
        System.out.println("java.util.InputMismatchException");
        throw new java.util.InputMismatchException(e);
    }
}

Hope this helps!

A: Got it running and passing all of the test case.

`import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    try{
    Scanner scan = new Scanner(System.in);
    int input1 = scan.nextInt();
    int input2 = scan.nextInt();
    scan.close();
    System.out.println(divideInput(input1,input2));
    }
        catch(ArithmeticException e){
    System.out.println("java.lang.ArithmeticException: / by zero");
}
catch(InputMismatchException e){
     System.out.println("java.util.InputMismatchException");
}

    }
  public static int divideInput(int input1, int input2)
        {
         int sum;
         sum = input1 / input2;
          return sum;
        }
    }`

A: You can catch it like below:-
//just use any one of these three statement
e.printStackTrace();
System.err.println(e.toString());
System.err.println(e.getMessage());


text:
Q: Getting values from nested JSON using AngularJS I am looping through a nested JSON object and I get stuck at accessing the sub items.
Here is a sample of the JSON file I am using. It passes the JSONLint test so it can be assumed it is OK.
JSON
[{
    "fleetcheckitemid": "1",
    "checkitemdesc": "Engine oil level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "2",
    "checkitemdesc": "Water level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "3",
    "checkitemdesc": "Brake fluid level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}]

I can access the "fleetcheckitemid"and "checkitemdesc" but I am unable to access the "answers": [{"fleetcheckitemid": "2","checkitemdesc": "Ok"},......values
In my controller I have the following code, but as soon as I hit the inner .each() loop I get an error: "TypeError: Cannot read property 'length' of undefined"
app.js
$http.get("http://mymadeupdomain/api/getfleetchecks.php?fleetid=" + $scope.newFleetIDValue).success(function(data)
{
    $scope.data = data;
    console.log("$scope.data: " + $scope.data); // WORKING - [object Object], ... [object Object]

    $scope.answersArray = [];
    console.log("$scope.answers: " + $scope.answers); // EMPTY ARRAY - NOT INITIALISED YET

    // Unable to access sub-items (answers) here
    $.each($scope.data, function(index, element)
    {
       var itemDescription = element.checkitemdesc;
       console.log("itemDescription: " + itemDescription); // WORKING - Engine Oil Level

       var fleetcheckitemid = element.fleetcheckitemid;
       console.log("fleetcheckitemid: " + fleetcheckitemid); // WORKING - 1....34

        $.each(this.answers, function(index, element)
        {
            var answers = element.answers;

            var fleetcheckid = element.fleetcheckid;
            console.log("element.fleetcheckid: " + element.fleetcheckid); // NOT WORKING
            console.log("fleetcheckid: " + fleetcheckid); // NOT WORKING
        });
    });
});

Where are I going wrong with this? Can it be the [] brackets around the answers in the JSON causing this?

A: other solution for your question.

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){

  $scope.data = [{
    "fleetcheckitemid": "1",
    "checkitemdesc": "Engine oil level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "2",
    "checkitemdesc": "Water level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}, {
    "fleetcheckitemid": "3",
    "checkitemdesc": "Brake fluid level",
    "answers": [{
        "fleetcheckid": "1",
        "checkvaluedesc": "Ok"
    }, {
        "fleetcheckid": "2",
        "checkvaluedesc": "Low"
    }, {
        "fleetcheckid": "3",
        "checkvaluedesc": "Top-Up Required"
    }]
}];

  angular.forEach($scope.data,function(value,key){
      console.log(value.fleetcheckitemid);
      console.log(value.checkitemdesc);
        angular.forEach(value.answers,function(v,k){
            console.log(v.fleetcheckid);
             console.log(v.checkvaluedesc);
          });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">

</div>

A: Do make for loop over $scope.answers instead of this.answers. Then do change the $.each 2nd parameter name which is the same as outer element variable. So when control in coming inside a function the
$.each($scope.answers, function(index, ele) {//also change variable here
   var answers = element.answers;
   var fleetcheckid = element.fleetcheckid;
   console.log("element.fleetcheckid: " + element.fleetcheckid);
   console.log("fleetcheckid: " + fleetcheckid); // NOT WORKING
}

Still not sure, how you are filling up values in $scope.answers?

A:  angular.forEach($scope.data, function(data1){
       console.log("fleetcheckitemid: " + data1.fleetcheckitemid); // WORKING - 1....34

        angular.forEach(data1.answers, function(data2)
        {
            console.log("element.fleetcheckid: " + data2.fleetcheckid); // NOT WORKING
            console.log("DESC: " + data2.checkvaluedesc); // NOT WORKING
        });
    });


text:
Q: @FontFace, using downloaded font I am trying to import a font that I downloaded to my code using @font-face, the text is reading right however it's bypassing the downloaded font in my font family and going straight to the backup font, "Cursive". I don't know why this is happening because I've triple checked that it is linked to the right folder. Please let me know any thoughts you might have. Thanks.
enter image description here

A: @font-face usage
With the @font-face rule,you do not have to use one of the "web-safe" fonts anymore like font-family:'Poppins','serif'.The will be Stored as a Local font like font-family : Times New Roman,serif
In the @font-face rule you must first define a name for the font (e.g. myFirstFont), and then point to the font file.
To use the font for an HTML element, refer to the name of the font (myFirstFont) defined in the font-family property:
@font-face {
      font-family: myFirstFont;
      src: url(sansation_light.woff);
    }

div {
  font-family: myFirstFont;
}


text:
Q: How to get rid of "Keras weights file saving" message Im currently working with Keras and creating Convolutional NN. I have been always creating an architecture using Sequential() and now I tried to do it in another way another way of creating an architecture. And now, whenever I execute my code it always outputs annoying message annoying message and I dont know how to get rid of this
There is no info about such problem on the internet, but I have tried to do this
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

but it doesnt work
UPDATE:
I have figured out that this message appears after I do this:
model = Model(input_, output)

And now I dont know why this message appears


text:
Q: When executing CGI, give me only plain text When I tried to execute CGI, it gives me only plain text.
I installed PHP5.3.11 with apache2
All of them were installed manually from source code, not from apt-get
## Apache2
./configure --prefix/=usr/loca/apache2
make
make install

## php5
./configure --prefix=/usr/local/php5 --with-apxs2=/usr/local/apache2/bin/apxs
make
make test
make install

The above are commands that I used to install apache2 and php5.
I guess my installation for apache2 and php5 is correct, since I can run php code on my server. So I tried to execute CGI script after properly, I guess, setting a configuration.
However it shows only plain text of CGI script.
###Start###

#!/usr/bin/perl -w
print "Content-type: text/html\r\n\r\n";
print "Hello there!
\nJust testing .
\n";

for ($i=0; $i<10; $i++){
    print $i."
";
}

###End###

perl is properly installed at /usr/bin/perl.
I set my httpd.conf like below.
<Directory "/usr/local/apache2/cgi-bin">
    Options +ExecCGI
    AddHandler cgi-script .cgi .pl
    Require all granted
</Directory>

I think cgi-php5 is installed correctly as well, since when I execute "php-cgi -h", it gives me a result.
And when I open phpinfo() through browser,
GATEWAY_INTERFACE is set to CGI/1.1
Any thing I am missing? I appreciate for your help.

A: I found the answer.
my mistake was on httpd.conf and it was really stupid mistake. :-(
I had to uncomment the following line.
LoadModule cgi-script blahblah
No one knows how many hour I spend for this stupid mistake :-(


text:
Q: Set Currency Depend on Country IP How to set currency depending on country's IP, means if customer selects India country on checkout step then currency should be set Indian Rupee automatically. My Default Currency is 'USD'.

A: Credits : Raphael at Digital Pianism
you can use Geo IP MAGENTO STORE SWITCHER BASED ON CUSTOMER LOCATION.
Follow this tutorial , you can find complete code here
I am posting code, just if link become 404 page
/* app/code/local/Atwix/Ipstoreswitcher/Helper/Data.php */
class Atwix_Ipstoreswitcher_Helper_Data extends Mage_Core_Helper_Abstract
{
    const DEFAULT_STORE = 'English';

    /**
     * countries to store relation
     * default is English
     * @var array
     */
    protected $_countryToStore = array(
        'FR' => 'French',
        'BE' => 'French',
        'CH' => 'French',
        'DE' => 'German',
        'AT' => 'German',
        'UK' => 'English',
        'US' => 'English',
        'UA' => 'English',
        'CN' => 'English',
        'JP' => 'English'
    );

    /**
     * get store view name by country
     * @param $country
     * @return bool
     */
    public function getStoreByCountry($country)
    {
        if (isset($this->_countryToStore[$country])) {
            return $this->_countryToStore[$country];
        }
        return self::DEFAULT_STORE;
    }
}

<!--app/code/local/Atwix/Ipstoreswitcher/etc/config.xml-->
<?xml version="1.0"?>
<config>
 ...
    <global>
    ...
    </global>
    <frontend>
        <events>
            <controller_action_postdispatch>
                <observers>
                    <atwix_ipstoreswitcher>
                        <class>atwix_ipstoreswitcher/observer</class>
                        <method>controllerActionPostdispatch</method>
                    </atwix_ipstoreswitcher>
                </observers>
            </controller_action_postdispatch>
        </events>
    </frontend>
</config>

/* app/code/local/Atwix/Ipstoreswitcher/Model/Observer.php */

class Atwix_Ipstoreswitcher_Model_Observer
{
    /**
     * redirects customer to store view based on GeoIP
     * @param $event
     */
    public function controllerActionPostdispatch($event)
    {
        $cookie = Mage::getSingleton('core/cookie');
        if ($cookie->get('geoip_processed') != 1) {
            $geoIPCountry = Mage::getSingleton('geoip/country');
            $countryCode = $geoIPCountry->getCountry();
            if ($countryCode) {
                $storeName = Mage::helper('atwix_ipstoreswitcher')->getStoreByCountry($countryCode);
                if ($storeName) {
                    $store = Mage::getModel('core/store')->load($storeName, 'name');
                    if ($store->getName() != Mage::app()->getStore()->getName()) {
                        $event->getControllerAction()->getResponse()->setRedirect($store->getCurrentUrl(false));
                    }
                }
            }
            $cookie->set('geoip_processed', '1', time() + 86400, '/');
        }
    }
}

A: You must care about checkout currency. GeoIP and auto switch store can help you change display currency based on country, but when customer checkout Magento will use base currency as default

A: I'm personally using this open source extension to detect a user's country and set the currency automatically.
https://github.com/chapagain/auto-currency-switcher


text:
Q: ZAP Attack proxy History Request ID is not consecutive I've used ZAP to intercept traffic .
Works nicely and I have a history  for my REQUEST - RESPONSE pairs like this:
ID      Req. TimeStamp                  Method     etc ..
...
1955    Tue Apr 05 15:42:47 CEST 2016   GET        https ://...
1971    Tue Apr 05 15:42:49 CEST 2016   GET        https ://...
1984    Tue Apr 05 15:43:30 CEST 2016   GET        https ://...
1998    Tue Apr 05 15:43:31 CEST 2016   GET        https ://...
...

How come the IDs are not consecutive ?

A: We have a FAQ for that :) https://github.com/zaproxy/zaproxy/wiki/FAQhistoryIdsMissing
Simon (ZAP Project Lead)


text:
Q: Redirect from one location with wilcards using htaccess I need help with how to use the htaccess when a folder and any subfolders get redirected to a new url.
Example: http:www.mysite.com/events/a-name-of-an-event  (the 'a-name-of-an-event' will vary)
to
http:www.mysite.com/fixtures/

A: You can use RedirectMatch directive in your DOCUMENT_ROOT/.htaccess file:
RedirectMatch 301 ^/events/ /fixtures/

OR using mod_rewrite:
RewriteEngine On
RewriteRule ^events/ /fixtures/ [L,R=301,NC]


text:
Q: Scala: How to access a shadowed function variable from an object I would like to make the following work:
def foo(x:Int = 1) = {
  object obj {
    val x = foo.this.x
  }
}

But I don't know how to reference x from within the object. Can this be done without renaming x in one of the two spots?
Renaming the variables may not be easy when, for example, foo is a widely used API function with x as a named variable, while obj extends a 3rd party trait that has x as an abstract member.

A: No, this is not possible. There is no way to identify the outer block of the function definition.
For your syntax to work foo would have to be an object with a member x. i.e. this works:
class foo{
  val x = 1
  object obj {
    val x = foo.this.x
  }
}

foo also could be a singleton object extending FunctionX, which gives you something very similar to a method. But it is probably easier to just rename one of the values.

A: It is not possible in Scala.
You write the code, so the easiest option will be to rename one of the xs and problem solved.
However, if from some reason you really need it - you can do a trick and create an object that will behave like your method
object Foo {
  self =>

  val x = 1

  def apply() = {
    object obj {
      val x1 = self.x
      val x2 = Foo.x
      // x1 == x2, just 2 different ways of doing this
    }
  }
}

Because the apply method is implemented you can use it as you would use a function Foo()

A: Why not just introduce a new variable that has the same value as foo's argument x, but is not shadowed?
def foo(x: Int): Unit = {
  val foo_x = x
  object obj {
    val x = 13
    def doStuff: Unit = printf("%d %d\n", x, foo_x);
  }
  obj.doStuff
}

foo(42)


text:
Q: using threads and pyGST in a wx python app OK, so I am writing an app, which plays music with the pyGST bindings.
This requires the use of threads to handle playback. The bindings library handles most of the thread control for me, which is nice(and what I was looking for in them).
Now, I don't have a full grasp on this concept, so I would be eager for some references. But the way I understand it, is I have to basically inform the app that it can use multiple threads.
I gathered this from the examples on the gstreamer site, where they use this call:
gtk.gdk.threads_init()
gtk.main()

according to here, this tells the app it can use multiple threads(more or less), which is where my above assumption came from.
That is the background. Now get this. I have placed those lines in my code, and they work fine. My app plays music rather than crashing whenever it tries. But something doesn't feel right.
In the examples that I got those lines from, they use gtk for the whole GUI, but I want to use wxWidgets, so it feels wrong calling this gtk function to do this.
Is there a wx equivalent to this? or is it ok to use this, and will it still work cross platform?
Also, I have to figure out how to kill all these threads on exit(which it does not do right now) I see how they do it in the example using a gtk method again, so again, looking for a wx equivalent.
PS: I think this(or the solution) may be related to the wx.App.MainLoop() function, but I am lost in trying to understand how this loop works, so again, good references about this would be appreciated, but I suppose not necessary as long as I have a good solution.

A: Try using this instead:
import gobject
gobject.threads_init()

I wonder how come it is not written in large print at the start of every python gstreamer plugin piece of documentation: it only took me several hours to find it.
A bit more details here.

A: I have no experience with pyGST, but the general advice for using threads and wxPython is to only update the GUI from the main thread (i.e. the thread that starts the MainLoop). See http://wiki.wxpython.org/LongRunningTasks for more information.

A: I have no experience with the python bindings, but I have had success using wxWidgets and GStreamer together on Windows.  The problem is that wxWidgets runs a Windows event loop while GStreamer uses a GLib event loop.  If you don't care about any of the GStreamer events, you shouldn't need to do anything.  However, if you care to receive any of the GStreamer events, you will have to run your own GLib event loop (GMainLoop) in a separate thread with a separate GMainContext.  Use gst_bus_create_watch to create a GST event source, add a callback to the source with g_source_set_callback, and then attach it to the main context of your GLib event loop with g_source_attach.  You can then handle the GST in the callback, for example, to forward the events to the wx main event loop.


text:
Q: Android Augmented Reality Pro AR 9: activity gets back when displays too many markers I'm using this very useful tutorial (https://github.com/RaghavSood/ProAndroidAugmentedReality) for developing a custom AR app.
It works pretty fine, but when I display markers extracted from a file folder (sometimes) the app gets blocked and restarts from the previous activity.
I suppose it's because of the big number of markers situated in the same point of the screen.
Infact, when I lower the radius, and then showing a littler number of markers, the activity continues to work.
Besides, I've tried to modify the function "getTextWidth()" as many people suggest on the net.
I don't know how to reduce the number of Markers drawn on the same point of the screen (so indipendently from reducing the radius). Can you suggest me something?  THANKS A LOT!!!!!
I show you the LocalDataSource.java modified:
package com.example.pointofinterests;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.example.pointofinterests.R;
import com.example.pointofinterests.IconMarker;
import com.example.pointofinterests.Marker;

/**
* This class should be used as a example local data source. It is an example of
* how to add data programatically. You can add data either programatically,
* SQLite or through any other source.
*
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public class LocalDataSource extends DataSource {

    private List<Marker> cachedMarkers = new ArrayList<Marker>();
    private static Bitmap icon = null;

    public LocalDataSource(Resources res) {
        if (res == null) throw new NullPointerException();
            createIcon(res);
    }

    protected void createIcon(Resources res) {
       if (res == null) throw new NullPointerException();
           icon = BitmapFactory.decodeResource(res, R.drawable.icon);
    }

    public List<Marker> getMarkers() {
        try{
        String TestoIDPercorsi = readFileAsString("/sdcard/Epulia/IDPercorsi.txt");
        if(TestoIDPercorsi==""){
           // DOING NOTHING
        }else {
            String[] IDPercorso = TestoIDPercorsi.split("#");
            for(int l=0; l<IDPercorso.length-1; l++){
                String TestoPercorso = readFileAsString("/sdcard/Epulia/Percorso" +          IDPercorso[l] + ".txt");
                if (TestoPercorso.equals("")){
                }else {
                    ArrayList<String> IDSTEPS2 = new ArrayList<String>();
                    String[] temp = TestoPercorso.split("#");
                    for (int j=1; j < temp.length; j++){
                        Log.d("RIGA_" + j + "_" + IDPercorso[l], temp[j]);
                        if(temp[j].substring(0,2).contains("P")){//POI
                            String[] POI = temp[j].split("\\|");
                            String id = POI[1];
                            String description = POI[2];
                            Double lat = Double.parseDouble(POI[3]);
                            Double lng = Double.parseDouble(POI[4]);
                            String type = POI[5];

                            Marker poi = new IconMarker(description, lat,lng, 0, Color.DKGRAY, icon);
                            cachedMarkers.add(poi);

                        }
                    }

                }
            }

        }
    }catch (Exception e){
        Log.e("EXCEPTION", "> " + e);
    }

    return cachedMarkers;
}

public static String readFileAsString(String filePath) {

    String result = "";
    File file = new File(filePath);
    if ( file.exists() ) {
       FileInputStream fis = null;
        try {
           fis = new FileInputStream(file);
            char current;
            while (fis.available() > 0) {
                current = (char) fis.read();
                result = result + String.valueOf(current);

            }

        } catch (Exception e) {
            Log.d("TourGuide", e.toString());
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ignored) {
            }
        }

   }
    return result;
    }

}

A: I would like to thank the Author of the Tutorial who helped me in fixing the problem.
I report his answer that soled my problem:
Not sure why you have that limitation but this should limit the number of Markers drawn on the screen.
In class AugmentedView.java
You can introduce a new member variable:
private static int MAX_NUM_TO_DRAW = 10;

Then in the method onDraw(Canvas canvas):
You can quit the drawing loop early.
        int i=0;
        ListIterator<Marker> iter = collection.listIterator(collection.size());
        while (iter.hasPrevious() && i<MAX_NUM_TO_DRAW ) {
            Marker marker = iter.previous();
            marker.draw(canvas);
            i++;
        }


text:
Q: TIMER 32-bit on pic32 can't use interrupts Hi I have a PIC32MX370F512L from microchip.
I want to use TIMER2 and TIMER3 as a 32-bit timer for interrupts.
I CAN use 16-bit Timer interrupt but CAN'T use 32-bit Timer interrupt, I will show you both codes:
16-bit timer:
void init16(){
T2CONbits.ON = 0;           //Timer disabled

T2CON = 0;      //Stop any 16-bit Timer2 operation

T2CONbits.T32 = 0;          //16 bit mode on, tmr2
T2CONbits.TCKPS = 0b100;    //prescaler
T2CONbits.TCS = 0;          //Select internal peripheral clock
PR2 = 0x0000FFFF;

TMR2 = 0;                   //Clear contents of TMR2

T2CONbits.ON = 1;           //Timer enable

//====INTERRUPT PART========
IEC0bits.T2IE   = 0;        //Disable interrupt
IPC2bits.T2IP = 1; //Priority 1
//IPC3bits.T3IS = 0; //Sub-priority 3

IFS0bits.T2IF = 0; //Interrupt flag putted at zero
//IFS0bits.T3IF = 0; //Interrupt flag putted at zero
IEC0bits.T2IE   = 1;        //Enable interrupt
}

32-bit timer:
void init32(){

T2CONbits.ON = 0;           //Timer disabled

T2CON = 0;      //Stop any 16/32-bit Timer2 operation
T3CON = 0;      //Stop any 16-bit Timer3 operation

T2CONbits.T32 = 1;          //32 bit mode on, tmr2 + tmr3
T2CONbits.TCKPS = 0b100;    //Prescaler
T2CONbits.TCS = 0;          //Select internal peripheral clock
PR2 = 0x000FFFFF;
//PR3 = 0;

TMR2 = 0;                   //Clear contents of TMR2 and TMR3

T2CONbits.ON = 1;           //Timer enable

//====INTERRUPT PART========
IEC0bits.T3IE = 0;        //Disable interrupt
IPC3bits.T3IP = 1; //Priority 1
//IPC3bits.T3IS = 0; //Sub-priority 0

IFS0bits.T3IF = 0; //Interrupt flag putted at zero
//IFS0bits.T3IF = 0; //Interrupt flag putted at zero
IEC0bits.T3IE = 1;        //Enable interrupt
}

main :
#include <stdio.h>
#include <stdlib.h>
#include <p32xxxx.h>
#include <plib.h>
#include "timer32Interrupt.h"
#include <xc.h>

/* Disable JTAG to use RA0 */
#pragma config JTAGEN = OFF
#pragma config FWDTEN = OFF //Watchdog disabled

/* Device Config Bits in DEVCFG1: */
#pragma config FNOSC = FRCPLL   //Fast RC Osc with PLL
#pragma config FSOSCEN = OFF    //Secondary Oscillator disabled
#pragma config POSCMOD = XT     //Primary Oscillator mode: Resonator, crystal or resonator
#pragma config OSCIOFNC = ON    //CLKO Output Signal Active on the OSCO Pin
#pragma config FPBDIV = DIV_2   //Peripheral Clock Divisor:  PBCLK is SYSCLK divided by 2

/* Device Config Bits in DEVCFG2: */
#pragma config FPLLIDIV = DIV_2 //PLL Input Divider
#pragma config FPLLMUL = MUL_20 //PLL Multiplier
#pragma config FPLLODIV = DIV_2 //System PLL Output Clock Divider: PLL Divide by 2

void main(){
    TRISA = 0;
    LATA = 0;
    LATAbits.LATA0 = 1;
    //LATAbits.LATA0 =~LATAbits.LATA0

    INTEnableSystemMultiVectoredInt();
    init32();
    //init16();

    while(1){
        int i = 0;
        if(TMR2 >= PR2 - 10 ){

            //LATAbits.LATA0 =~LATAbits.LATA0;
            //LATAbits.LATA2 =~LATAbits.LATA2;
            LATAINV = 0b10;
        }

    }

}

void __ISR(_TIMER_2_VECTOR, ipl1)Timer32Handler(void){
    LATAINV = 0b101;
    IFS0bits.T3IF = 0; //Interrupt flag putted at zero
    IFS0bits.T2IF = 0; //Interrupt flag putted at zero

}

The 16 bit implementation works and the 32 not, enabling interrupt on TIMER3 and not on TIMER2 is required in the data-sheet, section 14.3.4 of the timers.

A: Like said by @Sudhee for making the code work I should replace only this part:
_TIMER_2_VECTOR became _TIMER_3_VECTOR
void __ISR(_TIMER_3_VECTOR, ipl1)Timer32Handler(void){
    LATAINV = 0b101;
    IFS0bits.T3IF = 0; //Interrupt flag putted at zero
    IFS0bits.T2IF = 0; //Interrupt flag putted at zero

}


text: Q: Windows: Find the location of recently created or downloaded files How can I get information about recently created or downloaded files and directories at any location in the hard disk. I am developing the application in Qt on Windows.


text:
Q: Eventhandling and how to use itemListener for multiple items So I have 2 questions, the following classes regarding the questions I will ask are supplemented below:
1) If I have multiple JCheckBoxes, how can I use an itemListener to know when a specific JCheckBox is selected.
(In the example below, I have 3 JCheckBoxes named petrol, Electric & diesel, if petrol is chosen how can I be aware of this, I want to do something like, if petrol is selected then remove some items from the JComboBox)
2) How can I make the progress bar increase or decrease when a JButton is clicked. In the code below I have a JProgressBar, when the user clicks drive I want the JProgressBar to decrease and when they select refuel I want the JProgressBar to increase. I sort of want the JProgressBar to represent the fuel Level of the car. How would I go about doing this?
Class 1
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;

public class CarViewer extends JFrame{

//row1
JPanel row1 = new JPanel();
JButton drv = new JButton("Drive");
JButton park = new JButton("Park");
JButton refuel = new JButton("Refuel");
//row2
JPanel row2 = new JPanel();
JLabel carTypeTag = new JLabel("Car Model:", JLabel.RIGHT);
JComboBox<String> options = new JComboBox<String>();
JCheckBox petrol = new JCheckBox("Petrol");
JCheckBox Electric = new JCheckBox("Electric");
JCheckBox diesel = new JCheckBox("Diesel");
JLabel fuelTypeTag = new JLabel("Fuel Type: ", JLabel.RIGHT);
ButtonGroup groupFuelType = new ButtonGroup();
//row3
JPanel row3 = new JPanel();
JLabel costTag = new JLabel("Cost:", JLabel.RIGHT);
JTextField costField = new JTextField(10);
JLabel engTag = new JLabel("Engine Size: ", JLabel.RIGHT);
JTextField engField = new JTextField(5);
JLabel mileageTag = new JLabel("Mileage: ", JLabel.RIGHT);
JTextField mField = new JTextField(10);
JLabel tankSizeTag = new JLabel("Tank size: ", JLabel.RIGHT);
JTextField tSField = new JTextField(5);
//row4
JPanel row4 = new JPanel();
JProgressBar petTank = new JProgressBar();
//row5
JPanel row5 = new JPanel();
JButton reset = new JButton("Reset");

public CarViewer(){
    super("Analyse A Car - AAC");
    setSize(400,800);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    GridLayout layoutMaster = new GridLayout(6, 1, 10, 20);
    setLayout(layoutMaster);
    ////Initial Errands
    groupFuelType.add(petrol);
    groupFuelType.add(diesel);
    groupFuelType.add(Electric);
    Dimension buttonDimension = new Dimension(80,30);
    Dimension resetButtonX = new Dimension(150,100);
    drv.setPreferredSize(buttonDimension);
    park.setPreferredSize(buttonDimension);
    refuel.setPreferredSize(buttonDimension);
    petTank.setMinimum(0);
    petTank.setMaximum(100);

            ///Adding Car Models to Dropdown (JComboBox)
            options.addItem("Mercedes C63 AMG");
            options.addItem("BMW i7");
            options.addItem("Jaguar XFR");
            options.addItem("Nissan Skyline R35 GTR 4");
            EmptyBorder empty0 = new EmptyBorder(60, 0, 440, 0); //empty Border;
            EmptyBorder empty2 = new EmptyBorder(50,40,0,120); //empty Border row 3;
            EmptyBorder empty4 = new EmptyBorder(80,0,0,0);
            //Errands Complete

        CarEvent handler = new CarEvent();

        //Adding Listeners
        drv.addActionListener(handler);
        park.addActionListener(handler);
        refuel.addActionListener(handler);
        reset.addActionListener(handler);
        options.addItemListener(handler);
        petrol.addItemListener(handler);
        Electric.addItemListener(handler);
        diesel.addItemListener(handler);
        //Listeners Added.

    FlowLayout layout0 = new FlowLayout();
    row1.setLayout(layout0);
    row1.add(drv);
    row1.add(park);
    row1.add(refuel);
    row1.setBorder(empty0);
    add(row1);

    GridLayout layout1 = new GridLayout(1, 3, 40, 50);
    row2.setLayout(layout1);
    row2.add(carTypeTag);
    row2.add(options);
    row2.add(fuelTypeTag);
    row2.add(petrol);
    row2.add(diesel);
    row2.add(Electric);
    add(row2);

    GridLayout layout2 = new GridLayout(1, 4, 20, 0);
    row3.setLayout(layout2);
    costField.setEditable(false);
    engField.setEditable(false);
    tSField.setEditable(false);
    mField.setEditable(false);
    row3.add(costTag);
    row3.add(costField);
    row3.add(engTag);
    row3.add(engField);
    row3.add(tankSizeTag);
    row3.add(tSField);
    row3.add(mileageTag);
    row3.add(mField);
    row3.setBorder(empty2);
    add(row3);

    FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER);
    row4.setLayout(layout3);
    row4.setBorder(empty4);
    row4.add(petTank);
    add(row4);

    FlowLayout layout4 = new FlowLayout(FlowLayout.CENTER);
    row5.setLayout(layout4);
    reset.setPreferredSize(resetButtonX);
    row5.add(reset);
    add(row5);

    setVisible(true);

}

public static void main(String[] args){
    CarViewer gui = new CarViewer();
}
}

Event handling class (2):
    import java.awt.event.*;

public class CarEvent implements ActionListener, ItemListener {

public void actionPerformed(ActionEvent event){
    String cmd = event.getActionCommand();
    if(cmd.equals("Drive"));{

    }
    else if(cmd.equals("Park")){

    }
    else if(cmd.equals("Refuel")){

    }

    else if(cmd.equals("Reset")){

    }
}

public void itemStateChanged(ItemEvent event){
    Object identifier = event.getItem();
    String item = identifier.toString();

    if())
}

}

A: For the check box question the below code may help you.

*

*Use the CarEvent class as a inner class to CarViewer.

*In the CarViewer add the event to each control
public class CarViewer extends JFrame {
    petrol.addItemListener (new CarEvent());
    Electric.addItemListener (new CarEvent());
    diesel.addItemListener (new CarEvent());

class CarEvent implements ActionListener, ItemListener {

@Override
public void actionPerformed(ActionEvent e) {
    System.out.println(e.toString());
}

@Override
public void itemStateChanged(ItemEvent e) {
    if (e.getItem().equals(petrol)) {
        System.out.println("Petrol");
    }
    else if (e.getItem().equals(Electric)) {
        System.out.println("Electric");
    }
    else if (e.getItem().equals(diesel)) {
        System.out.println("Diesel");
    }
}
} //CarEvent class

} //CarViewer class
If you want to use the CarEvent as a separate class then you need to pass the CarViewer class instance to this CarEvent class and access the check boxes (when the check boxes as public)
public class CarViewer extends JFrame {
    petrol.addItemListener (new CarEvent(this));
    //and so on ,,,,
}//CarViewer class

class CarEvent implements ActionListener, ItemListener {
      CarViewer cv:
      public CarEvent(CarViewer _object){
            cv=_object;
      }

      @Override
public void actionPerformed(ActionEvent e) {
    System.out.println(e.toString());
}

@Override
public void itemStateChanged(ItemEvent e) {
    if (e.getItem().equals(cv.petrol)) {
        System.out.println("Petrol");
    }
    else if (e.getItem().equals(cv.Electric)) {
        System.out.println("Electric");
    }
    else if (e.getItem().equals(cv.diesel)) {
        System.out.println("Diesel");
    }
}
    }//CarEvent class


text:
Q: Play series of Animated GIF Images on Mouse Hover using Pure JavaScript I have a requirement where I have an <image> tag linked to a series of animated gif images.
I want to play those animations (gif) on mouse over state, one after another (like a playlist). Then on mouse Out I want to return to some original img source (like a static poster image, waiting for user rollover state).
Please find pseudo code below that I have tried:
function nextSlide() {
    document.getElementsByTagName('img').setAttribute('src', slides[currentSlide]);
    currentSlide = (currentSlide + 1) % slides.length;
}

document.getElementsByTagName('img').addEventListner('mouseover',function(){
    slides = gifImages;
    var slideInterval = setInterval(nextSlide,1000);
});
   document.getElementsByTagName('img').addEventListener('mouseout', function(){
        document.getElementsByTagName('img').src = originalImage;
    });

Challenges (to  fix) from using above code:
1. I want gif image to be replaced only after its animation is completed, but its getting replaced after every delay of timer as I am using setInterval.
2. On mouse out it is not returning to original image.
3. First image is also being loaded after 1 sec (since that's rate of setInterval).
Please let me know if there is any way to achieve this.
Update:

*

*Issues 2 and 3 is resolved. Now only issue I am facing is to play collection of gif images.

A: After lot of hours I got answer to my own question.
I got a code snippet to get duration of GIF Image. And once I have duration of GIF image I can set interval after duration of GIF images.
    function getGIF(url) {
    function downloadFile(url, success) {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'arraybuffer';
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (success) {
                    success(xhr.response);
                }
                 const file = new Blob([xhr.response], {type:'image/jpeg'});
            }
        };
        xhr.send(null);
    }

    downloadFile(url, function (data) {
        let d = new Uint8Array(data);

        let bin = null;
        let duration = 0;
        for (let i = 0; i < d.length; i++) {
            bin += String.fromCharCode(d[i]);

            // Find a Graphic Control Extension hex(21F904__ ____ __00)
            if (d[i] === 0x21 &&
                d[i + 1] === 0xF9 &&
                d[i + 2] === 0x04 &&
                d[i + 7] === 0x00) {
                // Swap 5th and 6th bytes to get the delay per frame
                let delay = (d[i + 5] << 8) | (d[i + 4] & 0xFF);

                // Should be aware browsers have a minimum frame delay
                // e.g. 6ms for IE, 2ms modern browsers (50fps)
                duration += delay < 2 ? 10 : delay;
            }
        }
    });
    return duration;
}

 Thanks to codepen from where I got the solution: LINK
REFERENCE:

*

*http://justinsomnia.org/2006/10/gif-animation-duration-calculation/

*http://www.w3.org/Graphics/GIF/spec-gif89a.txt

A: To load the GIF duration you can use gify. Then on mouseover you change the image and set a timeout function that changes the image with the current GIFs duration.
(function () {
    var slideUrls = [
        'https://media.giphy.com/media/9zXWAIcr6jycE/giphy.gif',
        'https://media.giphy.com/media/3ohzdFhIALkXTBxPkQ/giphy.gif'
    ];
    var originalUrl = 'http://via.placeholder.com/350x150';

    // Loads the duration information for each GIF
    var gifDurations = {};
    function loadDurations(i) {
        if (i >= slideUrls.length) return;

        var blob = null;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", slideUrls[i]);
        xhr.responseType = 'blob';

        xhr.onload = function () {
            blob = xhr.response;
            var reader = new FileReader();

            reader.onload = function (event) {
                var gifInfo = gify.getInfo(reader.result);
                gifDurations[slideUrls[i]] = gifInfo.duration;
                loadDurations(i + 1)
            }

            reader.readAsArrayBuffer(blob);
        }
        xhr.send();
    }
    loadDurations(0);

    var element = document.getElementById('id');
    var timeout;
    var currentSlide = 0;

    function nextSlide() {
        var url = slideUrls[currentSlide];
        var duration = gifDurations[url];
        element.setAttribute('src', slideUrls[currentSlide]);
        currentSlide = (currentSlide + 1) % slideUrls.length;

        timeout = setTimeout(function () {
            nextSlide();
        }, duration);
    }

    element.addEventListener('mouseover', function () {
        nextSlide();
    });

    element.addEventListener('mouseout', function () {
        clearTimeout(timeout);
        element.src = originalUrl;
    });

})();

A: Using jQuery .hover() with one static image and one .gif - JSFiddle
Had a good read on this thread first before writing this.

$("#gifdiv").hover(
  function () {
    $(this).find("img").attr("src", "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif");
    }, function() {
     $(this).find("img").attr("src", "https://lh4.googleusercontent.com/__LWblq_sBitgvSmldccaKsEqt0ADBGpPmYFsl3l0Jkxenqti4Jt05EN9EUJPDlHrM5DprN2-hrX3MM=w1680-h944");
    }
);


text:
Q: how to change the unix PATH value in php environment I've recently installed a composer library which heavily relies on the unix $PATH variable being set correctly.
Usually this isn't an issue, but unfortunately there is no way for me to override the functionality of this library.
Currently, when I echo out the $PATH, PHP will spit out:

/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.

When it needs to be:

/usr/local/bin

After searching around for a bit, I came across the dotenv library as a potential solution using $_ENV["PATH"] = "...". However, this didn't work.
Following that, I attempted to simply execute this at the top of my initialisation file:
exec("PATH=/usr/local/bin")
echo shell_exec("echo $PATH");

Also to no avail.
So, how would one do this within PHP? Specifically in a MAMP environment on OSX. Is there a config setting I can change?

A: If you need to do it with PHP in the PHP environment, you can use putenv().
putenv("PATH=/usr/local/bin");

Or if you just want to prepend your path
$oldpath = getenv('PATH');
putenv("PATH=/usr/local/bin:$oldpath");


text:
Q: How to make circle as table using konva react Need help, how to make custom circle like this enter image description here
and will adjust to the middle circle (the big circle) if I add a small circle as the chair.
iam using konvaJS.
Thanks in advance.

A: This is a plain JS solution to the question about adding seats and moving current seats appropriately. The math is simple - divide 360 by the number of seats to get the angle for each seat then iterate per seat calculating the X, Y position via the angle math, noting that JS Math lib works in radians.  Hopefully you can wrangle this into reactjs.
Snipped best viewed full screen. Also available at CodePen

// These are the main parameters of the image
let seats = 4, tableRadius = 150;
const radmult = Math.PI / 180;

// Set up a stage
let stage = new Konva.Stage({
        container: 'container',
        width: window.innerWidth,
        height: 500
      }),

    // add a layer to draw on
    seatLayer = new Konva.Layer(),

    tableLayer = new Konva.Layer(),

    // Add a circle to act as the table
    tableCircle = new Konva.Circle({name: 'table', x: 200, y: 200, radius: 120, fill: 'magenta', stroke: 'black', strokeWidth: 4 });

    // Add a circle to act as a positioner for the seats.
    seatPos = new Konva.Circle({name: 'seatPos', x: 200, y: 200, radius: 150, fill: 'transparent', stroke: 'black', strokeWidth: 4 });

 tableLayer.add(tableCircle);
 seatLayer.add(seatPos);
 stage.add(seatLayer);
 stage.add(tableLayer);

// function to lay out the seats
function layout() {

  let angle = 360 / (seats);

  // Clear current seats
  var shapes = seatLayer.find('.seat').destroy();

  // draw new seats
  for (var i = 0; i < seats; i++){

    let posAngle = angle * i,
        x = 200 + (tableRadius * Math.sin(posAngle * radmult)),
        y = 200 + (tableRadius * Math.cos(posAngle * radmult));

    let c = new Konva.Circle({name: 'seat', x: x, y: y, radius: 40, fill: 'cyan', stroke: 'black', strokeWidth: 4});

    seatLayer.add(c);

  }

  seatLayer.draw();
}

// initial draw so we can see something
layout();
stage.draw()

// Listeners on buttons to add & remove seats
$('#add').on('click', function(){

  seats = seats + 1;
  layout();

})

$('#remove').on('click', function(){

  if (seats > 0) {
    seats = seats - 1;
    layout();
  }

})
body {
  margin: 10;
  padding: 10;
  overflow: hidden;
  background-color: #f0f0f0;
}

  <button id = 'add'>Add seat</button>
  <button id = 'remove'>Remove seat</button>


text:
Q: How to preserve the reference of elements from a collection for O(1) accessibility in Java I'm new to Java. I tried to store iterators of LinkedList elements in a Map, and delete them later:
Map<Integer, Iterator<Integer>> map = new HashMap<>();
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(1);
map.put(1, list.iterator());
list.addFirst(2);
map.put(2, list.iterator());

Iterator<Integer> iter = map.get(1);
iter.next();
iter.remove(); // list is supposed to be [2]

However, ConcurrentModificationException occurs. I think as soon as I add '2' in the list, the iterator of '1' expires, right?
In C++, list<int>::iterator represents the pointer of a node from a linked list, which stays constant and available whenever new nodes are inserted into the list. I'm a little bit confused about this in Java.

Sorry for the confusion. Now I know that Iterator is usually used in iterations, not to 'locate' an element, which is a bit different from that in C++.
I actually try to preserve the reference of elements from a linked list, so that the elements can be efficiently accessible in a complexity of O(1) instead of O(n).
Is there any related kind of Collection or Util? Or maybe I have to implement DeLinkedList and DeLinkedNode by myself. Thanks in advance.

A: If you want the ordering and O(1) insertion and removal of a linked list, coupled with the O(1) lookup of a hash table, LinkedHashSet is likely your best bet.
A LinkedHashSet is a Set that preserves insertion order. So you can do things like:
import java.util.LinkedHashSet;

...

LinkedHashSet<Integer> set = new LinkedHashSet();
set.add(2);
set.add(1);

set.remove(1);

A couple of caveats:

*

*This is a Set, so you won't be able to keep more than one copy of an element.

*There is no addFirst equivalent. Items are always added to the end.

A: Instead of using LinkedList, use ConcurrentLinkedDeque. The iterators will then work as you are hoping.
If you need the List functionality, as opposed to just iterators, you can very easily use the AbstractSequentialList class to create a List implementation from your ConcurrentLinkedDeque.


text:
Q: Cancelling a Socket.xxxxAsync call After calling Socket.Shutdown, Socket.Close and Socket.Disconnect, it appears that Socket.ReceiveAsync does not abort. Attempts to reuse the SocketAsycEventArgs object used in the ReceiveAsync call (suggested in the documentation as best practice) result in the error:

An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance

What do I have to do to get ReceiveAsync to release its grip on this SocketAsyncEventArgs instance?
Edit:I have worked around this by flagging a pending receive and not doing any cleanup until the receive comes in (i.e Completed is dispatched). Doesn't feel too good though. Can't it just be aborted, like the WebRequest API?

A: There does not appear to be a way to abort the asynchronous receive.
When the socket is closed, this forces the receive to complete, and the SocketError property of the SocketAsyncEventArgs parameter to your callback method will have a value of SocketError.OperationAborted.  When this condition is encountered, you can return the SocketAsyncEventArgs object to the reusable pool.
This is demonstrated in the example shown here.  Specifically, look at the ProcessReceive() method, which calls the CloseClientSocket() method when e.BytesTransferred == 0 or e.SocketError != SocketError.Success.  The CloseClientSocket() method is where the SocketAsyncEventArgs object is returned to the pool.

A: Most likely cause is when reusing SocketAsyncEventArgs that you are calling:
SAE.Completed += new EventHandler(SocketEventArg_Completed);
Doing so will cause your callback to be called multiple times!!!
Be sure to only set Completed handler once.


text:
Q: Get columns with distinct value counts greater than a specified value Imagine the following Python Pandas Dataframe:
df = pd.DataFrame({'id' : ['foo', 'bar', 'foo'], \
                   'A' : ['property1', 'property1', 'property2'], \
                   'B' : ['test', 'test', 'test'] })
from tabulate import tabulate
print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+------+------+
|    | A         | B    | id   |
|----+-----------+------+------|
|  0 | property1 | test | foo  |
|  1 | property1 | test | bar  |
|  2 | property2 | test | foo  |
+----+-----------+------+------+

Here you can see that for the id "foo" column B has only one unique (distinct) value, which is test. But for column A it has two distinct values property1 and property2. For the id "bar" both columns have only one distinct value.
What I'm looking for is code that gives me the name of those columns where the count is larger than 1 if grouped by id. So the result should be the name of column A since is hold non-distinct values.
df.groupby(['id'])

I only know how to get the ID's for which the count (occurance) is larger than 1. But it's not what I'm ultimately looking for.
df['id'].value_counts().reset_index(name="count").query("count > 1")["id"]

Thanks for any hint.

A: Use:
#filter column of interest
a = (df.groupby(['id'])['A','B'].nunique() > 1).any()

print (a)
A     True
B    False
dtype: bool

#if need test all columns without id
a = (df.set_index('id').groupby('id').nunique() > 1).any()
print (a)
A     True
B    False
dtype: bool

Last filter:
b = a.index[a]
print (b)
Index(['A'], dtype='object')

A: Maybe you're looking for:
g = df.groupby('id')['A', 'B'].nunique()
g

     A  B
id
bar  1  1
foo  2  1

To get the relevant columns, just index into df.columns:
df.columns[(g > 1).any()]
Index(['A'], dtype='object')

A: UPDATE:
In [98]: df.columns.drop('id')[(df.groupby('id')[df.columns.drop('id')].nunique() > 1).any()]
Out[98]: Index(['A'], dtype='object')

In [31]: df[['A','B']].columns[df.groupby(['id'])['A','B'].apply(lambda x: x.nunique().gt(1)).any()]
Out[31]: Index(['A'], dtype='object')

Explanation:
In [32]: df.groupby(['id'])['A','B'].apply(lambda x: x.nunique().gt(1))
Out[32]:
         A      B
id
bar  False  False
foo   True  False

In [33]: df.groupby(['id'])['A','B'].apply(lambda x: x.nunique().gt(1)).any()
Out[33]:
A     True
B    False
dtype: bool

A: Here is another way
pd.crosstab(df.id,[df.A,df.B],margins =True)
Out[206]:
A   property1 property2 All
B        test      test
id
bar         1         0   1
foo         1         1   2
All         2         1   3

Or something like
[x if df.groupby(['id',x]).ngroup().max()>1 else np.nan for x in df.columns]
Out[233]: ['A', nan, nan]


text:
Q: Which row does MySQL naturally "choose" when doing a GROUP BY? How does MySQL decide which row's value to use when grouping?
id |  type |     timestamp
-------------------------------
1  |   3   | 2014-09-10 17:03:43
2  |   7   | 2014-09-10 17:15:00
3  |   18  | 2014-09-10 17:17:55
4  |   9   | 2014-09-10 18:01:30
5  |   18  | 2014-09-10 18:02:29
6  |   3   | 2014-09-10 18:06:26
7  |   3   | 2014-09-10 18:06:30

For example:
SELECT * FROM mytable GROUP BY type

This has implications where the timestamp is concerned.
Does it use the first one, the last, something determined via internal workings?

A: Without aggregate functions(MIN,MAX,SUM etc.) on the columns not in GROUP BY,mysql will return indeterminate values.In other databases this is not even allowed.

The server is free to choose any value from each group, so unless they
  are the same, the values chosen are indeterminate

However you can enable ONLY FULL GROUP BY mode.


text:
Q: Oracle will not start after VM crash My Oracle 11gR2, running on a VM, crashed when the datastore of the host filled up. I got the VM to start and as I'm trying to start the DB, I see this:
Connected to an idle instance.
SQL> startup
ORACLE instance started.

Total System Global Area 1987563520 bytes
Fixed Size                  2229704 bytes
Variable Size            1476397624 bytes
Database Buffers          503316480 bytes
Redo Buffers                5619712 bytes
Database mounted.
ORA-01092: ORACLE instance terminated. Disconnection forced
ORA-00450: background process 'QMNC' did not start
ORA-00443: background process "QMNC" did not start
Process ID: 3929
Session ID: 1 Serial number: 5

The alert log contains this:
ALTER DATABASE   MOUNT
Successful mount of redo thread 1, with mount id 1615598463
Database mounted in Exclusive Mode
Lost write protection disabled
Completed: ALTER DATABASE   MOUNT
Fri Nov 05 12:43:47 2021
ALTER DATABASE OPEN
Beginning crash recovery of 1 threads
Started redo scan
Completed redo scan
 read 5129 KB redo, 867 data blocks need recovery
Started redo application at
 Thread 1: logseq 16580, block 11139
Recovery of Online Redo Log: Thread 1 Group 2 Seq 16580 Reading mem 0
  Mem# 0: /home/oracle/u01/app/oracle/oradata/orcl/redo02.log
Completed redo application of 2.76MB
Completed crash recovery at
 Thread 1: logseq 16580, block 21398, scn 406093127
 867 data blocks read, 860 data blocks written, 5129 redo k-bytes read
Thread 1 advanced to log sequence 16581 (thread open)
Thread 1 opened at log sequence 16581
  Current log# 3 seq# 16581 mem# 0: /home/oracle/u01/app/oracle/oradata/orcl/redo03.log
Successful open of redo thread 1
MTTR advisory is disabled because FAST_START_MTTR_TARGET is not set
SMON: enabling cache recovery
[3929] Successfully onlined Undo Tablespace 2.
Undo initialization finished serial:0 start:4294873730 end:4294873790 diff:60 (0 seconds)
Verifying file header compatibility for 11g tablespace encryption..
Verifying 11g file header compatibility for tablespace encryption completed
SMON: enabling tx recovery
Database Characterset is AL32UTF8
No Resource Manager plan active
replication_dependency_tracking turned off (no async multimaster replication found)
Starting background process QMNC
Process QMNC died, see its trace file
Errors in file /home/oracle/u01/app/oracle/diag/rdbms/orcl/ORCL/trace/ORCL_ora_3929.trc:
ORA-00443: background process "QMNC" did not start
Errors in file /home/oracle/u01/app/oracle/diag/rdbms/orcl/ORCL/trace/ORCL_ora_3929.trc:
ORA-00450: background process 'QMNC' did not start
ORA-00443: background process "QMNC" did not start
Errors in file /home/oracle/u01/app/oracle/diag/rdbms/orcl/ORCL/trace/ORCL_ora_3929.trc:
ORA-00450: background process 'QMNC' did not start
ORA-00443: background process "QMNC" did not start
Error 450 happened during db open, shutting down database
USER (ospid: 3929): terminating the instance due to error 450
Instance terminated by USER, pid = 3929
ORA-1092 signalled during: ALTER DATABASE OPEN...
opiodr aborting process unknown ospid (3929) as a result of ORA-1092
Fri Nov 05 12:43:51 2021
ORA-1092 : opitsk aborting process

The trace file for QNMC shows this:
*** 2021-11-05 12:43:48.343
Completed recovery checkpoint
----- Recovery Hash Table Statistics ---------
Hash table buckets = 262144
Longest hash chain = 1
Average hash chain = 867/867 = 1.0
Max compares per lookup = 1
Avg compares per lookup = 26276/32586 = 0.8
----------------------------------------------
Recovery sets nab of thread 1 seq 16580 to 21398 with 8 zeroblks
kwqmnich: current time:: 10: 43: 48: 0
kwqmnich: instance no 0 repartition flag 1
kwqmnich: initialized job cache structure

*** 2021-11-05 12:43:49.876
Process QMNC is dead (pid=3931 req_ver=1 cur_ver=1 state=KSOSP_SPAWNED).
-------------------------------------------------------------------------------
Trace Bucket Dump Begin: default bucket for process 19 (osid: 3929)
TIME(*=approx):SEQ:COMPONENT:FILE@LINE:FUNCTION:SECT/DUMP: [EVENT#:PID:SID] DATA
-------------------------------------------------------------------------------
2021-11-05 12:43:48.876672 :80035B07:db_trace:ksb.c@2342:ksbs1p_real(): [10254:19:1] KSBS1P: process USER trying to start background QMNC
2021-11-05 12:43:48.876675 :80035B08:db_trace:ksb.c@2405:ksbs1p_real(): [10254:19:1] KSBS1P: process USER obtained PR enqueue to start background QMNC
2021-11-05 12:43:49.876615 :80035B3A:db_trace:ksb.c@2609:ksbs1p_real(): [10254:19:1] KSBS1P: out of loop: process did not start
-------------------------------------------------------------------------------
Trace Bucket Dump End: default bucket for process 19 (osid: 3929)
ORA-00443: background process "QMNC" did not start
ORA-00450: background process 'QMNC' did not start
ORA-00443: background process "QMNC" did not start
ORA-00450: background process 'QMNC' did not start
ORA-00443: background process "QMNC" did not start

*** 2021-11-05 12:43:49.900
USER (ospid: 3929): terminating the instance due to error 450

I was thinking of running a "startup mount" followed by a "recover database" but I don't want to take any chances.
Please help me get the database to start.


text:
Q: web2py how to make a list:reference of an other table in db.py I have an app tag and an app image.
How do I make a reference from image to the app tag database?
tag app db.py :
db.define_table('Tag',
   Field('Name', unique=True),
   format = '%(Name)s')

image app db.py :
db.define_table('Image',
   Field('Nom'),
   Field('Date_Creation',date),
   Field('Tag','list:reference Tag'),
   format = '%(Nom)s')

A: I think you're looking for many-to-many relationship; images can have many tags, tags can belong to many images.
So you would need another table to store this relationship between the two.
db.define_table('image_tag',
    Field('image', db.Image),
    Field('tag', db.Tag))

To get images and their tags:
images_tags = db((db.Image.id==db.image_tag.image) & (db.Tag.id==db.image_tag.tag))
for row in images_tags.select():
    print row.Image.Nom, row.Tag.Name


text:
Q: Extracting time in JavaScript singular/plural inconsistencies In JavaScript, when extracting time: What's the reason for the getFullYear, getMonth, getDay being singular but from getHours down the method title is plural? I know it doesn't really matter, but I keep on missing and adding 's' and understanding the reasoning behind it would help me to remember better.
Thanks in advance.


text:
Q: Migrate my questions If I were to post something, innocently, on the wrong site and became aware through my own observation or from the comments of others that another site was more appropriate for the question, am I able to migrate it myself or is that function only available to mods?

A: At present, the migration function is based off of the close mechanism, so either 5 people have to close it as "belongs on X" or a moderator has to do it. If you notice that you posted on the wrong site, just delete your question and post on the correct site, no harm done. However, if you already have some answers that you want to save, you can try and get it moved to the right site by editing your tags to say "belongs-on-X" and/or put a message at the top of the post requesting that it be moved.
Until users can flag their own posts, these are really the only tools that they can use to try and get some attention from moderators or users with the ability to close to move the post.
As a side note, if you see a post (not your own) that you think belongs on a different site, you can just flag it for moderator review, and, if you have closing power, close as "belongs on X".

A: It's only available to moderators and those with over 3000 rep (who can vote to close).
If you see a post that you think should be migrated, flag it as Requires Moderator attention and explain why.
If you can't flag your own post (see comments) then post a question here.

A: The function is only available to mods. Ideally you could flag your own question for moderator's attention, but I believe right now you cannot. The best you could do is post a comment indicating you believe it should be moved and asking others to help you out. Here is the feature request to be able to flag your own post.


text:
Q: Regex match pattern between tags plug a specific string I have this content
<something>; rel="previous", <something>; rel="next"

I want to match
<something>; rel="next"
This matches the entire line strangely
(<.+?>); rel="next"

Can anyone lend me a hand here?

A: You can use (<[^>]+>); rel="next" to avoid gobbling the whole line.