text:
Q: How to fit text to a precise width on html canvas? How can I fit a single-line string of text to a precise width on an html5 canvas? What I've tried so far is to write text at an initial font size, measure the text's width with measureText(my_text).width, and then calculate a new font size based on the ratio between my desired text width and the actual text width. It gives results that are approximately correct, but depending on the text there's some white space at the edges.
Here's some example code:
// Draw "guard rails" with 200px space in between
c.fillStyle = "lightgrey";
c.fillRect(90, 0, 10, 200);
c.fillRect(300, 0, 10, 200);

// Measure how wide the text would be with 100px font
var my_text = "AA";
var initial_font_size = 100;
c.font = initial_font_size + "px Arial";
var initial_text_width = c.measureText(my_text).width;

// Calculate the font size to exactly fit the desired width of 200px
var desired_text_width = 200;
new_font_size = initial_font_size * desired_text_width / initial_text_width;

// Draw the text with the new font size
c.font = new_font_size + "px Arial";
c.fillStyle = "black";
c.textBaseline = "top";
c.fillText(my_text, 100, 0, 500);

The result is perfect for some strings, like "AA":

But for other strings, like "BB", there's a gap at the edges, and you can see that the text doesn't reach to the "guardrails":

How could I make it so that the text always reaches right to the edges?

A: I had a similar problem in a project of mine. I needed to not only get the exact width of the text, but I also realised that if I rendered text at position X, it would sometimes flow to the left of X due to Side Bearings.
Try as I might, I couldn't get the DOM to give me those values, so I had to resort to SVG to accurately measure the text.
I ended up with the following solution to measure the text exactly, including the side bearing, or X offset that I would need to apply to get the pixels to appear in the right place.
This code has only been tested in Chrome and Firefox but should work in basically all modern browsers.
It also supports the usage of web fonts, which simply needs to be loaded into the page, and can then be referenced by name.

class TextMeasurer {
  constructor() {
    const SVG_NS = "http://www.w3.org/2000/svg";

    this.svg = document.createElementNS(SVG_NS, 'svg');

    this.svg.style.visibility = 'hidden';
    this.svg.setAttribute('xmlns', SVG_NS)
    this.svg.setAttribute('width', 0);
    this.svg.setAttribute('height', 0);

    this.svgtext = document.createElementNS(SVG_NS, 'text');
    this.svg.appendChild(this.svgtext);
    this.svgtext.setAttribute('x', 0);
    this.svgtext.setAttribute('y', 0);

    document.querySelector('body').appendChild(this.svg);
  }

  /**
   * Measure a single line of text, including the bounding box, inner size and lead and trail X
   * @param {string} text Single line of text
   * @param {string} fontFamily Name of font family
   * @param {string} fontSize Font size including units
   */
  measureText(text, fontFamily, fontSize) {
    this.svgtext.setAttribute('font-family', fontFamily);
    this.svgtext.setAttribute('font-size', fontSize);
    this.svgtext.textContent = text;

    let bbox = this.svgtext.getBBox();
    let textLength = this.svgtext.getComputedTextLength();

    // measure the overflow before and after the line caused by font side bearing
    // Rendering should start at X + leadX to have the edge of the text appear at X
    // when rendering left-aligned left-to-right
    let baseX = parseInt(this.svgtext.getAttribute('x'));
    let overflow = bbox.width - textLength;
    let leadX = Math.abs(baseX - bbox.x);
    let trailX = overflow - leadX;

    return {
      bbWidth: bbox.width,
      textLength: textLength,
      leadX: leadX,
      trailX: trailX,
      bbHeight: bbox.height
    };
  }
}

//Usage:
let m = new TextMeasurer();
let textDimensions = m.measureText("Hello, World!", 'serif', '12pt');
document.getElementById('output').textContent = JSON.stringify(textDimensions);

A: The problem you are facing is that TextMetrics.width represents the "advance width" of the text.
This answer explains pretty well what it is, and links to good resources.

The advance width is the distance between the glyph's initial pen position and the next glyph's initial pen position.

What you want here is the bounding-box width, and to get this, you need to calculate the sum of TextMetric.actualBoundingBoxLeft + TextMetric.actualBoundingBoxRight.
Note also that when rendering the text, you will have to account for the actualBoundingBoxLeft offset of the bounding-box to make it fit correctly.
Unfortunately, all browsers don't support the extended TextMetrics objects, and actually only Chrome really does, since Safari falsely returns the advance width for the bouding-box values.  For other browsers, we're out of luck, and have to rely on ugly getImageData hacks.

const supportExtendedMetrics = 'actualBoundingBoxRight' in TextMetrics.prototype;
if( !supportExtendedMetrics ) {
  console.warn( "Your browser doesn't support extended properties of TextMetrics." );
}

const canvas = document.getElementById('canvas');
const c = canvas.getContext('2d');
c.textBaseline = "top";

const input = document.getElementById('inp');
input.oninput = (e) => {

  c.clearRect(0,0, canvas.width, canvas.height);
  // Draw "guard rails" with 200px space in between
  c.fillStyle = "lightgrey";
  c.fillRect(90, 0, 10, 200);
  c.fillRect(300, 0, 10, 200);

  c.fillStyle = "black";
  fillFittedText(c, inp.value, 100, 0, 200) ;

};
input.oninput();

function fillFittedText( ctx, text = "", x = 0, y = 0, target_width = ctx.canvas.width, font_family = "Arial" ) {
  let font_size = 1;
  const updateFont = () => {
    ctx.font = font_size + "px " + font_family;
  };
  updateFont();
  let width = getBBOxWidth(text);
  // first pass width increment = 1
  while( width && width <= target_width ) {
    font_size++;
    updateFont();
    width = getBBOxWidth(text);
  }
  // second pass, the other way around, with increment = -0.1
  while( width && width > target_width ) {
    font_size -= 0.1;
    updateFont();
    width = getBBOxWidth(text);
  }
  // revert to last valid step
  font_size += 0.1;
  updateFont();

  // we need to measure where our bounding box actually starts
  const offset_left = c.measureText(text).actualBoundingBoxLeft || 0;
  ctx.fillText(text, x + offset_left, y);

  function getBBOxWidth(text) {
    const measure = ctx.measureText(text);
    return supportExtendedMetrics ?
      (measure.actualBoundingBoxLeft + measure.actualBoundingBoxRight) :
      measure.width;
  }

}
<input type="text" id="inp" value="BB">
<canvas id="canvas" width="500"></canvas>

A: Measuring text width
Measuring text is problematic on many levels.
The full and experimental textMetric has been defined for many years yet is available only on 1 main stream browser (Safari), hidden behind flags (Chrome), covered up due to bugs (Firefox), status unknown (Edge, IE).
Using width only
At best you can use the width property of the object returned by ctx.measureText to estimate the width. This width is greater or equal to the actual pixel width (left to right most). Note web fonts must be fully loaded or the width may be that of the placeholder font.
Brute force
The only method that seams to work reliably is unfortunately a brute force technique that renders the font to a temp / or work canvas and calculates the extent by querying the pixels.
This will work across all browsers that support the canvas.
It is not suitable for real-time animations and applications.
The following function

*

*Will return an object with the following properties

*

*width width in canvas pixels of text

*left distance from left of first pixel in canvas pixels

*right distance from left to last detected pixel in canvas pixels

*rightOffset distance in canvas pixel from measured text width and detected right edge

*measuredWidth the measured width as returned by ctx.measureText

*baseSize the font size in pixels

*font the font used to measure the text

*It will return undefined if width is zero or the string contains no visible text.
You can then use the fixed size font and 2D transform to scale the text to fit the desired width. This will work for very small fonts resulting in higher quality font rendering at smaller sizes.
The accuracy is dependent on the size of the font being measure. The function uses a fixed font size of 120px you can set the base size by passing the property
The function can use partial text (Short cut) to reduce RAM and processing overheads. The property rightOffset is the distance in pixels from the right ctx.measureText edge to the first pixel with content.
Thus you can measure the text "CB" and use that measure to accurately align any text starting with "C" and ending with "B"
Example if using short cut text
    const txtSize = measureText({font: "arial", text: "BB"});
    ctx.font = txtSize.font;
    const width = ctx.measureText("BabcdefghB").width;
    const actualWidth = width - txtSize.left - txtSize.rightOffset;
    const scale = canvas.width / actualWidth;
    ctx.setTransform(scale, 0, 0, scale,  -txtSize.left * scale, 0);
    ctx.fillText("BabcdefghB",0,0);

measureText function
const measureText = (() => {
    var data, w, size =  120; // for higher accuracy increase this size in pixels.
    const isColumnEmpty = x => {
       var idx = x, h = size * 2;
       while (h--) {
           if (data[idx]) { return false }
           idx += can.width;
       }
       return true;
    }
    const can = document.createElement("canvas");
    const ctx = can.getContext("2d");
    return ({text, font, baseSize = size}) => {
        size = baseSize;
        can.height = size * 2;
        font = size + "px "+ font;
        if (text.trim() === "") { return }
        ctx.font = font;
        can.width = (w = ctx.measureText(text).width) + 8;
        ctx.font = font;
        ctx.textBaseline = "middle";
        ctx.textAlign = "left";
        ctx.fillText(text, 0, size);
        data = new Uint32Array(ctx.getImageData(0, 0, can.width, can.height).data.buffer);
        var left, right;
        var lIdx = 0, rIdx = can.width - 1;
        while(lIdx < rIdx) {
            if (left === undefined && !isColumnEmpty(lIdx)) { left = lIdx }
            if (right === undefined && !isColumnEmpty(rIdx)) { right = rIdx }
            if (right !== undefined && left !== undefined) { break }
            lIdx += 1;
            rIdx -= 1;
        }
        data = undefined; // release RAM held
        can.width = 1; // release RAM held
        return right - left >= 1 ? {
            left, right, rightOffset: w - right,  width: right - left,
            measuredWidth: w, font, baseSize} : undefined;
    }
})();

Usage example
The example use the function above and short cuts the measurement by supplying only the first and last non white space character.
Enter text into the text input.

*

*If the text is too large to fit the canvas the console will display a warning.

*If the text scale is greater than 1 (meaning the displayed font is larger than the measured font) the console will show a warning as there may be some loss of alignment precision.

inText.addEventListener("input", updateCanvasText);
const ctx = canvas.getContext("2d");
canvas.height = canvas.width = 500;

function updateCanvasText() {
    const text = inText.value.trim();
    const shortText = text[0] + text[text.length - 1];
    const txtSize = measureText({font: "arial", text: text.length > 1 ? shortText: text});
    if(txtSize) {
        ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height)
        ctx.font = txtSize.font;
        const width = ctx.measureText(text).width;
        const actualWidth = width - txtSize.left - txtSize.rightOffset;
        const scale =  (canvas.width - 20) / actualWidth;
        console.clear();
        if(txtSize.baseSize * scale > canvas.height) {
            console.log("Font scale too large to fit vertically");
        } else if(scale > 1) {
            console.log("Scaled > 1, can result in loss of precision ");
        }
        ctx.textBaseline = "top";
        ctx.fillStyle = "#000";
        ctx.textAlign = "left";
        ctx.setTransform(scale, 0, 0, scale, 10 - txtSize.left * scale, 0);
        ctx.fillText(text,0,0);
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.fillStyle = "#CCC8";
        ctx.fillRect(0, 0, 10, canvas.height);
        ctx.fillRect(canvas.width - 10, 0, 10, canvas.height);
    } else {
        console.clear();
        console.log("Empty string ignored");
    }
}
const measureText = (() => {
    var data, w, size =  120;
    const isColumnEmpty = x => {
       var idx = x, h = size * 2;
       while (h--) {
           if (data[idx]) { return false }
           idx += can.width;
       }
       return true;
    }
    const can = document.createElement("canvas");
    const ctx = can.getContext("2d");
    return ({text, font, baseSize = size}) => {
        size = baseSize;
        can.height = size * 2;
        font = size + "px "+ font;
        if (text.trim() === "") { return }
        ctx.font = font;
        can.width = (w = ctx.measureText(text).width) + 8;
        ctx.font = font;
        ctx.textBaseline = "middle";
        ctx.textAlign = "left";
        ctx.fillText(text, 0, size);
        data = new Uint32Array(ctx.getImageData(0, 0, can.width, can.height).data.buffer);
        var left, right;
        var lIdx = 0, rIdx = can.width - 1;
        while(lIdx < rIdx) {
            if (left === undefined && !isColumnEmpty(lIdx)) { left = lIdx }
            if (right === undefined && !isColumnEmpty(rIdx)) { right = rIdx }
            if (right !== undefined && left !== undefined) { break }
            lIdx += 1;
            rIdx -= 1;
        }
        data = undefined; // release RAM held
        can.width = 1; // release RAM held
        return right - left >= 1 ? {left, right, rightOffset: w - right, width: right - left, measuredWidth: w, font, baseSize} : undefined;
    }
})();
body {
  font-family: arial;
}
canvas {
   border: 1px solid black;
   width: 500px;
   height: 500px;
}
Enter text <input type="text" id="inText" placeholder="Enter text..."/>
<canvas id="canvas"></canvas>

Note decorative fonts may not work, you may need to extend the height of the canvas in the function measureText


text:
Q: Last value is repeating from webservices when it is added to an arraylist public static VehicleDetails[] getAllVehicles(String clientCode,String secretCode) throws ClientProtocolException,
    IOException, JSONException {
        VehicleDetails[] vd = null;
String result = null;

VehicleDetails vdetails = null;
ArrayList<VehicleDetails> vehicleArrayList = new ArrayList<VehicleDetails>();
JSONObject jObject = null;
String loginUrl = "getAllVehicles";

try {

    HttpPost request = new HttpPost(URL + loginUrl);
    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

    postParameters.add(new BasicNameValuePair("clientCode", clientCode));
    postParameters.add(new BasicNameValuePair("secretCode",  secretCode));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
            postParameters);
    request.setEntity(entity);
    HttpResponse response = getThreadSafeClient().execute(request);
    entityResponse = response.getEntity();
    result = EntityUtils.toString(entityResponse, HTTP.UTF_8);
     Log.d(TAG, "result>>" + result);
    JSONObject object = (JSONObject) new JSONTokener(result)
            .nextValue();
    VehicleDetails.status_login = object.getString("message");

    if (VehicleDetails.status_login.contentEquals("success")) {
        JSONArray array = object.getJSONArray("data");
        vehicleArrayList.clear();
        for (int i = 0; i < array.length(); i++) {
            Log.d(TAG, "LiveTracking>>>>>>>>>>>");

            JSONObject jObj = array.getJSONObject(i);
            String vehicleId = jObj.getString("vehicle_id").toString();
            String vehicleNumber = jObj.getString("vehicle_number").toString();

            vdetails = new VehicleDetails();

            vdetails.vehicleId = vehicleId;
            vdetails.vehicleNo = vehicleNumber;

            vehicleArrayList.add(vdetails);

        }
        vd = new VehicleDetails[vehicleArrayList.size()];

        for (int x = 0; x < vehicleArrayList.size(); ++x) {

            vd[x] = (VehicleDetails) vehicleArrayList.get(x);
        }
    } else if(VehicleDetails.status_login.contentEquals("failed")){

        JSONArray array = object.getJSONArray("data");

        for (int i = 0; i < array.length(); i++) {
            JSONObject jObj = array.getJSONObject(i);

            vdetails.failReason = jObj.getString("data").toString();

        }

    }

} catch (Exception e) {
    e.printStackTrace();
}

return vd;

}

Hi,
Value from the webservice is repeating when it is added to the arraylist.I clear the arraylist.But the issue still exixts.
My json response from webservice is:
{
    "message": "success",
    "data": [
        {
            "vehicle_id": "7",
            "vehicle_number": "KL-01 BA 2233"
        },
        {
            "vehicle_id": "2",
            "vehicle_number": "KL 01 AP 9650"
        },
        {
            "vehicle_id": "10",
            "vehicle_number": "KL 01 AP  9650 N"
        },
        {
            "vehicle_id": "9",
            "vehicle_number": "HB"
        }
    ]
}
HB is repeating four times when added to arraylist
Please help me?
Please suggest a method to solve this?

A: your problem is that your recreating a single instance and because java is pass by reference all your values in arraylist point at the last instance.
to prevent this problem for each entry create a new instance;
VehicleDetails vdetails = new VehicleDetails();
vdetails.vehicleId = vehicleId;
vdetails.vehicleNo = vehicleNumber;

vehicleArrayList.add(vdetails);

and delete this line
VehicleDetails vdetails = null;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stress Tensor OPE in CFT In David Tong's CFT notes, he argues that  the OPE for the holomorphic stress tensor with itself must take the form $$T(z)T(w)=\frac{c/2}{(z-w)^4}+2\frac{T(w)}{(z-w)^2}+\frac{\partial T(w)}{z-w}+finite$$ I'm a bit confused about this point. He argues that in a unitary CFT, no operators can have negative scaling dimensions, suppressing the higher order poles allowed by symmetry from appearing in the expansion. From this OPE, he derives the Virasoro algebra. Then later, when examining consequences of unitarity, he uses the Virasoro algebra to prove that no operators can have negative scaling dimension. Isn't this argument a little circular then? Is there a way to argue for the general form of the $TT$ OPE that doesn't invoke such circular reasoning?

A: Let's start with the Ward Identities ((4.11) in Tong's lecture). In radial quantization for a 2D theory they read
$\delta_{\epsilon,\bar\epsilon}\Phi(w,\bar w)= \frac{1}{2\pi {\rm i}}\left( \oint_\gamma dz R\left[ T(z)\epsilon(z)\Phi(w,\bar w) \right] - \oint_\gamma d\bar z R\left[ \bar T(\bar z)\bar \epsilon(\bar z)\Phi(w,\bar w) \right] \right)$.
We know how a primary field transform under the a conformal transformation:
$\delta_{\epsilon}\Phi(w)= h (\partial\epsilon) \Phi(w) + \epsilon\partial\Phi(w) $.
(I have taken only the holomorphic part, a similar formula goes for the right moving sector. From now on, I omit the anti-holomorphic part.)
This, using Cauchy, we see that for a general conformal transformation, i.e. $\epsilon=z^n$, the OPE between $T$ and $\Phi$ has to be
$T(z)\Phi(w)= \frac{h}{(z-w)^2}\Phi(w) + \frac{1}{z-w}\partial \Phi(w)+\cdots$,
where it is understood that we are working in radial quantization, so we omit the $R$ in front of the OPE. Now, what happens if $\Phi$ is a quasi-primary? Quasi-primaries transform under the global part of the conformal group, $SO(3,1)$. This is the part that is preserved in $D>2$. The global part of the conformal group is given by $\epsilon=z^n$, $n=0,1,2$. In this case, what we obtain is
$T(z)\Phi(w)= \sum_{p\ge4} \frac{a_p(w)}{(z-w)^p}+\frac{h}{(z-w)^2}\Phi(w) + \frac{1}{z-w}\partial \Phi(w)+\cdots.$
What Tong is telling you now, is that $T$ is actually a quasi primary (actually, it is a descendant of the identity!)  When he allows a central charge extension, he is stating that, at the quantum level, you find an anomaly determined by $c\neq0.$ classically, $T$ is a primary, but not quantically. This has nothing to do with unitarity. This is just the transformation of fields. Note that $h$ hasn't been set positive.
Now, just as you defined a symmetry transformation using Noether's currents, you can define symmetry generators for the conformal algebra (Virasoro generators) using radial quantization with $T$ being the conserved current. From there, you can compute the Virasoro algebra and you find its central-extension.
Using representation theory you can see that $h\ge0$ (or from the 2 point function and cluster decomposition) by looking at the first descendant of $\Phi$, $L_{-1}\Phi$. By looking at $L_{-2}\Phi$ you find $c\ge0$.
As you see, this is a linear argument. Not a cyclic one!

A: What Tong is presumably doing is not "deriving the Virasoro algebra", but showing that the modes $T_n$ of the energy-momentum tensor as defined by $T(z) = T_n z^{-n-2}$ actually fulfill the commutation relations of the Virasoro algebra, that is, the non-trivial statement here is that given the OPE of $T(z)$ with itself, one can show its modes are the Virasoro generators (see also this question). Conversely, given $T(z) = L_n z^{-n-2}$ where the $L_n$ are known to be the Virasoro generators, one may derive the OPE of $T$ with itself.
However, the Virasoro algebra is present in a conformal field theory simply because it is a conformal field theory. You don't need to know anything about a stress-energy tensor to know that a quantum conformal field theory will carry a representation of the Virasoro algebra because the Virasoro algebra is the (centrally extended) algebra of infinitesimal conformal transformations. So the reasoning is not circular.


text:
Q: How do I authenticate with Spnego/Kerberos and Apache's HttpClient? How do I correctly setup a connection with HttpClient that uses the logged in user's ActiveDirectory credentials to authenticate against a website and requires Kerberos/Spnego authentication?

A: Here's an example:
public class HttpSpnegoConnection {

    /**
     * Uses HttpClient 4.3.4 and CommonsIO 2.4
     */
    public static void main(String[] args) throws ClientProtocolException, IOException {

        String domain = "yourdomain.com";
        String kdc =  "thekdc.yourdomain.ch";
        // careful with aliases, 'somewebsite' has to be in the kerberos database
        String url = "http://somewebsite:8080/myresource/";
        // if the port does not match the kerberos database entry, skip it during the lookup
        boolean skipPortAtKerberosDatabaseLookup = true;

        // Depending on your AD configuration, this file is not needed
        File krb5Config = createKrb5Configuration(domain,kdc);

        System.out.println("Created config '"+krb5Config.getAbsolutePath()+"':");
        System.out.println(IOUtils.toString(new FileReader(krb5Config)));

        System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString());
        System.setProperty("sun.security.krb5.debug", "true");
        System.setProperty("javax.security.auth.useSubjectCredsOnly","false");

        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPortAtKerberosDatabaseLookup))
            .build();

        CloseableHttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry).build();
        HttpClientContext context = HttpClientContext.create();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // This may seem odd, but specifying 'null' as principal tells java to use the logged in user's credentials
        Credentials useJaasCreds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };
        credentialsProvider.setCredentials( new AuthScope(null, -1, null), useJaasCreds );
        context.setCredentialsProvider(credentialsProvider);

        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = client.execute(httpget,context);
        String responseString = IOUtils.toString(response.getEntity().getContent());

        System.out.println("HTTP Response:");
        System.out.println(responseString);
    }

    /**
        Creates a temporary krb5.conf
        [libdefaults]
            default_realm = <domain>

        [realms]
            snb.ch = {
                kdc = <kdc>
                admin_server = <kdc>
            }
     */
    private static File createKrb5Configuration(String domain, String kdc) throws IOException {
        File tempFile = File.createTempFile("krb5", "kdc");
        ArrayList<String> lines = new ArrayList<>();
        lines.add("[libdefaults]");
        lines.add("\tdefault_realm = "+domain);
        lines.add("[realms]");
        lines.add("\t"+domain+" = {");
        lines.add("\t\tkdc = "+kdc);
        lines.add("\t\tadmin_server = "+kdc);
        lines.add("\t}");
        FileWriter writer = new FileWriter(tempFile);
        IOUtils.writeLines(lines, System.lineSeparator(), writer);
        IOUtils.closeQuietly(writer);
        return tempFile;
    }

}

Depending on your AD configuration, creating and specifying the krb5.conf may be skipped.


text:
Q: Java: conditional initialization? Ruby has conditional initialization. Apparently, Java does not or does it? I try to write more succintly, to limit the range as small as possible.
import java.io.*;
import java.util.*;

public class InitFor{

        public static void main(String[] args){
                for(int i=7,k=999;i+((String h="hello").size())<10;i++){}

                System.out.println("It should be: hello = "+h);

        }
}

Errors
Press ENTER or type command to continue
InitFor.java:8: ')' expected
  for(int i=7,k=999;i+((String h="hello").size())<10;i++){}
                              ^

Puzzles

*

*Is it possible to assign a value to an declared value in while-loop? YES code1

*Assignment in for-loop conditional? YES code2

*conditional init NO

*Can you assign different types of values in loops? YES in a reply

*Some rule for initialization inside loops? Declare outside to access values later, what about init?  (?)
1. CODE
import java.io.*;
import java.util.*;

public class InitFor{
        public static void main(String[] args){
                int k=5;
                while((k=(k%3)+1)!=1){
                        System.out.println(k);
                }
                //PRINTs only 3
        }
}

2. CODE
import java.io.*;
import java.util.*;

public class InitFor{

        public static void main(String[] args){
                int k=5;
                for(;(k=(k%3)+1)!=1;){
                        System.out.println(k);
                }
                //PRINTs only 3
                System.out.println(k);
                // WHY DOES IT PRINT 1? Assign in for-loop!
        }
}

Part of the Original problem with many different kind of assignments and initializations -- 100lines of code in one-liner
for(int t=0,size=(File[] fs=((File f=f.getParentFile()).listFiles(filt))).size();fs==null;t++){if(t>maxDepth){throw new Exception("No dir to read");}}

A: The problem is that a variable may not be declared there; variables may be declared within a block, but may not be declared as part of an expression. However, you can allocate objects in an expression:
for(int i=7,k=999;i+((new String("hello")).length())<10;i++){}

For your program, the following would make more sense:
public static void main(String[] args){
    String h = "hello";
    for(int i=7,k=999;(i+h.length())<10;i++){} // not sure what this is doing
    System.out.println("It should be: hello = "+h);
}

I would also add that even if a declaration were allowed where you had it, the variable would belong to the scope of the for-loop, and so the variable would no longer be visible after the loop (out of the scope).

A: Variable declarations cannot be parts of expressions, they are statements, as the Java spec said so.
If conditional initialization existed in Java, then how to determine if a variable is initialized? How to compile the code properly? (you need to understand how do Java compiler work to know it is impossible) How are errors handled? There are many complications. In your code, even if the variable is initialized, it will be gone after the for block due to Java's scoping strategy.

A: I think you are confusing assignment with declaration.  You could do
public static void main(String[] args){
    String h = null;
    for(int i=7,k=999;i+((h="hello").size())<10;i++){}

    System.out.println("It should be: hello = "+h);
}

the ='s operator is right associative and sets the first argument to the second argument and evaluates to the first argument, so something like
a = b = c = 4

is the same as
(a = (b = (c = 4)))

which sets c to 4, b to c (now 4) and a to b (now also 4)
your one line of code could be (reformatted for clarity)
File[] fs=null;
File f= ??? ; //you never initialize f in the for loop, you need a starting value
int t, size;

for (t=0,size=(fs=((f=f.getParentFile()).listFiles(filt))).size();
     fs==null;
     t++) {
       if(t>maxDepth) {throw new Exception("No dir to read");}
     }
}

EDIT - (though that's really ugly code and if you checked it in on my project I'd be telling you to rewrite it ASAP)

A: Java conditional initialization:
variable = (condition ? expression1 : expression2);

For example:
int max = (faces.length>curves.length ? faces.length : curves.length);


text:
Q: How to configure Linux firewall to allow Exchange Server ActiveSync Direct Push to work without warnings I am experiencing EventID 3033 'Server ActiveSync' warning events on our Exchange 2003 SP2 server described in KB905013 (see below), apparently due to firewall timeouts.
The Exchange server is behind a Red Hat Enterprise Linux 5.4 iptables based firewall, but I don't know what settings to check to make sure that the HTTP(S) timeout is set to at least 15 minutes as described in the article.
Can anyone tell me where the settings are that affect iptables firewall timeouts in Linux and how I can change them?
Event log error follows:
Event Type: Warning
Event Source:     Server ActiveSync
Event Category:   None
Event ID:   3033
Date:       08/10/2009
Time:       10:42:35
User:       <REMOVED>
Computer:   <REMOVED>

Description:

The average of the most recent [200] heartbeat intervals used by clients is less than or equal to [540].  Make sure that your firewall configuration is set to work correctly with Exchange ActiveSync and direct push technology. Specifically, make sure that your firewall is configured so that requests to Exchange ActiveSync do not expire before they have the opportunity to be processed.  For more information about how to configure firewall settings when using Exchange ActiveSync, see Microsoft Knowledge Base article 905013, "Enterprise Firewall Configuration for Exchange ActiveSync Direct Push Technology" (http://go.microsoft.com/fwlink/?linkid=3052&kbid=905013).

A: Having done some investigation, as far as I can see the default Linux netfilter timeout for 'established' TCP connections when using the 'state' module to allow ESTABLISHED connections through is 5 days, way above the 15 minutes recommended by Microsoft:
http://www.frozentux.net/ipsysctl-tutorial/chunkyhtml/netfilterreference.html

3.7.8. ip_ct_tcp_timeout_established The ip_ct_tcp_timeout_established
  variable tells us the default timeout
  value for tracked connections in the
  ESTABLISHED state. All connections
  that has finished the initial 3-way
  handshake, and that has not seen any
  kind of FIN packets are considered as
  ESTABLISHED. This is in other words
  more or less the default state for a
  TCP connection.
Since we never want a connection to be
  lost on either side of the netfilter
  firewall, this timeout is set
  extremely high so we do not
  accidentally erase entries that are
  still used. Per default, the
  ip_ct_tcp_timeout_established variable
  is set to 432000 seconds, or 5 days.

I am therefore going to investigate other options as there may be another firewall in the way causing the timeouts.
Thanks for those who helped anyway!


text:
Q: How can I replace the img with a DIV that has a background image? I want to optimize my code. I think I am correct in saying that if I combine multiple images into one file then I can't use the position attribute unless the images are part of a background image. But I am not sure how to set up my DIV. Do I need to set the width and height of the DIV? Do I need to do display: block or something like that?
Here's the code that I have so far:

Home

xx

yy

A: if you have multiple images in one file, I'd recommend you to add some classes, as @pduersteler said.
ul li a { display: inline-block; position: relative; width: 16px; height: 16px; }
ul li a.one { background: url('../../Content/Icons/home.png') left top no-repeat; }
ul li a.two { background: url('../../Content/Icons/home.png') -16px top no-repeat; }
ul li a.three { background: url('../../Content/Icons/home.png') -32px top no-repeat; }

Something like this...

A: If I got this, you want links with icons, right?
Append some classes
Home

And add CSS
.icon
{
    padding: 0 0 0 20px;
    background-repeat: no-repeat;
}

.icon.home
{
    background-image: url('path/to/your/icon_home.png');
    background-position: 0px 20px;
}

Now you just have to play with your padding.
EDIT
It looks like you want to use sprites. A List Apart has a good article about sprites here.


text:
Q: How can Einstein notation be used to prove rotational invariance of a dot product? I am beginning to self-learn Einstein Notation, and I tried to prove the rotational invariance of a dot product. In matrix notation (which I am more used to) it is quite simple. If $u$ and $v$ are column vectors, $ u \cdot v = u^T v $. If $R$ is a rotation matrix then the vectors transform as  $ u' = Ru $, $ v' = Rv $. Taking the dot product of the transformed vectors, $ u' \cdot v' = u'^Tv' = (Ru)^T(Rv) = u^T R^T R V $ and due to the orthogonality of R,the $ R^T R $ cancels out and we are left with $ u^T v $.
However, I am having difficulties using Einstein notation to prove this same result.
If $ R_{ij} $ is a rotation matrix such that $ R_{ik} R_{jk} = \delta_{ij} $, how do we prove that $ ( R_{ij} u_j ) ( R_{ij} v_j ) = u_i v_i $?

A: @Andrei is right. Use$$(Ru)_i(Rv)_i=R_{ij}R_{ik}u_jv_k=\delta_{jk}u_jv_k=u_jv_j.$$


text:
Q: Axis title won't rotate when y-axis is on the right I am trying to generate a plot with y-axis on the right and I would like to rotate the y-axis title to be horizontal. Here's some sample code :
ggplot() + geom_function(fun = ~ -.x) +
      scale_x_continuous(limits = c(-0.27,0),name = "example")+
      scale_y_continuous(position = "right",limits = c(0,0.27),name = "test")+
      theme_classic()+
      theme(axis.title.y = element_text(angle = 0, hjust = 0),
            axis.title.x = element_text(hjust = 0))

"angle = 0" doesn't seem to do anything when you set "position = "right"", but works fine when you use the default y-axis position. Why this is happening and how do I rotate the title when y-axis is on the right?
Thank you.

A: You have to use the theme element axis.title.y.right
ggplot() + geom_function(fun = ~ -.x) +
  scale_x_continuous(limits = c(-0.27,0),name = "example")+
  scale_y_continuous(position = "right",limits = c(0,0.27),name = "test")+
  theme_classic()+
  theme(axis.title.y.right = element_text(angle = 0),
        axis.title.x = element_text(hjust = 0))


text:
Q: Binary operator '+=' cannot be applied to operands of type '[Dictionary]' and 'Dictionary' I tried debugging my ios app in xcode using swift which I'm making a task app but I'm getting the error "'+=' cannot be applied to operands of type '[Dictionary]' and 'Dictionary'. The following error is happening in one of my functions which the code is below. How do I get around this error by applying "+=" using the Dictionary type?
Code:
func taskCreated(task: Dictionary<String, String>) {
    println("in task created delegate of ViewController")
    println(task)

    dataSource[0] += task

    tableView.reloadData()
}

Edit: My Declaration of dataSource
var dataSource: [[Dictionary<String, String>]] = [[], []]

A: You want to append a dictionary to an array of array of dictionaries.  Use append() on the selected array:
dataSource[0].append(task)


text:
Q: meteorjs and mongodb : delta for part of huge document updated With metorjs and mongodb , in a collection if i have a huge document and only a part of that is updated. Will the entire document will be sent to the clients or just the diff?
Let say for example in a mongodb collection say person if i have a document "
{
   personName:"abc",
   businessContacts:[
      {
          "contactName":"pqr",
          "phone":12121        // if this gets updated in mongodb .. what will be sent via meteor
      },

     //1000 such more ...
   ]
}

and user is sent out the entire document in query | find() .. // the entire document

A: Initially the entire document will be sent. When you make an update to the database only a diff containing that change would be sent


text:
Q: How to dump mysql table relations in PHP I searched a lot but could not find a way to dump table relations like one-to-one, one-to-many vs in PHP.
Is there a way to handle this issue in PHP?
A result might be:
array(
   'tableA' => array(
                'one-to-one' => array('tableB', 'tableC'),
                'one-to-many' => array('tableD'),

   'tableB' => array(
                'one-to-one' => array('tableA')

    ...
)

Any suggestions are much appreciated.

A: I found a script at http://dev.mysql.com/doc/refman/5.0/en/show-table-status.html which  describes parsing table info with regex. I had manipulated the code to work. here is the code.
<?php
$conn = mysql_connect('localhost', 'user', 'pass');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}

//DB connection already established
mysql_query("use db");
$res = mysql_query("SHOW CREATE TABLE tbl");
$row = mysql_fetch_assoc($res);
mysql_free_result($res);

//Only work on InnoDB foreign key info.
if(preg_match_all(
         '/FOREIGN KEY \(`(.*)`\) REFERENCES `(.*)` \(`(.*)`\)/',
         $row['Create Table'],
         $matchArr)) {
    print_r($matchArr); //which writes down the result

}

?>

A: You have to do this yourself by parsing the output of the DESCRIBE command. You might consider using a ORM like doctrine. You tell doctrine to make a one to one relation on table a and table b and it handles the rest.


text:
Q: Number of interval of seq without for loop I have a dataframe with dates and I used seq() between the lowest and the highest date by year.
Dataframe :
     daysOfStop dateConsult
 1:         NA  2002-11-17
 2:         NA  2003-11-03
 3:         NA  2004-12-16
 4:         NA  2006-01-31
 5:         NA  2006-01-31
 6:         NA  2003-02-05
 7:         NA  2003-09-29
 8:         NA  2005-08-01
 9:         NA  2005-08-01
10:         NA  2005-08-01

Results of seq() :
"2002-11-17" "2003-11-17" "2004-11-17" "2005-11-17"

What I would like to do it to create a new column in which the values are defined by the intervals of seq() without for looping (that takes a lot of time since I have more than 120 000 rows).
So :
between "2002-11-17" and "2003-11-17", it's year number 1 (first interval);
between "2003-11-17" and "2004-11-17", it's year number 2 (second interval)
and so on.
Results expected :
     daysOfStop dateConsult numYear
 1:         NA  2002-11-17    1
 2:         NA  2003-11-03    1
 3:         NA  2004-12-16    3
 4:         NA  2006-01-31    4
 5:         NA  2006-01-31    4
 6:         NA  2003-02-05    1
 7:         NA  2003-09-29    1
 8:         NA  2005-08-01    3
 9:         NA  2005-08-01    3
10:         NA  2005-08-01    3

Data :
structure(list(daysOfStop = c(NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_),
    dateConsult = structure(c(12008, 12359, 12768, 13179, 13179,
    12088, 12324, 12996, 12996, 12996), class = "Date")), .Names = c("daysOfStop",
"dateConsult"), class = c("data.table", "data.frame"), row.names = c(NA,
-10L), .internal.selfref = <pointer: 0x0000000006360788>)

A: We can use findInterval
dt1[, numYear := findInterval(dateConsult, seq(min(dateConsult),
                       max(dateConsult), "1 year"))]


text:
Q: Intermittent error: what would cause a video to stop loading between loadstart and durationchange? I'm in the frustrating situation of having an intermittent error.  When functional, PHP specifies a video and 3 pictures to be displayed.  The video begins playing 800ms after the page loads, and the pictures are displayed immediately upon the end of the video, at which point a user presses a key (corresponding to the location of the picture) and the keypress triggers a function that measures reaction time, stores which picture they selected, and loads the next page, whereupon all of this happens again with a new video and new pictures.
That all works just fine... sometimes.
At other times, I get a blank screen where I was expecting to see the video.  Sometimes it happens right away, sometimes after as many as 15 or 20 successful loads, or anywhere in between.  I'm running Chrome 27.0.1453.93, and tracking errors using Chrome's built-in javascript console.  Even when the video fails to load, there are no javascript errors (with DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">).
To pinpoint where things are breaking down, I've added a bunch of event listeners and used anonymous functions to pass some output to the js console log file to see which stages of the video event are or aren't happening.  Here, at least, is a reliable pattern: every time the video fails to load, loadstart has happened, but durationchange has not. I just can't figure out what the problem is that prevents it from continuing!
I look forward to the responses here, whether they're answers or even just other people corroborating the experience so I don't feel so crazy!  I'll include the two most relevant javascript functions here, but I'm not sure how much good they'll do.
<script>

    function playVid(newSource){

           console.log("playVid worked");
           setTimeout(function(){//tells it to wait for some amount of time (below) before doing the next part
               console.log("setTimeout was called");
               document.getElementById("StimClip").innerHTML="<video id='video1'> <source src='" + newSource + "' type='video/mp4'>Something went wrong.  Sorry 'bout that!</video>"; //replace blank.jpg with the appropriate video
               console.log("the inner html was set");
               myAddListener();
               console.log("myAddListener was called");
               var  myVid=document.getElementById("StimClip"); //create a new variable to identify the video
               console.log("the myVid variable was created");
               video1.play(); //play the video

        } //

           ,800); //finishes the setTimeout call by specifying how many msec to wait before executing.

        }

function myAddListener(){
        console.log("myAddListener worked");
        var myVideo = document.getElementsByTagName('video')[0];
        myVideo.addEventListener('waiting', function(){console.log("I'm WAITING...!")}, false);
        myVideo.addEventListener('suspend', function(){console.log("Nice suspenders.")}, false);
        myVideo.addEventListener('abort', function(){console.log("video was aborted")}, false);
        myVideo.addEventListener('error', function(){console.log("there was an error")}, false);
        myVideo.addEventListener('loadstart', function(){console.log("load start worked")}, false);
        myVideo.addEventListener('durationchange', function(){console.log("the duration changed")}, false);
        myVideo.addEventListener('loadedmetadata', function(){console.log("metadata was loaded")}, false);
        myVideo.addEventListener('loadeddata', function(){console.log("data was loaded")}, false);
        myVideo.addEventListener('progress', function(){console.log("progress...? ")}, false);
        myVideo.addEventListener('canplay', function(){console.log("video can play")}, false);
        myVideo.addEventListener('canplaythrough', function(){console.log("can play through worked")}, false);
        myVideo.addEventListener('playing', function(){console.log("the video started playing")}, false);
        myVideo.addEventListener('ended', ShowPics, false);
    }
</script>

A: Oh geez.  I'm glad no one else wasted their time trying to answer this.  In case you were wondering, the thing that would cause a video to stop loading between loadstart and durationchange is if that video doesn't exist!  (I had a typo in the filename of one of my videos, and because the order of videos is randomized I couldn't ever tell that it was always failing when it was trying to load the same one.)
Fixed.


text:
Q: SQLITE Database Error 14 I'm developing a game where there are 4 buildings and in these buildings, there are 3 stages inside. The player can play the stages one by one, from one building to another, however, when they have finished one cycle (eg. going from building 1 stage 1 to building 4 stage 3) I keep getting this error where it's an error 14 (SQLITE_CANTOPEN) whenever the player clicks on another building. It keeps happening every single time I test the app. Can anyone help me? :S
edit: sorry, here's the code I used to open the window to access the game:
NSArray *bldgLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
                                                                         withQuery: SQL_STMT_GET_BUILDING_LEVELS
                                                                withValuesAndTypes: [NSArray arrayWithObjects:
                                                                                [NSString stringWithFormat: @"%d", gameStateProxy.selectedArea], @"i", nil]];

        NSLog(@"bldgLevels: %@", bldgLevels);

        NSLog(@"getting player levels");
        NSArray *playerLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
                                                                           withQuery: SQL_STMT_GET_PLAYER_UNLOCKED_LEVELS
                                                                  withValuesAndTypes: [NSArray arrayWithObjects:
                                                                                [NSString stringWithFormat: @"%d", gameStateProxy.playerId], @"i", nil]];

        NSLog(@"playerLevels: %@", playerLevels);

        int i = 0;
        while (i < [bldgLevels count])
        {
            NSDictionary *bldgLevel = (NSDictionary *)[bldgLevels objectAtIndex: i];
            int levelId = [(NSNumber *)[bldgLevel objectForKey: @"level_id"] intValue];
            int indexOrder = [(NSNumber *)[bldgLevel objectForKey: @"index_order"] intValue];

            data = [BldgLevelData createObject];
            data.levelId = levelId;
            data.levelName = (NSString *)[bldgLevel objectForKey: @"name"];
            data.rescuedPtsRequired = [(NSNumber *)[bldgLevel objectForKey: @"rescued_required"] intValue];
            data.minPtsToComplete = [(NSNumber *)[bldgLevel objectForKey: @"min_pts"] intValue];
            data.lastPlayed = @"";
            data.dateAdded = @"";
            data.isNew = NO;
            data.isCompleted = NO;
            data.isLocked = YES;

            // Group levels together by their index order
            if (indexOrder == 1) { groupId++; }
            data.groupId = groupId;
            data.indexOrder = indexOrder;

            int j = 0;
            while (j < [playerLevels count])
            {
                NSDictionary *playerLevel = (NSDictionary *)[playerLevels objectAtIndex: j];
                int playerLevelId = [(NSNumber *)[playerLevel objectForKey: @"level_id"] intValue];

                if (levelId == playerLevelId)
                {
                    data.rescuedHighScore = [(NSNumber *)[playerLevel objectForKey: @"rescued_highscore"] intValue];
                    data.rescuedScore = [(NSNumber *)[playerLevel objectForKey: @"rescued_score"] intValue];
                    data.lastPlayed = (NSString *)[playerLevel objectForKey: @"lastplayed"];
                    data.dateAdded = (NSString *)[playerLevel objectForKey: @"dateadded"];
                    data.isNew = ([(NSString *)[playerLevel objectForKey: @"lastplayed"] isEqualToString: @""]);
                    data.isCompleted = ([(NSNumber *)[playerLevel objectForKey: @"completed"] intValue] == 1);
                    data.isLocked = NO;

                    break;
                }

                j++;
            }

            if (indexOrder == 1)
            {
                list = [NSMutableArray arrayWithCapacity: 1];

                groupData = [BldgLevelGroupData createObject];
                groupData.groupId = groupId;
                groupData.firstLevelId = levelId;
                groupData.timeLimit = [(NSNumber *)[bldgLevel objectForKey: @"time_limit"] intValue];
                groupData.list = list;

                // Get SOS items
                NSMutableArray *sosItems = [NSMutableArray arrayWithCapacity: 0];
                //
                NSLog(@"getting levelSOSItems");

                NSLog(@"i: %d, j: %d", i, j);
                NSLog(@"list: %@", list);
                NSLog(@"levelId: %d", levelId);

                NSArray *levelSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
                                                                                withQuery: SQL_STMT_GET_LEVEL_SOS
                                                                           withValuesAndTypes: [NSArray arrayWithObjects:
                                                                                [NSString stringWithFormat: @"%d", levelId], @"i", nil]];

                NSLog(@"Levelsositems: %@", levelSOSItems);

                NSLog(@"getting player sos Items");
                NSArray *playerSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
                                                                                withQuery: SQL_STMT_GET_PLAYER_SOS
                                                                            withValuesAndTypes: [NSArray arrayWithObjects:
                                                                                [NSString stringWithFormat: @"%d", gameStateProxy.playerId], @"i",
                                                                                nil]];

                NSLog(@"playerSoSItems: %@", playerSOSItems);

                j = 0;
                while (j < [levelSOSItems count])
                {
                    SOSItemData *sosItemData = [SOSItemData createObject];
                    sosItemData.itemId = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: @"sos_id"] intValue];
                    sosItemData.itemName = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: @"name"];
                    sosItemData.desc = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: @"desc"];
                    sosItemData.coins = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: @"coins_cost"] intValue];
                    sosItemData.cash = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: @"cash_cost"] intValue];
                    sosItemData.rescuedPtsRequired = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: @"rescued_required"] intValue];

                    int k = 0;
                    while (k < [playerSOSItems count])
                    {
                        if ([(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: @"sos_id"] intValue] == sosItemData.itemId)
                        {
                            sosItemData.qty = [(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: @"qty"] intValue];
                            break;
                        }

                        k++;
                    }

                    //NSLog(@"%@", sosItemData);
                    [sosItems addObject: sosItemData];

                    j++;
                }

                groupData.sosItems = sosItems;

                [groupsList addObject: groupData];
            }

            NSLog(@"%@", data);
            [list addObject: data];

            i++;
        }

and here's the code I used to fetch the data from the database:
-(NSArray *) fetchDataFromDatabase:(NSString *)dbPath withQuery: (NSString *)sql withValuesAndTypes: (NSArray *)params

{
    /*
     dbPath - Name of database file
     sql - SQL statement. Prepared statements are allowed to be used here (refer to params
     params - Array containing data and its corresponding data type
     */
NSMutableArray *result = nil;

//make sure db is closed
NSLog(@"close database first!");
sqlite3_close(database);

NSLog(@"open database!");
int dbStatus = [self openDatabase: dbPath];
if (dbStatus == SQLITE_OK)
{
    //int stmtStatus = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
    int stmtStatus = [self prepareStatement: sql withParams: params];
    if(stmtStatus == SQLITE_OK)
    {
        result = [NSMutableArray arrayWithCapacity: 1];

        while(sqlite3_step(stmt) == SQLITE_ROW)
        {
            NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity: 1];

            int columnCount = sqlite3_column_count(stmt);
            int j = 0;

            while (j < columnCount)
            {
                /*
                 Possible sqlite data types:
                 SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL
                 */

                if (sqlite3_column_type(stmt, j) == SQLITE_INTEGER)
                {
                    [row setObject: [NSNumber numberWithInt: sqlite3_column_int(stmt, j)]
                            forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
                }
                else if (sqlite3_column_type(stmt, j) == SQLITE_FLOAT)
                {
                    [row setObject: [NSNumber numberWithDouble: sqlite3_column_double(stmt, j)]
                            forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
                }
                else if (sqlite3_column_type(stmt, j) == SQLITE_TEXT)
                {
                    [row setObject: [NSString stringWithFormat: @"%s", sqlite3_column_text(stmt, j)]
                            forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
                }
                else if (sqlite3_column_type(stmt, j) == SQLITE_NULL)
                {
                    [row setObject: [NSNull null]
                            forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
                }

                j++;
            }

            [result addObject: row];
        }
    }
    else { NSLog(@"stmt error: %d", stmtStatus); }
}
else if (dbStatus == 14)
{
    NSLog(@"db error: %d", dbStatus);
    NSLog(@"killing app.");
    exit(0);
}
else { NSLog(@"db error: %d", dbStatus); }

//Even though the open call failed, close the database connection to release all the memory.
sqlite3_close(database);

return result;

}

A: sorry if it is wrong..... in your code you didn't finalize statement but useed stmt variable .before close DB ,we should finalize statement if we use statement.....
comment for finalize statement
 sqlite3_finalize(Stmt);


text:
Q: Funny characters in MySQL database after import I exported and then imported a wordpress mysql database from one server to another.
On the new server, a lot of the apostrophes have turned to question mark symbols ?.  When I look at the data in the database itself, the apostrophes are normal like this ' so what would be causing those characters to look messed up?
Thanks

A: Perhaps run SHOW CREATE TABLE tablename on both servers. The difference might be related to the CHARSET.

A: You should use the corresponding collation in the select, for example
SELECT k
FROM t1
ORDER BY k COLLATE latin1_german2_ci;
One common collation name could be SQL_Latin1_General_Cp1254_CS_AS
here is a list of collation names:http://msdn.microsoft.com/en-us/library/ms180175.aspx


text:
Q: Differential in Complex Analysis If we define the operator $$\partial_{\bar{z}} = \frac{\partial_x + i \partial_y}{2}$$ then it is claimed that for $\lambda \in \mathbb{R}$ we have the following series of equalities:
$$
\frac{1}{\pi} \int_{\mathbb{R}^2} \frac{\partial_{\bar{z}} f(x+ i y) }{\lambda - x- y} dx dy = \frac{1}{2 \pi i} \int_{\mathbb{R}^2} \partial_{\bar{z}} \left( \frac{f(x + i y)}{\lambda - x- iy} \right) dz d\bar{z} = \frac{1}{2 \pi i} \int_{\mathbb{R}^2} d \left( \frac{f(x + i y)}{\lambda - x- iy} dz \right)
$$
where the operator $d$ is the differential in the sense of a $~1$-form.
I'm having trouble proving both equalities and do not have any idea what the statement "is the differential in the sense of a $~1$-form" means in this context.
The first equality they claim follows from the observation $\partial_{\bar{z}} (\lambda - z)^{-1}= 0$ which I can prove.

A: You need to work with differential forms and the wedge product (which is anti-commutative) for this to make sense (and be correct). Note that
$$dz\wedge d\bar z = d(x+iy)\wedge d(x-iy) = (dx + i\,dy)\wedge (dx -i\,dy) = -2i dx\wedge dy,$$
so $\dfrac{dz\wedge d\bar z}{-2i} = dx\wedge dy$. So they have a sign error in the equation. They mean to write—or perhaps you mistyped?—$d\bar z\wedge dz$, and then it's correct. And then we have
$d(g(z)\,dz) = \partial_{\bar z} g \,d\bar z\wedge dz$, which gives the last equality. Here we use the fact that
$$dg = \dfrac{\partial g}{\partial z}dz + \dfrac{\partial g}{\partial\bar z}d\bar z$$
and apply $dz\wedge dz = 0$ to get their result.


text:
Q: IndexOf from an array shows as a negative number in an arraylist class Main{
int index = Student.studenten.indexOf(loggedInId);
}

Here in the main class im trying to get the position of the variable loggedInId which is an int.
class Student{
static ArrayList<Student>studenten = new ArrayList<>();

 public Student(int id, String naam, int studentnummer, String wachtwoord, boolean docent){
studenten.add(new Student(1,"Rowan", 21069816, "test", true));
        studenten.add(new Student(2,"test", 1234567, "test", false));
   }
}

Im adding the students to the arraylist with their id etc.
What im trying to do is have their id searched for position (for example id = 1) then it will look the position of that id in the arraylist (which would be position 0) and then return the position for the int index. So that i can get their studentnummer with that index.
Basically im trying to find their studentnummer with only their id
But no matter if loggedInId is 1 or 2, it will always return as -1 and that is out of bounds.

A: better use a map instead of a list, you can do something like :-
class Student {
private int id;
private int studentnummer;

static Map<Integer, Student> studenten = new HashMap<>();

public Student(int id, String naam, int studentnummer, String wachtwoord, boolean docent) {
    this.id = id;
    this.studentnummer = studentnummer;
    Student std1 = new Student(1, "Rowan", 21069816, "test", true);
    Student std2 = new Student(2, "test", 1234567, "test", false);
    studenten.put(std1.id, std1);
    studenten.put(std2.id, std2);
}

}
To get the student by id  :-
 int stdToSearch = 1;
 Student student =
 Student.studenten.get(stdToSearch);nummer=student.getStudentnummer();

A: I think you are using the wrong function.
The indexOf(element) function needs an element as a parameter (in your case a Student). After getting the parameter it checks if that element exists in the array.
If the element exists in the array it will return the index  of where exactly in the array it is located.
If the element DOES NOT exist it will always return -1;
If what you are trying to do is get a user with a specific ID:
make a foreach loop. In the foreach loop check if the current element(current student) in the arrayList has an ID of the Id that you are searching for.


text:
Q: pip install gives error: Unable to find vcvarsall.bat Using pip install zipline on Windows 8 with Python 2.7 gives me the error:
Downloading/unpacking six (from python-dateutil==2.1->delorean->zipline[all])
  Running setup.py egg_info for package six

Installing collected packages: blist, pytz, requests, python-dateutil, six
  Running setup.py install for blist
    building '_blist' extension
    error: Unable to find vcvarsall.bat
    Complete output from command C:\Python27\python.exe -c "import setuptools;__
file__='c:\\users\\ThatsMe\\appdata\\local\\temp\\pip-build-ThatsMe\\blist\\setup.py';ex
ec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" inst
all --record c:\users\ThatsMe\appdata\local\temp\pip-xvoky2-record\install-record.tx
t --single-version-externally-managed:

running install

running build

running build_py

running build_ext

building '_blist' extension

error: Unable to find vcvarsall.bat

Question: How can the error be resolved? Running pip install zipline[all] gives the same error...

A: If you are getting this error on Python 2.7 you can now get the Microsoft Visual C++ Compiler for Python 2.7 as a stand alone download.
If you are on 3.3 or later you need to install Visual Studio 2010 express which is available for free here: https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express
If you are 3.3 or later and using a 64 bit version of python you need to install the Microsoft SDK 7.1 that ships a 64 bit compiler and follow the directions here Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

A: First, you should look for the file vcvarsall.bat in your system.
If it does not exist, I recommend you to install Microsoft Visual C++ Compiler for Python 2.7. This will create the vcvarsall.bat in "C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0" if you install it for all users.
The problem now is in the function find_vcvarsall(version) in the C:/Python27/Lib/distutils/msvc9compiler.py module, which is looking for the vcvarsall.bat file.
Following the function calls you will see it is looking for an entry in the registry containing the path to the vcvarsall.bat file. It will never find it because this function is looking in other directories different from where the above-mentioned installation placed it, and in my case, the registry didn't exist.
The easiest way to solve this problem is to manually return the path of the vcvarsall.bat file. To do so, modify the function  find_vcvarsall(version) in the msvc9compiler.py file with the absolute path to the vcvarsall.bat file like this:
def find_vcvarsall(version):
    return r"C:\Program Files (x86)\Common Files\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat"

This solution worked for me.
If you already have the vcvarsall.bat file you should check if you have the key productdir in the registry:

(HKEY_USERS, HKEY_CURRENT_USERS, HKEY_LOCAL_MACHINE or HKEY_CLASSES_ROOT)\Software\Wow6432Node\Microsoft\VisualStudio\version\Setup\VC

Where version = msvc9compiler.get_build_version()
If you don't have the key just do:
def find_vcvarsall(version):
        return <path>\vcvarsall.bat

To understand the exact behavior check msvc9compiler.py module starting in the find_vcvarsall(version) function.

A: The problem here is the line 292 (Using Python 3.4.3 here) in $python_install_prefix/Lib/distutils/msvc9compiler.py  which says:
VERSION = get_build_version()

This only checks for the MSVC version that your python was built with. Just replacing this line with your actual Visual Studio version, eg. 12.0 for MSVC2013
VERSION = 12.0

will fix the issue.
UPDATE: Turns out that there is a good reason why this version is hardcoded. MSVC C runtime is not required to be compatible between major versions. Hence when you use a different VS version you might run into runtime problems. So I advise to use VS 2008 (for Python 2.6 up to 3.2) and VS2010 for (Python 3.3 and later) until this issue is sorted out.
Binary compatibility will arrive with VS 2015 (see here) along with Python 3.5 .
For Python 2.7 users Microsoft released a special Microsoft Visual C++ Compiler for Python 2.7 which can be used without installing the whole VS 2008.

A: Simply because you don't have c++ compiler installed there in your machine, check the following

*

*Download Microsoft Visual C++ 2008 from this page. That is a generally useful page anyway, so you should probably bookmark it. For Python 3.3+ use MS Visual C++ 2010.
Install it.

*Open Windows explorer (the file browser) and search for the location of 'vcvarsall.bat' and cut it to your clipboard.

*run regedit from the Windows start key. You will need admin privilges.

*Add a registry entry to
HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\9.0\Setup\VC\ProductDir (64 bit Windows) or
HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\Setup\VC\ProductDir (32 bit)
as described here.
Hint: 0.9 in the registery directory is the currently installed version of your visual studio, if you running VS 2013, you have to find the path HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\12.0....

*

*At the Windows start key, type cmd to get a command shell. If you need to, go to your virtual environment and run activate.bat.

*pip install  or whatever you use to install it.

A: You could use ol' good easy_install zipline instead.
easy_install isn't pip but one good aspect of it is the ability to download and install binary packages too, which would free you for the need having VC++ ready. This of course relies of the assumption that the binaries were prepared for your Python version.
UPDATE:
Yes, Pip can install binaries now!
There's a new binary Python archive format (wheel) that is supposed to replace "eggs". Wheels are already supported by pip. This means you'll be able to install zipline with pip without compiling it as soon as someone builds the wheel for your platform and uploads it to PyPI.

A: You need to have Visual Studio's bin dir in your path. Pip install is trying to compile some C code.

A: I spent hours researching this vcvarsall.bat as well. Most answers on SO focus on Python 2.7 and / or creating workarounds by modifying system paths. None worked for me. This solution worked out of the box for Python 3.5 and (I think) is the "correct" way of doing it.

*

*See this link -- it describes the Windows Compilers to use for different versions of Python: https://wiki.python.org/moin/WindowsCompilers#Microsoft_Visual_C.2B-.2B-_14.0_standalone:_Visual_C.2B-.2B-_Build_Tools_2015_.28x86.2C_x64.2C_ARM.29

*For Python 3.5, download this: https://www.microsoft.com/en-us/download/details.aspx?id=49983

*For me, I had to run C:\Program Files (x86)\Microsoft Visual C++ Build Tools\Visual C++ x64 Native Build Tools Command Prompt for it to work. From that command prompt, I ran "pip install django_compressor" which was the particular package that was causing me an issue, and it worked perfectly.
Hope this saves someone some time!

A: Thanks to "msoliman" for his hint, however his answer doesn't give clear solution for those who doesn't have VS2010
For example I have VS2012 and VS2013 and there are no such KEYs in system registry.
Solution:
Edit file: "[Python_install_loc]/Lib/distutils/msvc9compiler.py"
Change on line 224:
productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
                               "productdir")

to:
productdir = "C:\Program Files (x86)\Microsoft Visual Studio [your_vs_version(11/12...)]\VC"

and that should work

A: If you are trying to install matplotlib in order to work with graphs on python. Try this link.
https://github.com/jbmohler/matplotlib-winbuild.
This is a set of scripts to build matplotlib from source on the MS Windows platform.
To build & install matplotlib in your Python, do:
git clone https://github.com/matplotlib/matplotlib
git clone https://github.com/jbmohler/matplotlib-winbuild
$ python matplotlib-winbuild\buildall.py

The build script will auto-detect Python version & 32/64 bit automatically.

A: I appreciate this might not be the answer to resolving on 3.4 but I tried a huge variety of things to fix this on 3.4 and thought this might be useful if someone is time pressed or doesn't have the know-how to correct it (in my case, work demands).
With exactly the same setup, I found that my installation problems only happened with Python 3.4.  When I changed to 2.7, all my issues seemed to be resolved.
We have a rather overzealous security setup though so I'm going to try the same on my home version (still 3.4) and see if I have any more joy.  My inclination is that my VS version has somehow been restricted and the answers above should help.  If I find anything more tonight I'll add further detail.
This is my first reply, not the most technical I'm afraid!


text:
Q: useLinking with callback ref I'm trying to implement deep linking for my app using react-navigation v5.
I would like to set my navigationContainer ref to the useLinking hook from react-native, and at the same time, set the ref to my top level navigator :
const AppNavigationContainer: FC = () => {
    let navigatorRef;
    const [isReady, setIsReady] = useState<boolean>(false);
    const [initialState, setInitialState] = useState();
    const {getInitialState} = useLinking(navigatorRef, {
        prefixes: [prefix]
    });

    useEffect(() => {
        Promise.race([
            getInitialState(),
            new Promise(resolve => setTimeout(resolve, 150))
        ])
            .catch(console.log)
            .then(state => {
                if (state !== undefined) {
                    setInitialState(state);
                }
                setIsReady(true);
            });
    }, [getInitialState]);

    if (!isReady) {
        return null;
    }
    return (
        <NavigationContainer
            ref={(ref) => {
                NavigationService.setTopLevelNavigator(ref);
                navigatorRef = ref;
            }}
            initialState={initialState}
        >
            <StartupNavigator initialRouteName={Routes.CHECK}/>
        </NavigationContainer>
    );
}

But here, i got undefined is not an object (evaluating 'ref.current') from the useLinking hooks.
How to set my ref to the useLinking and at the same time, set to my top level navigator ?

A: You can set the current property of the ref:
const navigatorRef = React.useRef();

// ...

return (
    <NavigationContainer
        ref={(ref) => {
            NavigationService.setTopLevelNavigator(ref);
            navigatorRef.current = ref;
        }}
        initialState={initialState}
    >
        <StartupNavigator initialRouteName={Routes.CHECK}/>
    </NavigationContainer>
);


text:
Q: Magento 1.9 - Add custom zipcode validation on Home page Validate a zip code field on a home page popup in Magento 1.9 style might be using jquery button click.

A: If you use the standard Magento form validation you can do this by adding the css class validate-zip to your form field. That will pass the form input to the corresponding method in validatation.js.
I hope that helps.


text:
Q: Exit Telnet Through Batch File I've been asked to write a script in work that will send an email to our support email if an IP stops allowing us access to telnet on port 23. I've got the gist of what I need, but when the IP doesn't deny access, the script opens telnet and I can't get it to close using a command in the batch file.
This is what I've got so far. Sorry if there is already a question which answers this, I haven't been able to find it.
@ECHO OFF
set IPADDRESS=1.2.3.4
set INTERVAL=5

telnet %IPADDRESS% 23
if errorlevel 1 GOTO LOG

:LOG
ECHO %DATE% %TIME% %IPADDRESS% Could Not Be Reached >> failurelog.txt
GOTO MAIL

:MAIL
blat -install smtpserver
blat failurelog.txt -to email -subject "%IPADDRESS% Is Down"
timeout %INTERVAL%
exit


text:
Q: CentOS 8 Cgroup (or v2) installation without CWP We are trying to install cgroup v2 to our centOS 8 virtual servers but after all configs we can limit memory bu we can't limit cpu. We can't see the cpu.max (sys/fs/cgroup/user.slice)
Has cgroup v2 got full support on CentOS 8 ? , we don't have any idea on this. (We must use centOS 8 , can't be Rhel 8)
Do you have any idea or solution about how cgroup V2 works on CentOS 8 without CWP ?
Thank You for All

A: ##https://www.redhat.com/en/authors/marc-richter
#https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/pdf/managing_monitoring_and_updating_the_kernel/Red_Hat_Enterprise_Linux-8-Managing_monitoring_and_updating_the_kernel-en-US.pdf

*

*GRUB

grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="cgroup_no_v1=all"
reboot

*/usr/bin/configure_cgroups.sh

#!/bin/bash

touch /var/tmp/configure_cgroups.sh.ok

mkdir -p /mnt/cgroupv2

if [ ! -f /mnt/cgroupv2/cgroup.subtree_control ]
then
    mount -t cgroup2 none /mnt/cgroupv2
    echo "+cpu" > /mnt/cgroupv2/cgroup.subtree_control
    echo "+cpuset" > /mnt/cgroupv2/cgroup.subtree_control
    echo "+memory" > /mnt/cgroupv2/cgroup.subtree_control
fi

##cpuNo=0
numberfCpus=$(nproc --all)
numberOfUsers=$(ls /home| wc -l)
cpuShare=$((numberfCpus*100000/numberOfUsers))
totalMemory=$(cat /proc/meminfo | grep MemTotal| awk '{print $2}')
memoryShare=$((totalMemory/numberOfUsers*1024))
for username in $(ls /home)
do
  if [ ! -d /mnt/cgroupv2/user.$username ]
  then
      mkdir -p /mnt/cgroupv2/user.$username
      ##echo "$cpuNo" > /mnt/cgroupv2/user.$username/cpuset.cpus
      ##echo "$cpuNo" > /mnt/cgroupv2/user.$username/cpuset.mems
      echo "$cpuShare 100000" > /mnt/cgroupv2/user.$username/cpu.max
      echo "$memoryShare" > /mnt/cgroupv2/user.$username/memory.max
      ##cpuNo=$((cpuNo+1))
  fi

done

for username in $(ls /home)
do
      for pid in $(ps -ef |  grep -i "^$username" | awk '{print $2}')
      do
         grep $pid /mnt/cgroupv2/user.$username/cgroup.procs >/dev/null
         if [ $? != 0 ]
         then
             echo $pid > /mnt/cgroupv2/user.$username/cgroup.procs
         fi
      done
done

*SERVICE : /usr/lib/systemd/system/configure-cgroupsv2.service

[Unit]
Description=Configure CGroups V2

[Service]
Type=oneshot
ExecStart=/usr/bin/configure_cgroups.sh

*SERVICE : /usr/lib/systemd/system/configure-cgroupsv2.timer

[Unit]
Description=Configure CGroups V2 Timer

[Timer]
OnUnitActiveSec=10s
OnBootSec=10s

[Install]
WantedBy=timers.target

systemctl daemon-reload
systemctl enable configure-cgroupsv2.timer
systemctl start configure-cgroupsv2.timer

systemctl list-timers --all| grep configure

systemctl start configure-cgroupsv2.service
systemctl status configure-cgroupsv2.service
journalctl -xe

*Testing :

CPU: "while true; do   echo > /dev/null; done"  then  top

RAM :  "cat /dev/zero | head -c 20000M | tail " then top

A: Also , you must do the following to be able to run your docker images :
1. yum install crun -y

2. cp  /usr/share/containers/containers.conf /etc/containers/

3. edit  /etc/containers/containers.conf
   cgroups="disabled"
   runtime="crun"


text:
Q: How to detect and echo the last vowel in a word? $word = "Acrobat" (or Apple, Tea etc.)

How can I detect and echo the last vowel of a given word with php? I tried preg_match function, google'd for hours but couldn't find a proper solution.
There can be multibyte letters like ü, ö in the string.

A: Here's a multibyte safe version of catching the last vowel in a string.
$arr = array(
    'Apple','Tea','Strng','queue',
    'asartä','nő','ağır','NOËL','gør','æsc'
);

/*  these are the ones I found in character viewer
    in Mac so these vowels can be extended. don't
    forget to add both lower and upper case versions
    of new ones because personally I wouldn't rely
    on the i (case insensitive) flag in the pattern
    for multibyte characters.
*/
$vowels =
    'aàáâãāăȧäảåǎȁąạḁẚầấẫẩằắẵẳǡǟǻậặæǽǣ' .
    'AÀÁÂÃĀĂȦÄẢÅǍȀȂĄẠḀẦẤẪẨẰẮẴẲǠǞǺẬẶÆǼǢ' .
    'EÈÉÊẼĒĔĖËẺĚȄȆẸȨĘḘḚỀẾỄỂḔḖỆḜ' .
    'eèéêẽēĕėëẻěȅȇẹȩęḙḛềếễểḕḗệḝ' .
    'IÌÍÎĨĪĬİÏỈǏỊĮȈȊḬḮ' .
    'iìíîĩīĭıïỉǐịįȉȋḭḯ' .
    'OÒÓÔÕŌŎȮÖỎŐǑȌȎƠǪỌØỒỐỖỔȰȪȬṌṐṒỜỚỠỞỢǬỘǾŒ' .
    'oòóôõōŏȯöỏőǒȍȏơǫọøồốỗổȱȫȭṍṏṑṓờớỡởợǭộǿœ' .
    'UÙÚÛŨŪŬÜỦŮŰǓȔȖƯỤṲŲṶṴṸṺǛǗǕǙỪỨỮỬỰ' .
    'uùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự'
;

// set necessary encodings
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');

// and loop
foreach ($arr as $word) {

    $vow = mb_ereg_replace('[^'.$vowels.']','',$word);
    // get rid of all consonants (non-vowels in this pattern)
    $lastVw = mb_substr($vow,-1);
    // and get the last one from the remaining vowels

    if (empty($lastVw))
    // it evaluates this line when there's no vowel in the string
        echo "there's no vowel in \"$word\"." . PHP_EOL;
    else
    // and vice versa
        echo "last vowel in \"$word\" is " .
        "{$lastVw}" . PHP_EOL;
}

Here's the output.

last vowel in "Apple" is e
  last vowel in "Tea" is a
  there's no vowel in "Strng".
  last vowel in "queue" is e
  last vowel in "asartä" is ä
  last vowel in "nő" is ő
  last vowel in "ağır" is ı
  last vowel in "NOËL" is Ë
  last vowel in "gør" is ø
  last vowel in "æsc" is æ

A: $word = "Acrobat";
$vowels = array_intersect(str_split($word), array('A','E','I','O','U','a','e','i','o','u'));
echo array_pop($vowels);

A: function last_vowel($word) {
  for ($i = strlen($word) - 1; $i >= 0; --$i) {
      switch (strtolower($word[$i])) {
        case 'a': case 'e': case 'i': case 'o': case 'u': case 'y':
          return $word[$i];
      }
  }
  return null;
}

echo last_vowel("Apple");

A: use the method str_split()
http://www.php.net/manual/en/function.str-split.php
this will transform your string into an array then you can use the index of the array in finding the
first and last letter of your string.
-Array[0] is the first letter
*Array[total number of letters - 1] is the last letter.
After getting the first and last elements in the array, the mapping begins. eg:
    if(letter=="a"||letter=="A")
     echo "Apple";
and so on...

A: I would say Ed or Mark's answers are definitely more efficient, but if you want an example of a recursive function here it is:
$word = "stellar";

function lastVowel($word)
{
    $vowels = array('a','e','i','o','u');
    $letter = substr($word, strlen($word) - 1);
    if(in_array(strtolower($letter), $vowels))
        return $letter;
    else
    {
        if(strlen($word) > 0)
            return lastVowel(substr($word, 0, strlen($word) - 1));
        else
            return "no vowels";
    }
}

echo lastVowel($word);

Mind you, there are better ways to do this. Just giving a specific example, not necessarily the "best" one.

A: I would personally use preg_match() for this task.
$arr = array(
    'Apple','Tea','Strng','queue'
);

foreach ($arr as $word) {

    preg_match('~[aeiou](?=[^aeiou]*$)~i',$word,$m);

    if (empty($m)) echo "there's no vowel in \"$word\".";
    else echo "last vowel in \"$word\" is {$m[0]}";
    echo PHP_EOL;
}

This will output

last vowel in "Apple" is e
  last vowel in "Tea" is a
  there's no vowel in "Strng".
  last vowel in "queue" is e


text:
Q: Get the column names of a python numpy array I have a csv data file with a header indicating the column names.
xy   wz  hi kq
0    10  5  6
1    2   4  7
2    5   2  6

I run:
X = np.array(pd.read_csv('gbk_X_1.csv').values)

I want to get the column names:
['xy', 'wz', 'hi', 'kg']

I read this post but the solution provides me with None.

A: Let's assume your csv file looks like
xy,wz,hi,kq
0,10,5,6
1,2,4,7
2,5,2,6

Then use pd.read_csv to dump the file into a dataframe
df = pd.read_csv('gbk_X_1.csv')

The dataframe now looks like
df

   xy  wz  hi  kq
0   0  10   5   6
1   1   2   4   7
2   2   5   2   6

It's three main components are the

*

*data which you can access via the values attribute
df.values

array([[ 0, 10,  5,  6],
       [ 1,  2,  4,  7],
       [ 2,  5,  2,  6]])

*index which you can access via the index attribute
df.index

RangeIndex(start=0, stop=3, step=1)

*columns which you can access via the columns attribute
df.columns

Index(['xy', 'wz', 'hi', 'kq'], dtype='object')

If you want the columns as a list, use the to_list method
df.columns.tolist()

['xy', 'wz', 'hi', 'kq']

A: Use the following code:
import re

f = open('f.csv','r')

alllines = f.readlines()
columns = re.sub(' +',' ',alllines[0]) #delete extra space in one line
columns = columns.strip().split(',') #split using space

print(columns)

Assume CSV file is like this:
xy   wz  hi kq
0    10  5  6
1    2   4  7
2    5   2  6


text:
Q: c# Shorten int into case sensitive code There are 26 characters in the alphabet (abc..yz) and 10 digits (0..9).  That gives us a lexicon of 62 characters to use if we go case sensitive.
At the moment we are building a part of a filename based on an ID in our database.  These numbers can get quite long so we would like to shorten them.  For example instead of having:
file_459123.exe

We would rather:
file_aB5.exe

Does anyone have a method in C# that can convert an int into a shorter case sensitive string, and convert a case sensitive string back into an int?
Example (doesn't have to be this pattern):
1 = 1
2 = 2
...
9 = 9
10 = a
11 = b
...
36 = z
37 = A

A: Despite the Base64 references, here's a generic (non-optimized) solution:
// for decimal to hexadecimal conversion use this:
//var digits = "0123456789abcdef".ToCharArray();

var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
             .ToCharArray();

int number = 459123;
string output = "";

do
{
    var digit = digits[(int)(number%digits.Length)];
    output = output.Insert(0, digit.ToString());
    number = (int)number/digits.Length;
}
while (number > 0);

// output is now "1Vrd"

A: Try  Base64

A: just expanding M4Ns solution to a generic class....
  public class BaseX
    {
        private readonly string _digits;

        public BaseX(string digits)
        {
            _digits = digits;
        }
        public string ToBaseX(int number)
        {
            var output = "";
            do
            {
                output = _digits[number % _digits.Length] + output;
                number = number / _digits.Length;
            }
            while (number > 0);
            return output;
        }

        public int FromBaseX(string number)
        {
            return number.Aggregate(0, (a, c) => a*_digits.Length + _digits.IndexOf(c));
        }
    }

and then you can do...
var x = new BaseX("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
            Console.WriteLine(x.ToBaseX(10));
            Console.WriteLine(x.ToBaseX(459123));
            Console.WriteLine(x.ToBaseX(63));

            Console.WriteLine(x.FromBaseX("1Vrd"));
            Console.WriteLine(x.FromBaseX("A"));

            var bin = new BaseX("01");
            Console.WriteLine(bin.ToBaseX(10));

A: Depending on your situation you might want to look at using Base32 as the restricted character set may be easier to read (I.E., some users cannot easily distinguish the difference between zero and the letter o).
You can find examples here and here.


text:
Q: Adding animation CSS class with Jquery for twitch status I am trying to add a css style on an element based on whether my twitch status is live or not.  Sort of like a beacon.  I cannot seem to get it to add the css style to the object. if I add the animation style property directly in the html it does work, but need it wrapped around an if statement based on the twitch status. Here is the script code which sits in my header.

Here is the HTML line with the css class i am trying to alter.

I have also have the code in JSFIDDLE.  https://jsfiddle.net/LYv3R/407/

A: Your selector should have the . to identify the class elements. Not providing the dot, will search for the fa and fa-twitch tag names instead.
$('fa fa-twitch')

should be
$('.fa.fa-twitch')

As the 2 classes are present on the same selector. The way you have written would try to find a child with class fa-twitch
Also make sure you code is inside dom ready.
Check Fiddle


text:
Q: Facebook Webhooks doesn't receive any message I have a Developer Account, I have a Facebook Fans Page, and I have a Facebook App which link to Facebook Fans Page. I also deploy the backend to heroku successfully. And I also have access token, and Webhooks url and verify token still complete.
Through the curl by cmd, the backend receive message successfully. But through the Facebook Messenger webpage to send message, the backend can't receive any message from any user.
Why???
https://developers.facebook.com/docs/messenger-platform/getting-started/app-setup/
I follow this document, but not working.


text:
Q: Пример Android приложения на Delphi XE - БД изображений и способы ее передачи на ПК Помогите с примерами на Delphi XE5-8.
Система будет состоять из 2-х частей: приложение на Андроид - дневник, где пользователь делает записи, приклепляет фото c камеры или галереи.
Приблизительно раз в неделю пользователь будет подключать планшет к ПК и по нажатию кнопки сливать накопленный материал (фотографий 100-300)
Вопросы:
1) Есть ли пример такого приложения на Андроид:
блокнот с возможностью прикрепления изображений. Как это делать примерно понятно, но рабочий пример бы сильно помог.
2) Перекачивать данные на ПК. Есть ли пример приложения на Андроиде(передатчик), которое закачивает/копирует Базу с изображениями в приложение на Windows(приемник), или другой пример массовой перекачки фотографий по App tethering например.

A: Раз вы нашли упоминание про AppTethering (что уже неплохо), можете посмотреть примеры с ним, которые входят в комплект поставки Delphi. Наиболее полезным в вашем случае будет пример PhotoWall (если установка RAD Studio проводилась с путями по умолчанию, то он находится в папке C:\Users\Public\Documents\Embarcadero\Studio\17.0\Samples\Object Pascal\RTL\Tethering\PhotoWall), где как раз пересылаются фотографии.
Какие компоненты нужно задействовать для "дневника" - зависит от дизайна приложения. В простейшем случае - это список из TMemo и нескольких TImage, добавляемых динамически. Более сложный, но возможно более красивый - использовать RichEdit. На текущий момент бесплатных версий такого компонента для FMX пока не существует. На сайте fire-monkey.ru Ярослав Бровин только готовит свой компонент к релизу. Из платных стоит посмотреть в сторону TMS FMX Pack.
Уточнение 1: RAD XE5 не будет работать с последними версиями Android, лучше перейти на RAD Seattle.
Уточнение 2: AppTethering не работает через интернет. Оба приложения должны находиться в одной сети.
Минусы вам сыпятся из-за отсутствия конкретики: "я попробовал вот так (кусок кода), не получается вот это. Как мне обойти сей недостаток?


text:
Q: How to write multiple exceptions within a method when it is being discouraged in C#? My code just looks like this:
try
{
   foo();
}
catch (SecurityTokenValidationException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
    return null;
}
catch (SignatureVerificationFailedException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
    return null;
}

But the code analysis reports "Avoid Excessive Complexity"
Any pointers ?

A: If you are using C# 6 you can restrict the handling to your two types with exception filtering:
try
{
    foo();
}
catch (Exception ex) when (ex is SecurityTokenValidationException || ex is SignatureVerificationFailedException)
{
    Logger.ErrorFormat(ex.Message, ex);
    return null;
}

So you don't have to potentially catch other sub types of SecurityTokenException by mistake.

A: You can for example simplify return statements, by using return null only in case something failed.
Here are some pseudo code examples:
bool success;
try
{
   success = foo();
}
catch (SecurityTokenValidationException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
}
catch (SignatureVerificationFailedException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
}

if(success)
{
    return result;
}

return null;

Or another example.
try
{
   return foo();
}
catch (SecurityTokenValidationException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
}
catch (SignatureVerificationFailedException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
}

return null;

A: Finally, I resorted to using an exception which is the base class of the above two exceptions.
In other words,
try
{
   foo();
}
catch (SecurityTokenException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
    return null;
}

Both SecurityTokenValidationException1 and SignatureVerificationFailedException derives from SecurityTokenException.
Now, code analysis is happy :)


text:
Q: dynamic data - all option in paging I'm developing a dynamic data web app. On list.aspx page it has GridViewPager control for paging, it option in drop down list as 10,20,.. rows in a page like that, but it does not an option show all rows in a page.
How I can add "All" option in it?

A: I assume you are referring to a GridView and the automatic paging functionality included. If not please clarify. However, if this is the case then the default paging options do not include a show all. You can roll your own, I would start here: http://msdn.microsoft.com/en-us/library/5aw1xfh3.asp

A: In content folder Dynamic Data site lies the code for GridViewPager control.
What I have done is I added "All" option in dropdown list with values 0, and in the code behind file in function DropDownListPageSize_SelectedIndexChanged I check if selected value is 0 then set AllowPaging = false else true.
protected void DropDownListPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (_gridView == null)
        {
            return;
        }
        DropDownList dropdownlistpagersize = (DropDownList)sender;
        int sz=Convert.ToInt32(dropdownlistpagersize.SelectedValue);
        //_gridView.PageSize = Convert.ToInt32(dropdownlistpagersize.SelectedValue);
        if (sz<=0)
        {
            _gridView.AllowPaging = false;
            //_gridView.DataBind();
            //return;
        }
        else
        {
            _gridView.AllowPaging = true;
            _gridView.PageSize = sz;
            _gridView.AllowPaging = true;
        }
        int pageindex = _gridView.PageIndex;
        _gridView.DataBind();
        if (_gridView.PageIndex != pageindex)
        {
            //if page index changed it means the previous page was not valid and was adjusted. Rebind to fill control with adjusted page
            _gridView.DataBind();
        }
    }

A: You will have to implement your own pager and attached it to the Gridview. Default pager will not give you this option. May be this link could help you. http://www.codeproject.com/KB/grid/GridView_pager.aspx


text:
Q: How to use TestNG listener with Extent reports 4 I'm trying to figure out how to use the listeners in order to add them to my testso after each test the reports will be generated automaticly,
my structure looks like these:

and where it's red there i want to add the listeners,
my extentmanager class looks like these:
public class ExtentManager {
    public  ExtentReports extent;
    public  ExtentTest test;
    public  ExtentHtmlReporter htmlReporter;
    public  String reportDate;
    public  String filePath;

    public  void init() {
        reportDate = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());
        filePath = ".\\reports\\OrangeHRM Report "+ reportDate;
        htmlReporter = new ExtentHtmlReporter(filePath+"/report.html");
        new File(filePath).mkdirs();

        extent = new ExtentReports();
        extent.attachReporter(htmlReporter);

        htmlReporter.config().setDocumentTitle("automation report on OrangeHRM");
        htmlReporter.config().setReportName("OrangeHRM Test");
        htmlReporter.config().setEncoding("windows-1255");
    }

    public void create_test(String testName, String testDescription)
    {
        test = extent.createTest (testName, testDescription);
    }

    public String CaptureScreen() throws AWTException, IOException
    {
        String picDate = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());
        String imagePath = filePath+"/pic"+picDate+".jpg";
        Robot robot = new Robot();
        BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(screenShot, "jpg", new File(imagePath));
        return imagePath;
    }
}

and after it at BaseTest class i called the method init(); to start the extentReports, than MainRunner extends BaseTest and there each tese is marked with test.pass or test.fail - using IF.
i want to avoid it and to use the listeners so eacg test is working with assert so it can be mark the result at the listener and than to the report, so how to do it?
also, what is the difference in the listeners?


text:
Q: How to adjust Screen Resolution?
In android there are many different types of screen Resolutions available. How to adjust the screen resolutions using java code?

A: There is no way to alter the screen resolution programmatically. AFAIK, you'd need to do a hardware level modification to change it.
Instead, you must write your app in a manner that it scales well across displays. Use multiple images for different sizes and densities, use dp units instead of px units. Make layouts for different screen sizes. All of this and more is explained in the online documentation here.

A: If you are asking about how to make your App adjust to the device resolution, you should read the screen resolution using code below and make your app fill the space as your wish.
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

As there are 1000s of different Android devices, you just can't have a single line of code to do it automatically for you.
If you are speaking about changing the screen resolution like in PCs. LCD screens have native resolutions which cannot be altered. However, in PCs, the driver or the hardware behind the monitor change the resolution by considering consecutive pixels as single pixel. This option is added in high resolution monitors just to keep the compatibility with old video cards. In mobile phones, we do not have a need for doing this, so there is no such options. When LCD monitors replaced CRT, they had a need to work in different resolutions like CRT which can work on more than one native resolutions.

A: public int AR(int input)
{
    final float scale = getResources().getDisplayMetrics().density;
    return (int) (input * scale + 0.5f);
}

where, input is the value you want to use.
     Example:

ImageView TitleImage = new ImageView(this);
TitleImage.setPadding(AR(10), AR(5), AR(2), AR(3));

NOW THE IMAGE PADDING SUITS ALL KINDS OF RESOLUTIONS.


text:
Q: "Nice pub this" – what does it mean? I saw a video where this British person says "Nice pub this" and I'm wondering if that's actually a shorter way of saying "[A] nice pub this [is]."
Is this construction common in everyday British English? Does this form exist in American English at all?

A: Odd question, this.
I suppose to non-native Englishspeakers this may seem a bit "Yodish" (https://grammarpartyblog.com/2011/05/04/speaking-yodish/)...
But native speakers do tend to express themselves in similarly flexible ways.


text:
Q: Force MySQL 4.1 return to Decimal type I'm using JDBC to access a MySQL 4.1 database and have problems with queries of Decimal type.  When I do a query on a single Decimal column (i.e., SELECT amount AS v FROM Customer) I get a BigDecimal through the JDBC driver, but when I do an an operation of Decimal columns (i.e., SELECT amount + tax AS v FROM Customer) I get a Double even all columns involved in the operation are Decimal.  Is there ay way in which I can Convert or Cast the result to a Decimal.  I've tried CAST and CONVERT unsuccessfully.

A: Some JDBC drivers allow to receive the value as several types (for example, you can call rs.getString(), even though the value is an INTEGER). Try to call getObject() or getBigDecimal() on the column and check what you get.

A: Have a look at the ROUND() function:
Quote:

The return type is the same type as
  that of the first argument (assuming
  that it is integer, double, or
  decimal).

This might work if it considers one of your columns to be the first argument, rather than the result of the expression.