text:
Q: How to use z-index in svg elements? I'm using the svg circles in my project like this,
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
</svg>

And I'm using the z-index in the g tag to show the elements the first. In my project I need to use only z-index value, but I can't use the z-index to my svg elements. I have googled a lot but I didn't find anything relatively.
So please help me to use z-index in my svg.
Here is the DEMO.

A: There is no z-index for svgs. But svg determines which of your elements are the uppermost by theire position in the DOM. Thus you can remove the Object and place it to the end of the svg making it the "last rendered" element. That one is then rendered "topmost" visually.

Using jQuery:
function moveUp(thisObject){
    thisObject.appendTo(thisObject.parents('svg>g'));
}

usage:
moveUp($('#myTopElement'));

Using D3.js:
d3.selection.prototype.moveUp = function() {
    return this.each(function() {
        this.parentNode.appendChild(this);
    });
};

usage:
myTopElement.moveUp();

A: This is the top Google result for searches regarding z-index and SVGs. After reading all the answers, some of which are very good, I was still confused.
So for rookies like me, here is the current summary, 9 years later in 2022.
You can't use z-index with SVGs.
In SVGs, z-index is defined by the order the element appears in the document.
If you want something to appear on top, or closer to the user, draw it last or insert it before. Source
SVG 2 could support z-index but might never come out
SVG 2 is a proposal to implement that and other features but it is at risk of never moving forward.
SVG 2 reached the Candidate Recommendation stage in 2016, and was revised in 2018 and the latest draft was released on 8 June 2021. Source
However it doesn't have a lot of support and very few people are working on it. Source So don't hold your breath waiting for this.
You could use D3 but probably shouldn't
D3 a commonly used to visualize data supports z-index by binding your z-index and then sorting but it is a large and complex library and might not be the best bet if you just want a certain SVG to appear on top of a stack.

A: The clean, fast, and easy solutions posted as of the date of this answer are unsatisfactory.  They are constructed over the flawed statement that SVG documents lack z order.  Libraries are not necessary either.  One line of code can perform most operations to manipulate the z order of objects or groups of objects that might be required in the development of an app that moves 2D objects around in an x-y-z space.
Z Order Definitely Exists in SVG Document Fragments
What is called an SVG document fragment is a tree of elements derived from the base node type SVGElement.  The root node of an SVG document fragment is an SVGSVGElement, which corresponds to an HTML5 <svg> tag.  The SVGGElement corresponds to the <g> tag and permits aggregating children.
Having a z-index attribute on the SVGElement as in CSS would defeat the SVG rendering model.  Sections 3.3 and 3.4 of W3C SVG Recommendation v1.1 2nd Edition state that SVG document fragments (trees of offspring from an SVGSVGElement) are rendered using what is called a depth first search of the tree.  That scheme is a z order in every sense of the term.
Z order is actually a computer vision shortcut to avoid the need for true 3D rendering with the complexities and computing demands of ray tracing.  The linear equation for the implicit z-index of elements in an SVG document fragment.
z-index = z-index_of_svg_tag + depth_first_tree_index / tree_node_qty

This is important because if you want to move a circle that was below a square to above it, you simply insert the square before the circle.  This can be done easily in JavaScript.
Supporting Methods
SVGElement instances have two methods that support simple and easy z order manipulation.

*

*parent.removeChild(child)

*parent.insertBefore(child, childRef)

The Correct Answer That Doesn't Create a Mess
Because the SVGGElement (<g> tag) can be removed and inserted just as easily as a SVGCircleElement or any other shape, image layers typical of Adobe products and other graphics tools can be implemented with ease using the SVGGElement.  This JavaScript is essentially a Move Below command.
parent.insertBefore(parent.removeChild(gRobot), gDoorway)

If the layer of a robot drawn as children of SVGGElement gRobot was before the doorway drawn as children of SVGGElement gDoorway, the robot is now behind the doorway because the z order of the doorway is now one plus the z order of the robot.
A Move Above command is almost as easy.
parent.insertBefore(parent.removeChild(gRobot), gDoorway.nextSibling())

Just think a=a and b=b to remember this.
insert after = move above
insert before = move below

Leaving the DOM in a State Consistent With the View
The reason this answer is correct is because it is minimal and complete and, like the internals of Adobe products or other well designed graphics editors, leaves the internal representation in a state that is consistent with the view created by rendering.
Alternative But Limited Approach
Another approach commonly used is to use CSS z-index in conjunction with multiple SVG document fragments (SVG tags) with mostly transparent backgrounds in all but the bottom one.  Again, this defeats the elegance of the SVG rendering model, making it difficult to move objects up or down in the z order.

NOTES:

*

*(https://www.w3.org/TR/SVG/render.html v 1.1, 2nd Edition, 16 August 2011)

3.3 Rendering Order Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document
  fragment getting "painted" first. Subsequent elements are painted on
  top of previously painted elements.
3.4 How groups are rendered Grouping elements such as the 'g' element (see container elements) have the effect of producing a temporary
  separate canvas initialized to transparent black onto which child
  elements are painted. Upon the completion of the group, any filter
  effects specified for the group are applied to create a modified
  temporary canvas. The modified temporary canvas is composited into the
  background, taking into account any group-level masking and opacity
  settings on the group.

A: Another solution would be to use divs, which do use zIndex to contain the SVG elements.As here:
https://stackoverflow.com/a/28904640/4552494

A: As others here have said, z-index is defined by the order the element appears in the DOM. If manually reordering your html isn't an option or would be difficult, you can use D3 to reorder SVG groups/objects.
Use D3 to Update DOM Order and Mimic Z-Index Functionality
Updating SVG Element Z-Index With D3
At the most basic level (and if you aren't using IDs for anything else), you can use element IDs as a stand-in for z-index and reorder with those. Beyond that you can pretty much let your imagination run wild.
Examples in code snippet

var circles = d3.selectAll('circle')
var label = d3.select('svg').append('text')
    .attr('transform', 'translate(' + [5,100] + ')')

var zOrders = {
    IDs: circles[0].map(function(cv){ return cv.id; }),
    xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),
    yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),
    radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),
    customOrder: [3, 4, 1, 2, 5]
}

var setOrderBy = 'IDs';
var setOrder = d3.descending;

label.text(setOrderBy);
circles.data(zOrders[setOrderBy])
circles.sort(setOrder);

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 100">
  <circle id="1" fill="green" cx="50" cy="40" r="20"/>
  <circle id="2" fill="orange" cx="60" cy="50" r="18"/>
  <circle id="3" fill="red" cx="40" cy="55" r="10"/>
  <circle id="4" fill="blue" cx="70" cy="20" r="30"/>
  <circle id="5" fill="pink" cx="35" cy="20" r="15"/>
</svg>

The basic idea is:

*

*Use D3 to select the SVG DOM elements.
var circles = d3.selectAll('circle')

*Create some array of z-indices with a 1:1 relationship with your SVG elements (that you want to reorder). Z-index arrays used in the examples below are IDs, x & y position, radii, etc....
var zOrders = {
    IDs: circles[0].map(function(cv){ return cv.id; }),
    xPos: circles[0].map(function(cv){ return cv.cx.baseVal.value; }),
    yPos: circles[0].map(function(cv){ return cv.cy.baseVal.value; }),
    radii: circles[0].map(function(cv){ return cv.r.baseVal.value; }),
    customOrder: [3, 4, 1, 2, 5]
}

*Then, use D3 to bind your z-indices to that selection.
circles.data(zOrders[setOrderBy]);

*Lastly, call D3.sort to reorder the elements in the DOM based on the data.
circles.sort(setOrder);

Examples

*

*You can stack by ID

*

*With leftmost SVG on top

*

*Smallest radii on top

*

*Or Specify an array to apply z-index for a specific ordering -- in my example code the array [3,4,1,2,5] moves/reorders the 3rd circle (in the original HTML order) to be 1st in the DOM, 4th to be 2nd, 1st to be 3rd, and so on...

A: We have already 2019 and z-index is still not supported in SVG.
You can see on the site SVG2 support in Mozilla that the state for z-index – Not implemented.
You can also see on the site Bug 360148 "Support the 'z-index' property on SVG elements" (Reported: 12 years ago).
But you have 3 possibilities in SVG to set it:

*

*With element.appendChild(aChild);

*With parentNode.insertBefore(newNode, referenceNode);

*With targetElement.insertAdjacentElement(positionStr, newElement); (No support in IE for SVG)

Interactive demo example
With all this 3 functions.

var state = 0,
    index = 100;

document.onclick = function(e)
{
    if(e.target.getAttribute('class') == 'clickable')
    {
        var parent = e.target.parentNode;

        if(state == 0)
            parent.appendChild(e.target);
        else if(state == 1)
            parent.insertBefore(e.target, null); //null - adds it on the end
        else if(state == 2)
            parent.insertAdjacentElement('beforeend', e.target);
        else
            e.target.style.zIndex = index++;
    }
};

if(!document.querySelector('svg').insertAdjacentElement)
{
    var label = document.querySelectorAll('label')[2];
    label.setAttribute('disabled','disabled');
    label.style.color = '#aaa';
    label.style.background = '#eee';
    label.style.cursor = 'not-allowed';
    label.title = 'This function is not supported in SVG for your browser.';
}
label{background:#cef;padding:5px;cursor:pointer}
.clickable{cursor:pointer}
With:
<input type="radio" name="check" onclick="state=0" checked/>appendChild()
<input type="radio" name="check" onclick="state=1"/>insertBefore()

<input type="radio" name="check" onclick="state=2"/>insertAdjacentElement()
<input type="radio" name="check" onclick="state=3"/>Try it with z-index

<svg width="150" height="150" viewBox="0 0 150 150">
    <g stroke="none">
        <rect id="i1" class="clickable" x="10" y="10" width="50" height="50" fill="#80f"/>
        <rect id="i2" class="clickable" x="40" y="40" width="50" height="50" fill="#8f0"/>
        <rect id="i3" class="clickable" x="70" y="70" width="50" height="50" fill="#08f"/>
    </g>
</svg>

A: Try to invert #one and #two. Have a look to this fiddle : http://jsfiddle.net/hu2pk/3/
Update
In SVG, z-index is defined by the order the element appears in the document. You can have a look to this page too if you want : https://stackoverflow.com/a/482147/1932751

A: Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.
var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);

Target: Is an element for which we need to bring it to top
svg: Is the container of elements

A: You can use use.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
    <use xlink:href="#one" />
</svg>

The green circle appears on top.
jsFiddle

A: Specification
In the SVG specification version 1.1 the rendering order is based on the document order:
first element -> "painted" first

Reference to the SVG 1.1. Specification

3.3 Rendering Order
Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements.

Solution (cleaner-faster)
You should put the green circle as the latest object to be drawn. So swap the two elements.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120">

   <circle fill="orange" cx="100" cy="95" r="20"/>

   <circle fill="green" cx="100" cy="105" r="20"/>
</svg>

Here the fork of your jsFiddle.
Solution (alternative)
The tag use with the attribute xlink:href (just href for SVG 2) and as value the id of the element. Keep in mind that might not be the best solution even if the result seems fine. Having a bit of time, here the link of the specification SVG 1.1 "use" Element.

Purpose:
To avoid requiring authors to modify the referenced document to add an ID to the root element.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="30 70 160 120">

    <circle id="one" fill="green" cx="100" cy="105" r="20" />

    <circle id="two" fill="orange" cx="100" cy="95" r="20" />

    <use xlink:href="#one"/>
</svg>

Notes on SVG 2
SVG 2 Specification is the next major release and still supports the above features.

3.4. Rendering order
Elements in SVG are positioned in three dimensions. In addition to their position on the x and y axis of the SVG viewport, SVG elements are also positioned on the z axis. The position on the z-axis defines the order that they are painted.
Along the z axis, elements are grouped into stacking contexts.
3.4.1. Establishing a stacking context in SVG
...
Stacking contexts are conceptual tools used to describe the order in which elements must be painted one on top of the other when the document is rendered, ...

*

*SVG 2 Support Mozilla - Painting

*How do I know if my browser supports svg 2.0

*Can I use SVG

*Deprecated XLink namespace For SVG 2 use href instead of the additional deprecated namespace xlink:href (Thanks G07cha)

A: Move to front by transform:TranslateZ
Warning: Only works in FireFox

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160" style="width:160px; height:160px;">
    <g style="transform-style: preserve-3d;">
        <g id="one" style="transform-style: preserve-3d;">
            <circle fill="green" cx="100" cy="105" r="20" style="transform:TranslateZ(1px);"></circle>
        </g>
        <g id="two" style="transform-style: preserve-3d;">
            <circle fill="orange" cx="100" cy="95" r="20"></circle>
        </g>
    </g>
</svg>

A: As discussed, svgs render in order and don't take z-index into account (for now). Maybe just send the specific element to the bottom of its parent so that it'll render last.
function bringToTop(targetElement){
  // put the element at the bottom of its parent
  let parent = targetElement.parentNode;
  parent.appendChild(targetElement);
}

// then just pass through the element you wish to bring to the top
bringToTop(document.getElementById("one"));

Worked for me.
Update
If you have a nested SVG, containing groups, you'll need to bring the item out of its parentNode.
function bringToTopofSVG(targetElement){
  let parent = targetElement.ownerSVGElement;
  parent.appendChild(targetElement);
}

A nice feature of SVG's is that each element contains it's location regardless of what group it's nested in :+1:

A: Using D3:
If you want to re-inserts each selected element, in order, as the last child of its parent.
selection.raise()

A: Using D3:
If you want to add the element in the reverse order to the data, use:
.insert('g', ":first-child")
Instead of .append('g')
Adding an element to top of a group element

A: A better example of use, that I've ended up using.
<svg>
  <defs>
    <circle id="one" fill="green" cx="40" cy="40" r="20" />
    <circle id="two" fill="orange" cx="50" cy="40" r="20"/>
  </defs>
  <use href="#two" />
  <use href="#one" />
</svg>

To control the order you can change href attribute values of these use elements. This can be useful for animation.
Thanks to defs, circle elements are drawn only once.
jsfiddle.net/7msv2w5d

A: its easy to do it:

*

*clone your items

*sort cloned items

*replace items by cloned

function rebuildElementsOrder( selector, orderAttr, sortFnCallback ) {
 let $items = $(selector);
 let $cloned = $items.clone();

 $cloned.sort(sortFnCallback != null ? sortFnCallback : function(a,b) {
    let i0 = a.getAttribute(orderAttr)?parseInt(a.getAttribute(orderAttr)):0,
        i1 = b.getAttribute(orderAttr)?parseInt(b.getAttribute(orderAttr)):0;
    return i0 > i1?1:-1;
 });

        $items.each(function(i, e){
            e.replaceWith($cloned[i]);
 })
}

$('use[order]').click(function() {
    rebuildElementsOrder('use[order]', 'order');

    /* you can use z-index property for inline css declaration
    ** getComputedStyle always return "auto" in both Internal and External CSS decl [tested in chrome]

    rebuildElementsOrder( 'use[order]', null, function(a, b) {
        let i0 = a.style.zIndex?parseInt(a.style.zIndex):0,
        i1 = b.style.zIndex?parseInt(b.style.zIndex):0;
    return i0 > i1?1:-1;
    });
    */
});
use[order] {
  cursor: pointer;
}

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="keybContainer" viewBox="0 0 150 150" xml:space="preserve">
<defs>
    <symbol id="sym-cr" preserveAspectRatio="xMidYMid meet" viewBox="0 0 60 60">
        <circle cx="30" cy="30" r="30" />
        <text x="30" y="30" text-anchor="middle" font-size="0.45em" fill="white">
            <tspan dy="0.2em">Click to reorder</tspan>
        </text>
    </symbol>
</defs>
    <use order="1" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="0" y="0" width="60" height="60" style="fill: #ff9700; z-index: 1;"></use>
    <use order="4" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="50" y="20" width="50" height="50" style="fill: #0D47A1; z-index: 4;"></use>
    <use order="5" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="15" y="30" width="50" height="40" style="fill: #9E9E9E; z-index: 5;"></use>
    <use order="3" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="25" y="30" width="80" height="80" style="fill: #D1E163; z-index: 3;"></use>
    <use order="2" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="30" y="0" width="50" height="70" style="fill: #00BCD4; z-index: 2;"></use>
    <use order="0" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="5" y="5" width="100" height="100" style="fill: #E91E63; z-index: 0;"></use>
</svg>

A: Just wanted to add a trick that works when you want to put a specific element on top.
function moveInFront(element) {
    const svg = element.closest('svg'); // Find the parent SVG
    svg.appendChild(element); // Append child moves the element to the end
}

This works because, and I quote the docs, "appendChild() moves [the element] from its current position to the new position" instead of adding a copy.

Note: If the element is nested, you would have to move the element to front within the group, and perhaps move the group to front as well.

A: use works for this purpose, but those elements that are placed with use help after is hard to manipulate...
What I couldn't figure out after I used it was: why I couldn't hover (neither mouseover, mouseenter manipulations from js would work) on the use elements to get additional functionality - like ~ showing text over the circles ~
After returned to circle reordering as it was only way to manipulate with those svg objects


text:
Q: Multithreading alternative to mutex in parallel_for I'm fairly new to C++, therefore please pardon if this is a stupid question, but I didn't find good example of what I'm looking for on the internet.
Basically I'm using a parallel_for cycle to find a maximum inside a 2D array (and a bunch of other operations in between). First of all I don't even know if this is the best approach, but given the length of this 2D array, I though splitting the calculations would be faster.
My code:
vector<vector<double>> InterpU(1801, vector<double>(3601, 0));
Concurrency::parallel_for(0, 1801, [&](int i) {

    long k = 0; long l = 0;
    pair<long, long> Normalized;
    double InterpPointsU[4][4];
    double jRes;
    double iRes = i * 0.1;
    double RelativeY, RelativeX;
    int p, q;

    while (iRes >= (k + 1) * DeltaTheta) k++;
    RelativeX = iRes / DeltaTheta - k;
    for (long j = 0; j < 3600; j++)
    {
        jRes = j * 0.1;
        while (jRes >= (l + 1) * DeltaPhi) l++;
        RelativeY = jRes / DeltaPhi - l;
        p = 0;
        for (long m = k - 1; m < k + 3; m++)
        {
            q = 0;
            for (long n = l - 1; n < l + 3; n++)
            {
                Normalized = Normalize(m, n, PointsTheta, PointsPhi);
                InterpPointsU[p][q] = U[Normalized.first][Normalized.second];
                q++;
            }
            p++;
        }
        InterpU[i][j] = bicubicInterpolate(InterpPointsU, RelativeX, RelativeY);
        if (InterpU[i][j] > MaxU)
        {
            SharedDataLock.lock();
            MaxU = InterpU[i][j];
            SharedDataLock.unlock();
        }
    }
    InterpU[i][3600] = InterpU[i][0];
});

You can see here that I'm using a mutex called SharedDataLock to protect multiple threads accessing the same resource. MaxU is a variable that should only containe the maximum of the InterpU vector.
The code works well, but since I'm having speed performance problem, I began to look into atomic and some other stuff.
Is there any good example on how to modify a similar code to make it faster?

A: As mentioned by VTT, you can simply find the local maximum of each thread, and merge those afterwards With use of combinable:
Concurrency::combinable<double> CombinableMaxU;
Concurrency::parallel_for(0, 1801, [&](int i) {
    ...
        CombinableMaxU.local() = std::max(CombinableMaxU.local(), InterpU[i][j]);
}
MaxU = std::max(MaxU, CombinableMaxU.combine(std::max<double>));

Note that your current code is actually wrong (unless MaxU is atomic), you read MaxU outside of the lock, while it can be written simultaneously by other threads. Generally, you must not read a value that is being written to simultaneously unless both sides are protected by atomic semantics or locks and memory fences. A reason is that a variable access may very well consist of multiple memory accesses, depending on how the type is supported by hardware.
But in your case, you even have a classic race condition:
MaxU == 1
  Thread a                 |   Thread b
InterpU[i][j] = 3          | InterpU[i][j] = 2
if (3 > MaxU)              |  if (2 > MaxU)
SharedDataLock.lock();     | SharedDataLock.lock();
(gets the lock)            | (waiting for lock)
MaxU = 3                   | ...
SharedDataLock.unlock();   | ...
...                        | (gets the lock)
                           | MaxU = 2
                           | SharedDataLock.unlock();
MaxU == 2

Locks are hard.
You can also use an atomic and compute the maximum on that. However, I would guess1 that it still doesn't perform well inside the loop2, and outside the loop it doesn't matter whether you use atomics or locks.
1: When in doubt, don't guess - measure!
2: Just because something is atomic and supported by hardware, doesn't mean it is as efficient as accessing local data. First, atomic instructions are often much more costly than their non-atomic counterparts, second you have to deal with very bad cache effects, because cores/caches will fight for the ownership of the data. While atomics may be more elegant in many cases (not this one IMHO), reduction is faster most of the time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding the "NOR" of two times I have a format of two arrays representing the start and end of a time slot, i.e 9am-5pm represented as:
int[] startTime = {9, 0};
int[] endTime = {17, 0};

The aim is to find, from a list of these (Held in a basic class, format is for ease of database entry), the periods of time in which no element occupies (I guess it could be referred to as NOR?). For example, when provided 09:00-14:00 and 16:00-17:00 (And suppose only entries between 9am-5pm are of interest), it should return 14:00-16:00.
The list is not particularly large, although it will likely contain duplicates and be out of order. I have no idea where to proceed at this point, any ideas?
To clarify: One list of times are being compared to another (Once is local, the other pulled from elsewhere)

A: Step 1: Sort intervals by (end time, start time), in ascending order
Step 2: Merge intervals if end_time(i) >= start_time(i+1)
At this point you have a deduplicated, sorted list of non-oberlapping intervals.
Step 3: Output all (end_time(i), start_time(i+1))

A: Can you read Scala code and translate it to Java yourself?
case class Interval (lower: Int, upper: Int) {
    def deflate () : List [Int] = {(lower to upper).toList}
}

def list2disjunctIntervals (li: List[Interval]) : List[Interval] = {
  val united = (li.flatMap (_.deflate).distinct).sorted

  def split (l: List [Int], sofar: List[Int]): List[List[Int]] = l match {
    case Nil => List (sofar)
    case h::t=> if (sofar.isEmpty) split (t, List (h)) else
      if (h == sofar.head + 1) split (t, h :: sofar)
      else sofar :: split (t, List (h))
  }

  val sublists = split (united, Nil)
  sublists.map (l => Interval (l.last, l.head))
}

Demo:
val li = List (Interval (0, 4), Interval (7, 12), Interval (1, 3), Interval (5, 8), Interval (15, 17), Interval (16, 22))

scala> list2disjunctIntervals (li)
res64: List[Interval] = List(Interval(0,12), Interval(15,22))

In prosa: Interval is a class, defined by its bounds. Deflate is the only method (so far) which produces - for an interval the values in that interval: (9, 12) => (9, 10, 11, 12)
list2disjunctIntervals takes a List of Intervals. It has an inner method united, which deflates all intervals, than reduces the values to distinct ones, and sorts them. So for (3,4)(6,9)(9,11) it produces (3,4,6,7,8,9,10,11).
Split takes this List, and divides it into multiple Lists: (3, 4) and (6,...11).
The last call is to generate new Intervals from the sublists.

A: Here is a rough Java approach:
import java.util.*;

class Interval {

    int lower, upper;

    Interval (int l, int u) {
      lower = l;
      upper = u;
    }

    boolean isMergeable (Interval other) {
        return (upper >= other.lower && lower <= other.upper);
    }
    /**
        if a contains b fully, result is a
        if b contains a fully, result is b
        if a and b don't overlap result is (a, b)
        if a and b overlap, result is Interval min(a.lower, b.lower), max(a.upper, b.upper)
        i(10,12).merge (13, 17) fails
    */
    List <Interval> merge (Interval other) {
      List <Interval> li = new ArrayList <> ();
        if (lower < other.lower && upper > other.upper)
          li.add (this);
        else if (lower > other.lower && upper < other.upper)
          li.add (other);
        else if (upper < other.lower || lower > other.upper)
          {li.add (this); li.add (other);}
        else
          li.add (new Interval (Math.min (lower, other.lower), Math.max (upper, other.upper)));
        return li;
    }

    // the usual, boring stuff from here
    @Override
    public String toString ()
    {
          return "[" + lower + ":" + upper + "]";
    }

    // to make List<Interval>.contains(interval) work
    @Override public boolean equals (Object o) {
      if (! (o instanceof Interval))
        return false;
      Interval other = (Interval)o;
      return lower == other.lower && upper == other.upper;
    }

    @Override
    public int hashCode () {
      return 1023*upper + lower;
    }
}

And a Test situation:
public class IntervalTest {

  static List <Interval> mergeList (List <Interval> li) {
    List <Interval> iset = new ArrayList <> ();
    for (Interval i1 : li) {
      Interval m = i1;
      for (Interval i2 : li)
        if (i2.isMergeable (m))
            m = i2.merge (m).get(0);
      if (! iset.contains (m))
          iset.add (m);
    }
    return iset;
  }

  public static void main (String[] args)
  {
    Interval[] ia = {new Interval (0, 4), new Interval (1, 2), new Interval (7, 12), new Interval (1, 3), new Interval (5, 8), new Interval (15, 17), new Interval (16, 19), new Interval (9, 13), new Interval (22, 23)};
    List<Interval> li = Arrays.asList (ia);
    System.out.println (li);
    System.out.println (mergeList (li));
  }
}

Output:
// atomic Intervals:
[[0:4], [1:2], [7:12], [1:3], [5:8], [15:17], [16:19], [9:13], [22:23]]
// merged:
[[0:4], [5:13], [15:19], [22:23]]

Note that the borders - are they included or not? - are differently understood in every day life, so when I say I watch TV from 1-3 and from 4-5, there is obviously a gap between 3 and 4.
But if I say quarter 1 goes from month 1-3 and quarter 2 from month 4 to 6, there is neither a gap between q1 and q2, nor between month 3 and month 4. The given algorithm makes a gap between 4 and 5 so this has to be adjusted if otherwise needed/preferred.
To find open time slots, you have to sort the merged array, and find (if any) time before the first interval, after the last interval and the intervals between.
But if, in your use case, the starting time 0-9 and 17-24 is always included in the List, you only have to search for the intervals between.


text:
Q: Fast vertex computation for near skeletal animation I am building a 3D flower mesh through a series of extrusions (Working in Unity 4 environment). For each flower there are splines that define each branch, petals, leaves etc. Around each spline there is a shape that is being extruded along that spline. And a thickness curve that defines at each point in the spline, how thick the shape could be.
I am trying to animate this mesh using parameters (i.e. look towards sun, bend with the wind).
I have been working on this for nearly two months and my algorithm boiled down to basically reconstructing the flower 'every frame', by iterating over the shape for each spline point, transforming it into the the current space and calculating new vertex positions out of it, a version of parallel transport frames.
for each vertex:
v = p + q * e * w

where
p = point on the path
e = vertex position in the local space of shape being extruded
q = quaternion to transform into the local space of the p (by its direction towards next path point)
w = width at point p

I believe this is as small of a step as it gets to extrude the model. I need to do this once for each vertex in the model basically.
I hit the point where this is too slow for my current scene. I need to have 5-6 flowers with total around 60k vertices and I concluded that this is the bottleneck.
I can see that this is a similar problem to skeletal animation, where each joint would control a cross-section of the extruded shape. It is not a direct question but I'm wondering if someone can elaborate on whether I can steal some techniques from skeletal animation to speed up the process. In my current perspective, I just don't see how I can avoid at least one calculation per vertex, and in that case, I just choose to rebuild the mesh every frame.


text:
Q: Binary numbers with at most I am trying to find how many binary numbers are there with $10$ digits if the first two must be $1$s.
I am thinking this to be $2^{10 - 2}$, but I'm not sure.

A: This is like the same problem as creating a $8$ digit number, then attaching two $1$s in front of it. Therefore, our answer is: $$2^8=\boxed{256}$$


text:
Q: parser sax in php with accented letters I have a problem with accented letters.
For example:
I have a tag that contains: "il mio prodotto é molto bello". However, the output is: "il mio prodotto "
When in xml, and there is an accented letter, the date is cut. I have a xml with:
<?xml version="1.0" encoding="utf-8"?>

Here is my parser code:
<?php
class Content_Handler {
   function Content_Handler(){}
   function start_element($parser, $name, $attrs) {
       global $desc, $names, $link;
       if ($name == "PRODUCT"){
          $zupid = ($attrs["ZUPID"]);
          echo "$zupid
";
       }
       if ($name == "DESCRIPTION") { $desc = true;}
       if ($name == "NAME") { $names = true;}
       if ($name == "DEEPLINK") { $link = true;}
   }

   function end_element($parser, $name) {
       if ($name == "PRODUCT") {
          print "
";
       }
   }

   function characters($parser, $chars) {
       global $desc, $names, $link;
       if ($desc) { echo $chars."
"; $desc = false;}
       if ($names) { echo $chars."
"; $names = false;}
       if ($link) { echo $chars."
"; $link = false;}
   }
}

$handler = new Content_Handler();
$cat_parser = xml_parser_create("UTF-8");

xml_parser_set_option($cat_parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
xml_set_object($cat_parser, $handler);
xml_set_element_handler($cat_parser, "start_element", "end_element");
xml_set_character_data_handler($cat_parser, "characters");

$file = "my.xml";

if ($file_stream = fopen($file, "r")) {

   while ($data = fread($file_stream, 4096)) {

       $this_chunk_parsed = xml_parse($cat_parser, $data, feof($file_stream));
       if (!$this_chunk_parsed) {
           $error_code = xml_get_error_code($cat_parser);
           $error_text = xml_error_string($error_code);
           $error_line = xml_get_current_line_number($cat_parser);

           $output_text = "Parsing problem at line $error_line: $error_text";
           die($output_text);
       }
   }
} else {

    die("Can't open XML file.");

}
xml_parser_free($cat_parser);

?>

A: This is the normal error when dealing with SAX parsing in what appears to be any language (see previous answers on java and C!).
When you are a parsing SAX events, the Characters function isn't the entire contents of the element between the start and end tag, it can be called many times, and when you are dealing with accented characters it is.
The full characters contents can only be determined by concatinating the values between a start and end tags.
so for your term '"il mio prodotto é molto bello', characters will be called probably 3 times, with 'il mio prodotto ', 'é' and ' molto bello', so you need to concatinate them, not use them as litterals.
Your 'characters' function should be more like:
function characters($parser, $chars) {
   global $desc, $names, $link;
   $fullchars .= $chars;
}

with your chars being used and reset in the end_element and start_element.


text:
Q: Heroku deplpy fails with '..bin/bundle: line 11: require: command not found... Failed to install gems via Bundler.' Im trying to deploy my Rails api-only application to Heroku and when I run git push heroku main, I got this error:
Counting objects: 100% (1198/1198), done.
Delta compression using up to 8 threads
Compressing objects: 100% (417/417), done.
Writing objects: 100% (1198/1198), 171.98 KiB | 21.50 MiB/s, done.
Total 1198 (delta 715), reused 1188 (delta 711), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote: -----> Using buildpacks:
remote:        1. heroku/ruby
remote:        2. https://github.com/heroku/heroku-buildpack-ruby.git
remote: -----> Ruby app detected
remote: -----> Installing bundler 2.2.21
remote: -----> Removing BUNDLED WITH version in the Gemfile.lock
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-3.0.2
remote: -----> Installing dependencies using bundler 2.2.21
remote:        Running: BUNDLE_WITHOUT='development:test' BUNDLE_PATH=vendor/bundle BUNDLE_BIN=vendor/bundle/bin BUNDLE_DEPLOYMENT=1 bundle install -j4
remote:        /tmp/build_814ed8d0/bin/bundle: line 11: require: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 13: m: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 14: module_function: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 16: def: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 17: syntax error near unexpected token `$PROGRAM_NAME'
remote:        /tmp/build_814ed8d0/bin/bundle: line 17: `    File.expand_path($PROGRAM_NAME) == File.expand_path(__FILE__)'
remote:        Bundler Output: /tmp/build_814ed8d0/bin/bundle: line 11: require: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 13: m: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 14: module_function: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 16: def: command not found
remote:        /tmp/build_814ed8d0/bin/bundle: line 17: syntax error near unexpected token `$PROGRAM_NAME'
remote:        /tmp/build_814ed8d0/bin/bundle: line 17: `    File.expand_path($PROGRAM_NAME) == File.expand_path(__FILE__)'
remote:
remote:  !
remote:  !     Failed to install gems via Bundler.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to murmuring-forest-17162.
remote:
To https://git.heroku.com/murmuring-forest-17162.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/murmuring-forest-17162.git'

My local file looks like that bin/bundle:
# frozen_string_literal: true

#!/usr/bin/env ruby
#
# This file was generated by Bundler.
#
# The application 'bundle' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

m = Module.new do
  module_function

  def invoked_as_script?
    File.expand_path($PROGRAM_NAME) == File.expand_path(__FILE__)
  end

  def env_var_version
    ENV['BUNDLER_VERSION']
  end

  def cli_arg_version # rubocop:disable Metrics/PerceivedComplexity, Metrics/MethodLength, Metrics/CyclomaticComplexity
    return unless invoked_as_script? # don't want to hijack other binstubs
    return unless 'update'.start_with?(ARGV.first || ' ') # must be running `bundle update`

    bundler_version = nil
    update_index = nil
    ARGV.each_with_index do |a, i|
      bundler_version = a if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
      next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/

      bundler_version = Regexp.last_match(1)
      update_index = i
    end
    bundler_version
  end

  def gemfile
    gemfile = ENV['BUNDLE_GEMFILE']
    return gemfile if gemfile && !gemfile.empty?

    File.expand_path('../Gemfile', __dir__)
  end

  def lockfile
    lockfile =
      case File.basename(gemfile)
      when 'gems.rb' then gemfile.sub(/\.rb$/, gemfile)
      else "#{gemfile}.lock"
      end
    File.expand_path(lockfile)
  end

  def lockfile_version
    return unless File.file?(lockfile)

    lockfile_contents = File.read(lockfile)
    return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/

    Regexp.last_match(1)
  end

  def bundler_version
    @bundler_version ||=
      env_var_version || cli_arg_version ||
      lockfile_version
  end

  def bundler_requirement
    return "#{Gem::Requirement.default}.a" unless bundler_version

    bundler_gem_version = Gem::Version.new(bundler_version)

    requirement = bundler_gem_version.approximate_recommendation

    return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new('2.7.0')

    requirement += '.a' if bundler_gem_version.prerelease?

    requirement
  end

  def load_bundler!
    ENV['BUNDLE_GEMFILE'] ||= gemfile

    activate_bundler
  end

  def activate_bundler # rubocop:disable Metrics/MethodLength
    gem_error = activation_error_handling do
      gem 'bundler', bundler_requirement
    end
    return if gem_error.nil?

    require_error = activation_error_handling do
      require 'bundler/version'
    end
    if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION))
      return
    end

    warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" # rubocop:disable Layout/LineLength
    exit 42
  end

  def activation_error_handling
    yield
    nil
  rescue StandardError, LoadError => e
    e
  end
end

m.load_bundler!

load Gem.bin_path('bundler', 'bundle') if m.invoked_as_script?

I have tried to change my ruby- and bundler- versions to same as Heroku uses, but result didn't change:
bundler -v
Bundler version 2.2.21

ruby -v
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-darwin20]

rbenv -v
rbenv 1.1.2

My Gemfile:
# frozen_string_literal: true

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '3.0.2'

gem 'bootsnap', '>= 1.4.4', require: false
gem 'bcrypt'
gem 'dry-monads'
gem 'grape-swagger'
gem 'grape-swagger-entity'
gem 'jwt'
gem 'net-http'
gem 'pg', '~> 1.1'
gem 'puma', '~> 5.0'
gem 'pundit'
gem 'rack-cors'
gem 'ransack', github: 'activerecord-hackery/ransack'
gem 'rails', '~> 6.1.4.1'
gem 'redis'
gem 'require_all'
gem 'strong_migrations'
gem 'uri'

group :development do
  gem 'database_consistency', require: false
  gem 'listen', '~> 3.3'
  gem 'rubocop', require: false
  gem 'rubocop-discourse', require: false
  gem 'rubocop-rails', require: false
  gem 'spring'
end

group :development, :test do
  gem 'bullet'
  gem 'bundler-audit'
  gem 'byebug', platforms: %i[mri mingw x64_mingw]
  gem 'dotenv-rails'
  gem 'factory_bot_rails'
  gem 'ffaker'
  gem 'rspec-rails', '~> 5.0.0'
end

group :test do
  gem 'rspec-sqlimit'
  gem 'shoulda-matchers', '~> 5.0'
  gem 'webmock'
end

gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby]

In the end of my Gemfile.lock:
...

RUBY VERSION
   ruby 3.0.2p107

BUNDLED WITH
   2.2.21

I've tried (as you can see in heroku logs) to connect different ruby buildpacks, but it didn't help.
I've tried to remove Gemfile.lock, reinstall gems and push updated file back to main branch, but it didn't help.
I've tried to install gems locally with same command as Heroku uses (BUNDLE_WITHOUT='development:test' BUNDLE_PATH=vendor/bundle BUNDLE_BIN=vendor/bundle/bin BUNDLE_DEPLOYMENT=1 bundle install -j4) and push to git vendor/bundle folder, but it didn't help.
I've tried to run git push heroku main:main as logs recommends, but it didn't help.
Every time I see the same error.
Anybody has ideas, what am I doing wrong and how to fix it? Thank you so much in advance!

A: The reason was in file bin/bundle. Since this is executable shell-file, first row here must be #!/usr/bin/env ruby. When I removed first few excess rows, Heroku read ruby files as I expected.
This is working version of bin/bundle:
#!/usr/bin/env ruby
#
# This file was generated by Bundler.
#
...


text:
Q: Binary input of text file Programming Principles and Practice says in the Chapter 11:
"In memory, we can represent the number 123 as an integer value (each int on 4 bytes) or as a string value (each character on 1 byte)".
I'm trying to understand what is stored in the memory, when reading binary a text file.
So I'm writing the content of the vector v.
If the input file contains this text: "test these words"
The output file shows these numbers: 1953719668 1701344288 1998611827 1935962735 168626701 168626701 168626701 168626701 168626701 168626701
I tried to convert each char of "test" to binary
and I have 01110100 01100101 01100101 01110100
and if I consider this as an integer of 4 bytes and convert it to decimal I get 1952802164, which is still different from the output.
How is this done correctly, so I can understand what's going on? Thanks!
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<sstream>
#include <fstream>
#include <iomanip>
using namespace std;

template <class T>
char *as_bytes(T &i) // treat a T as a sequence of bytes
{
    void *addr = &i; // get the address of the first byte of memory used to store the object
    return static_cast<char *>(addr); // treat that memory as bytes
}

int main()
{
    string iname{"11.9_in.txt"};
    ifstream ifs {iname,ios_base::binary}; // note: stream mode
    string oname{"11.9_out.txt"};
    ofstream ofs {oname,ios_base::binary}; // note: stream mode

    vector<int> v;
    // read from binary file:
    for(int x; ifs.read(as_bytes(x),sizeof(int)); ) // note: reading bytes
        v.push_back(x);

    for(int x : v)
        ofs << x << ' ';

}

A: Let me assume you are using little-endian machine (for example, x86) and ASCII-compatible character code (such as Shift_JIS and UTF-8).
test is represented as 74 65 73 74 as binary data.
Using little-endian, higher bytes of muitl-byte integer is placed to higher address.
Therefore, reading thes as 4-byte integer, it will be interpreted as 0x74736574 and it is 1953719668 in decimal.


text:
Q: How to set cookie in android WebView client I want to call one specific url via WebView. The page can only be called after user already logged in. I use AsyncHttpClient library to perform login call. Once after successfully logged in , loading url via WebView doesn't seem recognise the proper headers esp cookie. My suspect is that cookies are not sync correctly between HttpClient and WebView's HttpClient . Any idea why ? . Here is how i use WebView
    final WebView webView = (WebView) content.findViewById(R.id.web_travel_advisory);
    String url = "http://mydomainurl.com/get_data_after_login";

    webView.setWebViewClient(new WebViewClient());

    CookieSyncManager.createInstance(getActivity());
    CookieSyncManager.getInstance().startSync();
    CookieManager.getInstance().setAcceptCookie(true);

    webView.getSettings().setJavaScriptEnabled(true);

    webView.loadUrl(url);

Appreciate ur help .

A: Try this code, after few changes works for me:
public class WebViewActivity extends Activity{
    private SharedPreferences mPreferences;

    String token="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webviewpage);

        mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);

    }

    public void LaunchWebView(View view) {

        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setSaveFormData(false);

        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        CookieManager.getInstance().setAcceptThirdPartyCookies(myWebView, true);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String token2= mPreferences.getString("auth_token","");

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("x-auth-token", token);

        myWebView.getSettings().setAppCacheEnabled(true);
        myWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                view.loadUrl(url);
                return true;
            }
        });
        myWebView.loadUrl("YOUR_URL", map);
    }
}

A: Ohh after several hours, i finally figured it out to get it worked. Firstly CookieSyncManager is deprecated on later version of android since api 21 according to doc. So decided not to use it anymore. Secondly CookieManager is used to store cookie for WebView.
Final code
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    List<Cookie> cookies = WSHelper.cookieStore.getCookies();

    cookieManager.removeAllCookie();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().contains("session")){
                String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
                cookieManager.setCookie(cookie.getDomain(), cookieString);
                Log.d("CookieUrl",cookieString + " ");
            }
        }
    }
    webView.loadUrl(url);

The key changes to solution is: use cookie.getDomain() instead of explicit domain.
cookieManager.setCookie(cookie.getDomain(), cookieString);

A: My problem was slightly different, but answer from @Tixeon gave me the key to solve it. I was composing my Cookie and adding it to the WebView request, but I discovered that Android was overriding my Cookie and sending its own Cookie.
So first of all, I had to remove all cookies from the array, then compose my own Cookie. This is the sample code:
// Note that my project has minSdkVersion 21, so I can directly use methods only available in Lollipop
private fun loadUrlInWebView(url: String) {
    webView.settings.apply {
        builtInZoomControls = false
        javaScriptEnabled = true
        useWideViewPort = true
        loadWithOverviewMode = true
        setSupportMultipleWindows(false)
    }
    CookieManager.getInstance().apply {
        setAcceptThirdPartyCookies(webView, true) // My minSdkVersion is 21
        removeAllCookies { value ->
            Log.d("Cookies", "Removed all cookies from CookieManager")
        }
    }

    webView.apply {
        isVerticalScrollBarEnabled = true
        isHorizontalScrollBarEnabled = true
        loadUrl(
            url,
            mutableMapOf(
                "Cookie" to "ThisIsMyCookieWithMyValues",
                "Accept" to "*/*",
                "Accept-Encoding" to "gzip, deflate",
                "Cache-Control" to "no-cache",
                "Content-type" to "application/x-www-form-urlencoded"
            )
        )
    }
}

Now the request contains my Cookie and not the default one provided by Android, and my session in WebView is working. Hope this helps someone else

A: Latest way to set cookies using cookieManager
val siteCookies = CookieManager.getInstance().getCookie("https://www.dummyurl.com")
cookieManager.removeSessionCookies {
    if (! siteCookies.isNullOrEmpty()) {
        val cookie = siteCookies.split("; ".toRegex())
            .dropLastWhile { it.isEmpty() } as ArrayList<String>
        val iterator = cookie.iterator()
        while (iterator.hasNext()) {
            val cookie = iterator.next()
            if (cookie.isNullOrEmpty()) continue
            cookieManager.setCookie("https://www.dummyurl.com", cookie)
        }
    }
}

posting this if this helps someone.


text:
Q: Last action on Row was not recorded because the control does not have any good identification property I try to run an UITest on Visual Studio Ultimate 2012. I try to populate a dataGrid in WPF but for some reason I receive  an error when I try to record one test
error in Visual Studio
It is possible to modify the XAML so I can perform the test correctly? I do not prefer a solution inside C# classes.It's mandatory to solve this in XAML.

A: You can do this by binding the AutomationProperties in XAML to an existing property that can identify a specific row/item.
Quote from the blog in case it goes down or the post is removed:

The other alternative is to bind the AutomationProperties.Name property of list item properly.
For example, adding the following code in bold corrects the problem for this List -
<ListBox Name="GoodList" Grid.Column="1" Grid.Row="1" ItemsSource="{Binding Source={StaticResource Oscar2010}, XPath=BestPictureNomination}">
     <ListBox.ItemContainerStyle>
         <Style>
             <Setter Property="AutomationProperties.Name" Value="{Binding XPath=.}"/>
         </Style>
     </ListBox.ItemContainerStyle>
 </ListBox>

Source: https://blogs.msdn.microsoft.com/gautamg/2010/03/10/how-to-get-automation-working-properly-on-data-bound-wpf-list-or-combo-box/


text:
Q: Access To Com Port Is Denied (when detach the port cable)
Possible Duplicate:
Releasing a unplugged virtual Serial Port

This is my code to connect a serial com port:
try{
SRR_serial_port.PortName = comboBox2.Text;
SRR_serial_port.BaudRate = 9600;
SRR_serial_port.Parity = System.IO.Ports.Parity.None;
SRR_serial_port.DataBits = 8;
SRR_serial_port.StopBits = System.IO.Ports.StopBits.One;
SRR_serial_port.Handshake = System.IO.Ports.Handshake.None;
SRR_serial_port.WriteTimeout = 500;

SRR_serial_port.Open();
}
catch{}

and then close the port as follow:
SRR_serial_port.Close();

now i have a problem in this scenario:

*

*open port

*detach the serial port cable (from computer USB port)

*attach the cable again

*close port

*open port again

this leads to the following error:

access to the port is denied

In debug mode I see that this error occurs in the following lines of this line:
SRR_serial_port.Open();

I mean, this line executes and the port state change to open but after a while(during execution of next line) that error appears.
However, this scenario does not produce any error:

*

*open port

*close port

*detach and reattach cable

*open port


text:
Q: How to access files from shared location using java 8 or any recent ways to access using java? I have found how to access but these links are old, one of the link is
How to Read file from a shared location Windows? (Java)
All I want is some recent way to do it if possible.

A: It is easy by using new nio2 package, i.e. Path
Path path = Paths.get("src/test/resources/fileTest.txt");
String read = Files.readAllLines(path).get(0);

Of coz you can retrieve file name, path, location by its API. hope it solved your problem


text:
Q: Detecting window load with XUL and running a Javascript function? I am developing my first addon for Firefox, and I'm using the Extention Developer addon to help me. It has a real time XUL editor which I am using to design my form.
At the moment this is what I have:
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="yourwindow" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:h="http://www.w3.org/1999/xhtml">
<vbox>
    <label control="masterPassLabel" value="Master password:" />
    <textbox id="masterPass" value="" type="password" />
    <label control="siteNameLabel" value="Site name (defaults to current URL):" />
    <textbox id="siteName" value="" />
</vbox>
<button label="Generate" oncommand="generatePass()" />
<script type="text/javascript">
<![CDATA[
// put some js code here

siteName.value = window.location;

function generatePass() {
    //password generating code
}
]]>
</script>
</window>

I want to automatically populate the siteName textbox with the current URL when that form is loaded. And perhaps add some input validation so if there's no page loaded at that time it will show an error?
I'm new to XUL and developing Firefox addons. I have read through a lot of their documents already but I am still learning.
Thanks. :)

A: Add a function call to the "onload" event attribute of your window.

A: The following page got me sorted with a similar requirement:
Detecting window load with XUL and running a Javascript function
-FM


text:
Q: How to change kernel i/o buffer size I am running some experiments with I/O intensive applications and am trying to understand the effects of varying the kernel i/o buffer size, different elevator algorithms, and so on.
How can I know the current size of the i/o buffer in the kernel? Does the kernel use more than one buffer as need arises? How can I change the size of this buffer? Is there a config file somewhere that stores this info?
(To be clear, I am not talking about processor or disk caches, I am talking about the buffer used by the kernel internally that buffers reads/writes before flushing them out to disk from time to time).
Thanks in advance.

A: I think you mean the disk IO queues. For example:
$ cat /sys/block/sda/queue/nr_requests
128

How this queue is used depends on the IO scheduler that is in use.
$ cat /sys/block/sda/queue/scheduler
noop anticipatory deadline [cfq]

cfq is the most common choice, although on systems with advanced disk controllers and in virtual guest systems noop is also a very good choice.
There is no config file for this information that I am aware of. On systems that I need to change the queue settings on I put the changes into /etc/rc.local although you could use a full-up init script instead and place it into an RPM or DEB for mass distribution to a lot of systems.

A: The kernel does not buffer reads and writes the way you think...  It maintains a "page cache" that holds pages from the disk.  You do not get to manipulate its size (well, not directly, anyway); the kernel will always use all available free memory for the page cache.
You need to explain what you are really trying to do.  If you want some control over how much data the kernel pre-fetches from disk, try a search for "linux readahead".  (Hint: blockdev --setra XXX)
If you want some control over how long the kernel will hold dirty pages before flushing them to disk, try a search for "linux dirty_ratio".
A specific application can also bypass the page cache completely by using O_DIRECT, and it can exercise some control over it using fsync, sync_file_range, posix_fadvise, and posix_madvise.  (O_DIRECT and sync_file_range are Linux-specific; the rest are POSIX.)
You will be able to ask a better question if you first educate yourself about the Linux VM subsystem, especially the page cache.


text:
Q: RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces) I am using Pytorch. I got this RuntimeError while evaluating a model. Any idea how to solve this?

A: SOLUTION2: change the .view(...) to .contiguous().view(...).
Actually, 'reshape()' does a similar job as contiguous() under the hood, if it needs.

A: SOLUTION: Just replace the view() function with reshape() function as suggested in the error and it works.
I guess this has to do with how the tensor is stored in memory.


text:
Q: Uploading files to Amazon S3 using asp.net - How to show progress bar? Can someone please tell me how to show progress bar in asp.net when uploading files to amazon S3?

A: I know its a little late and you might would have already solved this problem. But I will reply to it anyways.
I have been working on a problem of the same kind. After a lot of research and wasting time I found a plausible solution to this problem. To use the jquery upload plugin. Here is the LINK for how to use the plugin with ASP.NET:
And here is the link for the demo of the plugin :
DEMO
I have not tried it myself because the requirements for my project had changed by the time I figured this out, but if anyone try this and it works do let me know!
Thanks!


text:
Q: Change Select value with Jquery I'm trying to use Jquery to change the value from a "select" input in a form, but when it changes, the function for that change doesn't work.
HTML:
<select id='select'>
  <option checked value='1' >Option 1</option>
  <option value='2' >Option 2</option>
</select>

Option 1 selected

Click to select Option 2

JQuery:
$('#select').change(function(){
    if($(this).val() == '1'){
    $('#text').text('Option 1 selected');
  } else if($(this).val() == '2'){
    $('#text').text('Option 2 selected');
  }
});

$('#button').click(function(){
    $('#select').val('2');
})

CSS:
#button {
  cursor: pointer;
  color: white;
  background: red;
  padding: 5px;
  display: inline-block;
}

Demo: https://jsfiddle.net/fdko9nna/
When I click the #buttondiv, it changes the select field, but the function that changes the #text it's not executed.
Thanks.

A: You need to trigger the change event with either .change() or trigger('change') in your button's code:
$('#button').click(function(){
    $('#select').val('2').change();
})

The change event you bound to the select doesn't get triggered by changing the value via jQuery alone, so you need to invoke jQuery's change event.
jsFiddle example

A: Based on https://api.jquery.com/change/
Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
This method is a shortcut for .on( "change", handler ) in the first two variations, and .trigger( "change" ) in the third.
The change event is sent to an element when its value changes. This event is limited to  elements,  boxes and  elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
Your value changed in JQuery did not fire the change event, you need to add trigger for the change event.

A: Try this:
 $('#button').click(function(){
        $('#select option[value="2"]').prop('selected', true);
    })


text:
Q: From a list, how to Print from certain string to certain string I want to print the Strings in a list.
For example, if my list contains like below, I would like to print the strings between Deer to Crazy, but not Deer and crazy.
['black', 'white', 'Deer', 'Blue', 'More', 'Crazy']

A: You can use index() in order to find the indices of the strings you are looking for.
Knowing the indexes you can print the desired strings:
my_list = ['black', 'white', 'Deer', 'Blue', 'More', 'Crazy']
print(my_list[my_list.index('Deer') + 1:my_list.index('Crazy')])

The output is:
['Blue', 'More']

A: you can use:
my_list = ['black', 'white', 'Deer', 'Blue', 'More', 'Crazy']
print(*my_list[my_list.index('Deer') + 1: my_list.index('Crazy')])

output:
Blue More


text:
Q: Will Microservices Architecture Speed Up Spring Boot Startup Time? I have a Spring Boot application with Gradle that currently is taking a lot of time.
Now, is taking about 10 minutes plus just to startup.
The source code indeed is growing rapidly, 6 Months ago, it only taking 3 minutes plus to startup.
Possible Causes
Here are facts that I think are causing the slowness:

*

*Usage of Hibernate: current source code uses a lot of sql queries.
In fact, I cant use hibernate.show_sql since it will make the startup time longer
with never ending logs keep showing up.

*There are 160+ entities with each entity is for a table.

*There are 20+ schedulers.

*There are 60+ dependencies used
Thought on Microservice
I just learnt the concept of Microsevice where
it breaks down an application to smaller pieces.
So, with that, would it possibly speed up the startup time?

*

*I have tried to comment Schedulers during
startup time in my local, but still takes 10 mins plus

*I have used spring.main.lazy-initalization = true
but still takes 9 mins plus

*I used
org.gradle.paralel = true, still takes 10 mins plus


text:
Q: What are the regional Pokémon? I have heard that there are some Pokémon that are region specific.  Could someone please clarify which Pokémon are region specific and in which regions that they can be found in?

A: *

*Farfetch'd > Asia

*Kangaskhan > Australia

*Mr. Mime > Europe

*Tauros > North America(*)

Several communities confirmed those (including The Silph Road), Niantic didn't.
(*) South America is likely to have Tauros as well. This has been posted on Reddit several times (Tauros apparently got caught in Brazil), but not enough to confirm this as true. Feel free to update this once there's proof. Until then this stands as Tauros is for North America only.

A: Reddit's r/TheSilphRoad subreddit has updated a regional map for Generation 2.

This image shown here is constructed from this link, supplemented with images from Bulbapedia. The link includes some details about these boundaries, which I will add below.
Generation 1
Tauros

Covers all major Canadian cities, no further North than Calgary, somewhere between 51˚ and 52°N, but the North East section might be a little more unclear. South as far as 29˚N. Heracross starts where it stops

Mr. Mime

Reported as far North as 61˚, does not cover all of Norway. Not found in Gibraltar but in Northern Tunisia. Found  in Sicily but not Malta. As far West as the Azores. South Eastern border a little more unclear but as far East into Russia as Kazan

Farfetch'd

All of Japan, South Korea, and reports of Vladivostok and Eastern Russia as well as areas of Northern China. Covers all of Taiwan. Covers all of Hong Kong and any areas of China South of there.

Kangaskhan

Covers Australia, including Tasmania, as well as Papua New Guinea.

Generation 2
Corsola

No higher than 31˚N and not found more than 300km inland, southern limit still disputed. 26˚S in Australia, Chile, Madagascar and Mauritius, but lower in Brazil. Confirmed in Nairobi most likely due to Lake Victoria being such a large body of water.

Heracross

Starts at 29˚N and covers the Caribbean, Central and South Americas. Most likely reaches all the way to the Southern tips of Argentina and Chile.

Note that an alternate map slightly adjusts the borders, with it being notable that Corsola do not exist very far inland. The Tauros border also extends farther north into Canada, although not completely covering it. Farfetch'd also covers more parts of China.
Credit to u/oktimeforplanb post on r/silphroad (With their image at that link).

A: I have just disproved this theory that there are regional Pokémon! Mr Mime does in fact spawn in the US! I have recently found him in my home state of NJ. So this leads me to believe that the others spawn within the US as well.

A: I have caught several wild Tauros in California. Someone also told me that her husband hatched a Kangaskhan from an egg here in the US.


text:
Q: How to convert selected Spinner item to String I was playing around with Spinners in Android, and after some playing I had a problem with  getting the selected spinner item and convert it to a String.
Can someone explain to me how to do this properly?
Thank you.

A: Try this:
spinner.getSelectedItem().toString();

A: Great question! And I hope you haven't lost your drive for Android development.
What you are missing is an ItemListener. Below is an example of how to get the data from your spinner:
Spinner mySpinner = (Spinner) findViewbyId(R.id.<your id in your xml>)

Then create a listener to for that item:
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                 String dataWanted = parent.getItemAtPosition(position).toString(); }

public void onNothingSelected(AdapterView<?> parent) {
        }
    });


text:
Q: How to reload content according exac time without refreshing the page I'm preparing simple digital signage script which require time scheduling.
I was able to do it with javascript with refreshing every 15 minutes.
But my question is, how can I measure the time and change the content on exact hour without refreshing the page?
My page looks like this:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="900" >
<title>Signage</title>
<style>
body {
   margin: 0;
   padding: 0;
}
</style>
<script>
function src() {
    var Day = "day.html";
    var Lunch = "lunch.html";
    var Evening = "evening.html";
    var Src;

    var hour = new Date().getHours();
    var day = new Date().getDay();

    if (hour >= 10 && hour <= 13 && day >= 1 && day <=5) {
        Src = Lunch;
    }

    else if (hour >= 7 && hour <= 19)   {
        Src = Day;
            }

    else  {
        Src = Evening;
            }

document.getElementById('signage').src = Src;

}

</script>

</head>
<body onLoad="src();">
<iframe scrolling="no" id="signage" src="about:blank" width="1920" height="1080" frameborder="0"></iframe>

</body>
</html>

A: If you want your page to refresh automatically after a certain time period, you can use javascript's setInterval() function.
setInterval(function() { window.location.reload(); } , timePeriod );

A: Try to add this code in head
<script> document.addEventListener("DOMContentLoaded", setTimeout(function() {src();}, 5000 /*5 sec*/)); </script>


text:
Q: Android @SuppressWarnings at statement-level, rather than method-level TL;DR: Can Android's @SuppressWarnings("deprecation"), or similar, be applied to a single statement, rather than an entire method?
I have a method myMethod that uses deprecated method ImageView.setAlpha():
public void myMethod(ImageView icon) { icon.setAlpha(0xFF); }

To avoid use of the deprecated method in Jelly Bean and subsequent releases, whilst providing backward compatibility, method myMethod can be rewritten as follows:
public void myMethod(ImageView icon) {
  if (android.os.Build.VERSION.SDK_INT
                                >= android.os.Build.VERSION_CODES.JELLY_BEAN)
     icon.setImageAlpha(0xFF);
  else
     icon.setAlpha(0xFF);
}

Moreover, command line warnings generated by Gradle/Lint can be suppressed by prepending method myMethod with @SuppressWarnings("deprecation"). But, that suppresses all deprecated warnings generated by method myMethod, rather than just the single warning generated by statement icon.setAlpha(0xFF).
Can I suppress the single deprecation warning generated by statement icon.setAlpha(0xFF), rather than suppressing all deprecation warnings generated by method myMethod?

A: You can achieve it as follows if you are using Android Studio:
 //noinspection deprecation
 icon.setAlpha(0xFF);

For your future reference: The correct format can be easily generated in Android-Studio as follows:

*

*Press alt+Enter on the statement which is throwing warning.

*Then Expand the option Deprecated API usage options

*Click on Suppress for statement
Following Image shows the process:

In your case since you are not using IDE:

*

*Unfortunately there is no direct way to achieve it at method body level. Since you have already moved the deprecated part in individual method and marked it with @SuppressWarnings this should be best you can achieve.

*There are some posts which claim to have solved it by using fully qualified class name instead of import. But looks like the issue has been fixed in Java 9. Since current popular java version for android is 8.x this should help in short term. You can refer this SO for more details


text:
Q: How to remove the java standard library from a gradle project? How can one make Gradle not include the Java standard library as a dependency to IntelliJ IDEA project?
I am using IntelliJ and every time I Refresh all Gradle projects:

IntelliJ adds the Java standard library back to the project as an external dependency:

So I have to manually remove it every single time:

Things I tried that didn't work out

*

*fiddling with the sourceCompatibility and targetCompatability properties...

*applying the idea plugin to Gradle and setting idea.project.jdkName to null.
Background

*

*I'm writing a program for the Lego NXT Brick

*I'm using Lejos so I can write the program in Java

*Lejos' "standard library" for the Lego brick is only a fraction of the actual Java standard library....(because of memory constraints?)

*Lejos provides a JAR file that contains all the classes of their standard library to assist in programming. I've added this JAR as a dependency of the project.

*Gradle also (implicitly?) adds the actual java standard library as a dependency to the project, which obscures Lejos' standard library classes since they use the same names...
P.S. at least this is what I think is happening....please correct me if I'm wrong

A: You better create a user variable like %JAVAHOME% in enivronment variables and give it in path in the system variables.
use 1.7 in javahome and 1.8 in javahomeb
when you want 1.8 just rename the variable


text:
Q: variable used out of scope I'm doing a responsive background video. I have this code.
<video id="bgvideo" />

function scaleVideo() {

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    var videoNativeWidth = $('video#bgvideo')[0].videoWidth;
    var videoNativeHeight = $('video#bgvideo')[0].videoHeight;

    var heightScaleFactor = windowHeight / videoNativeHeight;
    var widthScaleFactor = windowWidth / videoNativeWidth;

    if (widthScaleFactor >= heightScaleFactor) {
        var scale = widthScaleFactor;
    } else {
        var scale = heightScaleFactor;
    }

    var scaledVideoHeight = videoNativeHeight * scale;
    var scaledVideoWidth  = videoNativeWidth * scale;

    $('video#bgvideo').height(scaledVideoHeight);
    $('video#bgvideo').width(scaledVideoWidth);
}

I'm using grunt to compile my code and etc.
Jshint of grunt is saying I'm using "scale" out of scope and I cant understand why.
Any suggests ?

A: You should not write var scale = heightScaleFactor; inside the else statement  if you want to use it outside of it.
Initialize scale outside the if
 var scale;
 if (widthScaleFactor >= heightScaleFactor) {
     scale = widthScaleFactor;
 } else {
     scale = heightScaleFactor;
 }

A: Try this instead:
function scaleVideo() {
    var scale; //this is the change

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    var videoNativeWidth = $('video#bgvideo')[0].videoWidth;
    var videoNativeHeight = $('video#bgvideo')[0].videoHeight;

    var heightScaleFactor = windowHeight / videoNativeHeight;
    var widthScaleFactor = windowWidth / videoNativeWidth;

    if (widthScaleFactor >= heightScaleFactor) {
        scale = widthScaleFactor; //simply modify the value here
    } else {
        scale = heightScaleFactor;
    }

    var scaledVideoHeight = videoNativeHeight * scale;
    var scaledVideoWidth  = videoNativeWidth * scale;

    $('video#bgvideo').height(scaledVideoHeight);
    $('video#bgvideo').width(scaledVideoWidth);
}


text:
Q: OWL Carousel is not working here is my code html code..

owl carousel jquery
$('.sliderImgs').owlCarousel({
        navigation : true, // Show next and prev buttons
        slideSpeed : 300,
        paginationSpeed : 400,
        singleItem:true,
        autoPlay: 1000
    });

and the css
.sliderImgs img{display:block;width:100%;height:auto;}

A: I tried your code and it works fine here in the codepen example
codepen example
Please verify if jquery is loaded and Owl js file should be included after jquery
Similar to this:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.css" />

A: Your code must be like below.


text:
Q: How to limit languages that show in Sitecore publishing dialog? To streamline our content editors' experience, I want to ensure that the languages that show up in the publishing dialog window are limited to the languages to which the editor has Language Write access. We've set up Language Write for our various editor roles appropriately, but the entire selection of System > Languages still shows up in the publishing dialog (screenshot below -- the Publish Language section is what I'm looking to streamline based on lang write perms). I've tried denying Language Read for a non-essential language to see if that did it, but it did not. Is there a way to do this?

A: Wether the language is shown in the Publish dialog is not depended on the Language Read access right.
It's simply the Read right that determines this.

A: Have you broken inheritance on the languages? By default the everyone group has read access to the languages, so you need to specifically break inheritance for all other languages when selecting a English (Canada) role for example.

I've just tried this and removing Language Read on a particular role removes the language from the publish language list. Use the Access Viewer (>Security Tools) to make sure that Language Read is not inherited from another role.
Look at the method which builds the Publish dialog in dotPeek, this is the codebeside for sitecore/shell/Applications/Dialogs/Publish/Publish.xml
BuildLanguages() method in Sitecore.Shell.Applications.Dialogs.Publish.PublishForm class in  Sitecore.Client.dll
Also, make sure that CheckSecurityOnLanguages in Sitecore config is set to true.
Be aware, if you are running multi-site and have different permissions on different branches, make sure that you have Publishing.CheckSecurity and Publishing.RequireTargetDeleteRightWhenCheckingSecurity otherwise users will be able to cross publish items, which is not what you want.
http://sitecorebasics.wordpress.com/2011/04/12/publishing-security-basics/
[EDIT] @Ruud, you shouldn't specifically deny Role access to an item, instead you should break inheritance, that way if you compound roles (i.e. a user belongs to multiple Roles) the user will still have access to that item. If you deny access, no other permission will be able to override it.
Sitecore Worst Practices Blog Series: Security

To prevent denial from overriding allowance, avoid denying access rights in favor of breaking inheritance and granting access rights.

Sorry, don't have enough rep to comment directly on your post.


text:
Q: How to choose a specific 'div' when they share the same class and find a certain element inside it with beautiful soup? I'm trying to access two separate values with beautiful soup. There are multiple 'divs' with the same class and no ID but I'm trying to access this specific one. I've tried finding it with no progress, I've looked on this site as well but still haven't been able to find any answers. How do I do this?
So far, this code:
name = soup.find_all('div', {'class':'d-flex justify-content-between mx-3'})
print(name)

I get this:

Gucci Bloom Perfume

<svg aria-hidden="true" focusable="false" preserveaspectratio="xMidYMid meet" style="vertical-align: -1.0em;-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform:
rotate(360deg);" viewbox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g fill="none"><path d="M13.544 10.456a4.368 4.368 0 0 0-6.176 0l-3.089 3.088a4.367 4.367 0 1 0 6.177 6.177L12
18.177" stroke="#fff" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><path d="M10.456 13.544a4.368 4.368 0 0 0 6.176 0l3.089-3.088a4.367 4.367 0 1 0-6.177-6.177L12 5.823" stroke="#fff" stroke-linecap=
    "round" stroke-linejoin="round" stroke-width="2"></path></g></svg>

But i just want the text in this:

Gucci Bloom Perfume

How would I differ between these? The text values change so trying to find via text is not an option.

Edit: Here is the url


text:
Q: How to draw an entire listview to canvas in Java/Android I've been trying to draw a listView to a canvas so I can create a PDF document out of it, but have been unsuccessful. The problem is that my listView is longer than my screen, so only 6 elements out of the 9 are actually on screen, and only those 6 get drawn.
I've tried everything I can think of, but nothing seems to work. How do I get the entire listView so that I can draw it to a canvas?
Here is the XML of the listView:
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/cl_lv_k"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@null"
        android:dividerHeight="0dp" >
    </ListView>
    ....

When I try and access the listView by findViewById(R.id.cl_lv_k) it only gives me the current elements that are on the screen.
I've tried everything I can think of. Help would be greatly appreciated.
EDIT:
I got a solution. Thanks to @Mike M. for finding a related question: Android get screenshot of all ListView items
I used the following code in my program, and it worked.
ListView listView = (ListView) findViewById (R.id.cl_lv_k);
PageInfo pageInfo =
                new PageInfo.Builder(pageWidth, 12000, 1).create();
Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();

ChartAdapter adapter = listView.getAdapter(); //this is just a custom adapter
for (int i = 0; i < adapter.size(); i++)
{
    View childView = adapter.getView(i, null, kColumn);
            childView.measure(MeasureSpec.makeMeasureSpec(kColumn.getWidth(),
                                                  MeasureSpec.EXACTLY),
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    childView.layout(0, 0, childView.getMeasuredWidth(),
                                    childView.getMeasuredHeight());
    childView.setDrawingCacheEnabled(true);
    childView.buildDrawingCache();
    childView.getDrawingCache();
    childView.draw(canvas);
    canvas.translate(0, childView.getMeasuredHeight());
}
....

I made a PDF document out of this page, so I filled in the rest of the PDF code and it worked.


text:
Q: UWP how to get access to file in folder Help me please, I can't  get access to file which I choose by  FileOpenPicker.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.CommitButtonText = "Открыть";
openPicker.FileTypeFilter.Add(".xlsx");
var file = await openPicker.PickSingleFileAsync();

using (FileStream fs = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{

}

What is wrong?

A: Because of how UWP sandboxes access to the filesystem, you can't construct a FileStream directly from a StorageFile's path. Instead, you have a few options, in order from simplest to most complex:
1) If your file is small enough, you can just use the helpers in the FileIO static class to read it all at once:
string text =  await FileIO.ReadTextAsync(file); // or ReadLinesAsync or ReadBufferAsync, depending on what you need

2) Use the OpenAsync() method on StorageFile:
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowReadersAndWriters))
{
     // your reading code here
}

If you need to, you can convert between IRandomAccessStream and .NET Streams with the AsStream(), AsStreamForRead() and AsStreamForWrite() extension methods on IRandomAccessStream, the docs for which are here.
3) If you want complete control, you can get a SafeFileHandle to the underlying file using CreateSafeFileHandle(), like so:
SafeFileHandle fileHandle = file.CreateSafeFileHandle(FileAccess.Read, FileShare.ReadWrite);

You can then use this file handle to create a standard FileStream:
using (FileStream fs = new FileStream(fileHandle, FileAccess.Read))
{
     // Read stuff here
}

This is the only way to reliably use a FileStream on a UWP StorageFile, and should be used with some caution. The official docs have more details on the implications of doing this.

A: FileOpenPicker gives you a StorageFile which wraps the opened files and gives you permission to it. This doesn't give you access to the file in general - e.g. you cannot use its Path only to open it with a FileStream. Instead, you need to use the respective Windows.Storage APIs to do this. I usually use the OpenStreamForReadAsync extension method. Add using System.IO to the file header and then:
var stream = await file.OpenStreamForReadAsync();

This method returns a System.IO.Stream which you can use with classic System.IO-enabled APIs.

A: Please avoid use file Path to access file stream in UWP platform, if you have get the file with FileOpenPicker. You could get the file stream with following.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.CommitButtonText = "Открыть";
openPicker.FileTypeFilter.Add(".xlsx");
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
 var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
}

And if you need use stream in System.IO namespace. please call AsStream method for IRandomAccessStream object.
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
System.IO.Stream iostream = stream.AsStream();

For more detail please refer this official document.


text:
Q: How to store Eclipse plug-in state between sessions? I am working on an Eclipse plugin. The plugin reminds the user to save his work in a central repository every time he saves his work locally.
However, once the user successfully saves his work on a central repository for 10 times he will no longer be reminded to save his work.
This works well in a single session. That is, when the user starts working in the workspace and enables the plugin.
However, if the user exits from the workspace after saving his work to the central repository
for 9 times, he will continue to be reminded for 10 more times i.e from the scratch, the next time he opens his workspace.
I want to know, if it possible to increment a counter and store it in the memory, so that the plugin works as intended.

A: You may use the plugin Settings to store and retrieve values for your plugin.
The example from Eclipse FAQ:
 private void savePluginSettings() {
  // saves plugin preferences at the workspace level
  Preferences prefs =
    //Platform.getPreferencesService().getRootNode().node(Plugin.PLUGIN_PREFEERENCES_SCOPE).node(MY_PLUGIN_ID);
    new InstanceScope().getNode(MY_PLUGIN_ID); // does all the above behind the scenes

  prefs.put(KEY1, this.someStr);
  prefs.put(KEY2, this.someBool);

  try {
    // prefs are automatically flushed during a plugin's "super.stop()".
    prefs.flush();
  } catch(BackingStoreException e) {
    //TODO write a real exception handler.
    e.printStackTrace();
  }
}

private void loadPluginSettings() {
  Preferences prefs = new InstanceScope().getNode(MY_PLUGIN_ID);
  // you might want to call prefs.sync() if you're worried about others changing your settings
  this.someStr = prefs.get(KEY1);
  this.someBool= prefs.getBoolean(KEY2);
}

A: You need to save your state to disk. The details of how to do this are completely up to you. There are numerous ways to do this. One way is to use Eclipse preferences API. It is based on the concept of different scopes... install vs. workspace vs. project. I believe that the workspace-level ones are tracked by InstanceScope class...
http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/preferences/InstanceScope.html
This API will give you ability to store arbitrary content in a tree-like structure and then read it back out. Make sure that the first node in the tree is your plugin id to avoid collisions with other plugins.


text:
Q: Sort one column to match another in excel I have a spreadsheet and I need to match the two columns together. However "Dove code" is 3600 rows and "code 2" is 1100. They all have the same codes as you can see in the image but you can also see where it starts changing and I need to have the codes all line up so I can see the gaps. I have already arranged them all alphabetically and its the "code 2" that would need to match up to "Dove code

A: If the above solution would result in too much shunting and vba is not an option, there's another way. Copy the first column and use 'remove duplicates' on it. Now you have an index list, put numbers from 1 to x in the column on the right of it.
Insert a column between the two lists and right of the second one.
Assuming that the index list is in F and the numbers in G, put this formula in the cell right of the first cell in the larger list:
 =VLOOKUP(A2,$F$2:$G$500,2,FALSE)
Adjust the range accordingly. Put the same formula in the cell right of the first cell in the shorter list, with of course C2 instead of A2. Copy both formules to the end of the list.
Now both columns have an index on every row. You can match them using data sort, but for that you need to add dummies in the index columns.
Put this formula in the cell right of your basic index list: =countif(B:B,G2)
And this one in the cell right of that: =countif(D:D,G2)
Now you know how many times each record arises in both lists. Just add extra numbers manually so that both formulas turn up the same result. You should be able to do that really fast. If you have 200 records that are used 2 times in the first column and not in the second one, just copy the index of those 200 records and paste them twice. The countif's will automatically update.
You can use an extra column to calculate the difference between the two counts and use data sort on your basic index list to sort on the diferences.
After that just use data sort.
IF my directions are clear enough, this shouldn't cost you more than 10 minutes.
Edit:
Here's an example: http://img14.imageshack.us/img14/6366/k8pg.jpg

A: Without VBA I do this (for columns with a limited number of mismatches!) by adding a formula such as =INDIRECT("A"&ROW())<>INDIRECT("B"&ROW()) in a helper column. Working downwards, every time you see a TRUE shunt the appropriate column down to suit. But it may be only just about viable for 1100 rows!


text:
Q: Microsoft OLEDB 12.0 not registered on local machine I have created an ASP.net web application which reads data from excel sheet and displays it in jquery data table.
After taking a build and deploying it on IIS 8, it works fine on my machine. But once I deploy it on another machine which has 32 bit office installed, there is Microsoft.OLEDB 12.0 driver not registered error.
But even after installing microsoft redistriuable and data connectivity components I am getting the same exception.
Every answer on stackoverflow covers driver installation but it dosen't help in my case.


text:
Q: In app purchase - method to allow full control of adding products from personal server = allowed? I have a very strait forward question (and yes I've looked though apple documentation to see if this has an answer but no luck... I may have accidentally missed it though)
Here's my plan:
The problem I've been trying to find a workaround for is that if the admin would ever want to add a product, he would have to log into iTunes connect to add it and also add it in a custom control panel. We, obviously, don't want to make him suffer that so I've been looking for a solution but I need you guys to tell me if it's allowed by apple. Basically I will take over most of the product handling on our servers and will only go to apple with the transactions. This means that apple will not have an in-app purchase set up for ALL the products... only one for each length of subscription (1 month, 3 month... etc) and a few consumable in-app purchases for the various prices of the issues/singles
Side note: I will be selling monthly issues that contain multiple singles for each day of the month. The user will be able to download a full month or a single day at a time if they like.
DEFINITION OF CONSUMABLE PURCHASE - products must be purchased each time the user needs that item. For example, one-time services are commonly implemented as consumable products.
So I will store all the information in our server about the products and if someone chooses to buy a single month's issue that was set to 4.99 (on our server, not apples) then the app will run the in-app purchase with apple that is listed for the 4.99 tier. Whenever a person opens the app for the first time, their app will send some information to our server and they will have a row set aside for them where all the information about their purchases will be recorded so that they can restore them if they switch over to another device.
If you guys think i'm safe in doing this, please let me know so that I can proceed. Also, if this method helps anyone, feel free to use it!
Thanks,
Matt

A: I think your restore process might be flawed. You talk about the app sending some information up to your server, but what is that information? There is no reliable way to uniquely identify a user across different devices.
If you want to continue on this path you'll want to make sure that your recovery and failover process is very solid. Try out every imaginable scenario. From an app store submission point of view, you'll want to consider a token/coin-based approach. Of course, Apple's guidelines are fairly loose and subject to change so it's always possible you'll get rejected, but tokens are certainly more solid than simply using the same generic in-app purchase.
In a token system, you would set up in-app purchases for different numbers of tokens that the user can purchase as a sort-of virtual currency only valid within your application. Then users can spend these tokens on any items that you dynamically create.
Server-side this means you'll need some way to store how many tokens a user currently has and a way to uniquely identify a user across devices, which is a fairly uncertain proposition. Instead of storing the number of tokens each user has, you could implement some sort of hashing algorithm that generates a hash from an in-app purchase receipt and then sends it up to your server. If the app crashes or the network dies after purchase but before sending your hashes up, next time they open the app you can recalculate all of the hashes, send 'em up, and if the server doesn't recognize a hash it just adds it to the database. Then if a user wants to restore their purchases you simply recalculate the hashes on the device using the in-app purchase receipts you'll receive and then send them up to your server and ask the server to figure out for each of those hashes, how many tokens the user has left. You could think of it like a gift card system, where each hash is one gift card.
Again, app store rules change and if apple thinks you're trying to game the system and not provide a useful experience they have the right to reject you. It could be worthwhile to open a Developer Technical Support request and see if an apple engineer can provide you with a better solution or tell you if the reviewers are likely to accept your application.


text:
Q: Receiving data from RS232(com) I want to write an app that receive data from RS232(sometimes using usb connector) port using C/C#.
I have searched the web but found nothing. Do u have anything interesting? Articles, tutorials, tips, code snippets, everything is very much appreciated.
I have got transmission protocol, but have no idea how to read data from rs232.
Can I read/write data asynchronously?

A: Take a look at this really great tutorial: http://www.codeproject.com/Articles/8605/Serial-Communication-using-C-and-Whidbey . It offers not only a whole small project but it also explains the basics of serial communication.
As for the USB-to-Serial-connector or real RS232 - it doesn't really matter because Windows recognizes both as a COM port. If you open your Device manager, in the Ports(COM & LPT) section you will be able to see both.


text:
Q: Microsoft Flow - Add new item to existing item lookup, separate list I have two sharepoint 2013 lists that have references to each other. It was one to many relationship. So "list A" has a lookup column that references several items in "list B" by clicking the checkbox in the column stetting "allow multiple values". "List B" has a lookup to a single item in "List A" (unchecked "allow multiple values" option). I would like to have a Microsoft Flow that is triggered after I create a new item in "List B" add the lookup to "List A" item to "List B" item.
In this scenario List A Items already exists. A user will create an item in List B and select an item from "List A". So now the link from List B item to List A item exists, but the link from List B item to List A item does not exist. I want the Flow  that is started from the creation of the new List B Item to use the lookup to the List A item to update the List A item lookup to include a link to List B item.

When I create an action step in the Flow and choose the Flow option "Sharepoint - Update item" for list A, the lookup field to list B is missing.
Is there a way to achieve what I'm after in flow? It doesn't seem to be documented anywhere I've found.