text:
Q: Why is scrollview hiding buttons behind other views? I have a bunch of buttons in a scrollview and then below the scrollview is a horizontal linear layout with some buttons for controls and then below that is an Ad Mob banner ad.  I can't seem to figure out why when I scroll to the bottom of the list of buttons, approximately half of the last row of buttons are hidden behind the controls and banner ad.  Can anybody tell me how to make it scroll to show the full bottom row of buttons so they aren't hidden behind the linear layout for the controls and the ad banner?
Here is a screenshot:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fillViewport="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/button"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 1"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@+id/button2"
                app:layout_constraintTop_toTopOf="parent" />

            <Button
                android:id="@+id/button2"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 2"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintLeft_toRightOf="@+id/button"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <Button
                android:id="@+id/button3"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 3"

                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@+id/button2"
                app:layout_constraintTop_toBottomOf="@id/button" />

            <Button
                android:id="@+id/button4"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 4"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintLeft_toRightOf="@+id/button"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@id/button2" />

            <Button
                android:id="@+id/button5"
                android:layout_width="0dp"
                android:layout_height="0dp"

                android:text=" Button 5"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@+id/button2"
                app:layout_constraintTop_toBottomOf="@+id/button3" />

            <Button
                android:id="@+id/button6"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 6"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toRightOf="@+id/button"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button4" />

            <Button
                android:id="@+id/button7"
                android:layout_width="0dp"
                android:layout_height="0dp"

                android:text=" Button 7"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@+id/button8"
                app:layout_constraintTop_toBottomOf="@+id/button5" />

            <Button
                android:id="@+id/button8"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 8"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toRightOf="@+id/button"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button6" />

            <Button
                android:id="@+id/button9"
                android:layout_width="0dp"
                android:layout_height="0dp"

                android:text=" Button 9"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@+id/button10"
                app:layout_constraintTop_toBottomOf="@+id/button7" />

            <Button
                android:id="@+id/button10"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 10"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toRightOf="@+id/button"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button8" />

            <Button
                android:id="@+id/button11"
                android:layout_width="0dp"
                android:layout_height="0dp"

                android:text=" Button 11"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@+id/button12"
                app:layout_constraintTop_toBottomOf="@+id/button9" />

            <Button
                android:id="@+id/button12"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 12"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toRightOf="@+id/button"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button10" />

            <Button
                android:id="@+id/button13"
                android:layout_width="0dp"
                android:layout_height="0dp"

                android:text=" Button 13"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@+id/button14"
                app:layout_constraintTop_toBottomOf="@+id/button11" />

            <Button
                android:id="@+id/button14"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:text="Button 14"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintDimensionRatio="H,1:1"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toRightOf="@+id/button"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button12" />

            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_begin="87dp" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/controlslayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#000000"
        app:layout_constraintBottom_toTopOf="@+id/adView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <Button
            android:id="@+id/play"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Play/Pause" />

        <Button
            android:id="@+id/timer"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Timer" />

        <Button
            android:id="@+id/volume"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Volume" />
    </LinearLayout>

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        app:adSize="SMART_BANNER"
        app:adUnitId="ca-app-pub-3940256099942544/6300978111"
        app:layout_constraintBottom_toBottomOf="@+id/scrollView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"></com.google.android.gms.ads.AdView>
</androidx.constraintlayout.widget.ConstraintLayout>

The bottom row of buttons should be fully visible when scrolled down and not hidden behind the other views.

A: app:layout_constraintBottom_toBottomOf="parent" in your ScrollView needs to be app:layout_constraintBottom_toTopOf="@+id/controlslayout". Currently, your list is filling the entire screen, and the buttons are drawn over it.
Also, there isn't much point using ConstraintLayout if you're going to nest ViewGroups like this.


text:
Q: Find nearest prime number python I want to find the largest prime number within range(old_number + 1 , 2*old_number)
This is my code so far:
def get_nearest_prime(self, old_number):
    for num in range(old_number + 1, 2 * old_number) :
        for i in range(2,num):
            if num % i == 0:

                break

    return num

when I call the get_nearest_prime(13)
the correct output should be 23, while my result was 25.
Anyone can help me to solve this problem? Help will be appreciated!

A: There are lots of changes you could make, but which ones you should make depend on what you want to accomplish. The biggest problem with your code as it stands is that you're successfully identifying primes with the break and then not doing anything with that information. Here's a minimal change that does roughly the same thing.
def get_nearest_prime(old_number):
    largest_prime = 0
    for num in range(old_number + 1, 2 * old_number) :
        for i in range(2,num):
            if num % i == 0:
                break
        else:
            largest_prime = num
    return largest_prime

We're using the largest_prime local variable to keep track of all the primes you find (since you iterate through them in increasing order). The else clause is triggered any time you exit the inner for loop "normally" (i.e., without hitting the break clause). In other words, any time you've found a prime.
Here's a slightly faster solution.
import numpy as np

def seive(n):
    mask = np.ones(n+1)
    mask[:2] = 0
    for i in range(2, int(n**.5)+1):
        if not mask[i]:
            continue
        mask[i*i::i] = 0
    return np.argwhere(mask)

def get_nearest_prime(old_number):
    try:
        n = np.max(seive(2*old_number-1))
        if n < old_number+1:
            return None
        return n
    except ValueError:
        return None

It does roughly the same thing, but it uses an algorithm called the "Sieve of Eratosthenes" to speed up the finding of primes (as opposed to the "trial division" you're using). It isn't the fastest Sieve in the world, but it's reasonably understandable without too many tweaks.
In either case, if you're calling this a bunch of times you'll probably want to keep track of all the primes you've found since computing them is expensive. Caching is easy and flexible in Python, and there are dozens of ways to make that happen if you do need the speed boost.
Note that I'm not positive the range you've specified always contains a prime. It very well might, and if it does you can get away with a lot shorter code. Something like the following.
def get_nearest_prime(old_number):
    return np.max(seive(2*old_number-1))

I don't completely agree with the name you've chosen since the largest prime in that interval is usually not the closest prime to old_number, but I think this is what you're looking for anyway.

A: You can use a sublist to check if the number is prime, if all(i % n for n in range(2, i)) means that number is prime due to the fact that all values returned from modulo were True, not 0. From there you can append those values to a list called primes and then take the max of that list.
List comprehension:
num = 13
l = [*range(num, (2*num)+1)]
print(max([i for i in l if all([i % n for n in range(2,i)])]))

Expanded:
num = 13
l = [*range(num, (2*num)+1)]

primes = []
for i in l:
     if all([i % n for n in range(2, i)]):
        primes.append(i)

print(max(primes))

23

A: Search for the nearest prime number from above using the seive function
def get_nearest_prime(old_number):
    return old_number+min(seive(2*old_number-1)-old_number, key=lambda a:a<0)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse for Java EE on Linux - cannot see Java EE projects? I just installed eclipse indigo on Ubuntu. After, I went to install new software > WEB, XML, Java EE etc.
When I go to Eclipse plugins, I see they are installed.
But when I try to create a new eg Web Project, I cannot see it! The one and only point to choose is "create new > general > project". Nothing else!
What could I be doing wrong?

A: Even though this does not answer the OP's question, I would recommend installing the latest Java EE version from here :
http://www.eclipse.org/downloads/?osType=linux
Back to your question. Perhaps you could try re-starting eclipse with the -clean option just to make sure that it's not obsolete workspace metadata which is at fault. If that does not work, I would reiterate the original suggestion to download the Java EE version to save time.
(Please don't be offended, but to rule out the obvious, you must have restarted Eclipse after installing all the plugins ?)


text:
Q: Wordpress: Having issues with is_home() and is_front_page() I have this snippet in a "portfolio-loop.php" file. I'm using get_template_part to display the loop on the front page and on other pages.
I have this within the loop:
<?php if( !is_home() || !is_front_page() ) : ?>

<?php the_time('F Y'); ?>

<?php endif; ?>

I can't seem to get it to exclude the front page. Could it because it's in it's own template?

A: you probably mean
if( !is_home() && !is_front_page() )

Meaning you are not home AND you are not on the front page


text:
Q: How to fill an array with node elements from a binary search tree, in ascending order? In a school assignment I'm supposed to complete a method that should return an array of
node elements in ascendig order. The nodes are assembled in a binary search tree, so to sort them correct, I got a tip to create a recursive method to do the job.
The problem is that this doesn't even yield all the elements in the collection according to the test output (java.lang.AssertionError: toArray() does not return all the elements in the collection.)
I couldn't come up with any other way to deal with the array, and I'm not quite sure if the recursion even works. Any help is much appreciated.
Below is my code:
public class BinarySearchTree<E extends Comparable<E>> implements
    IfiCollection<E> {

    Node root;
    Node current;
    int size = 0;
    int i = 0;

    public class Node {
    E obj;
    Node left, right;

    public Node(E e) {
        obj = e;
    }

    } // END class Node

    [...]

    public E[] toArray(E[] a) {

    Node n = root;

    a = sort(n, a);
    return a;

    }

    public E[] sort(Node n, E[] a) { //, int idx, E[] a) {

    if (n.left != null) {
        current = n.left;
        sort(current, a);
    }

    a[i] = current.obj;
    i++;

    if (n.right != null) {
        current = n.right;
        sort(current, a);
        }

    return a;

    } // END public Node sort

    [...]

} // END class BinarySearchTree

Test output:
java.lang.AssertionError: toArray() does not return all the elements in the collection.: TestPerson("Bender").compareTo(TestPerson("Fry")) == 0 expected:true but was:false
    at inf1010.assignment.IfiCollectionTest.assertCompareToEquals(IfiCollectionTest.java:74)
    at inf1010.assignment.IfiCollectionTest.assertCompareToEquals(IfiCollectionTest.java:83)
    at inf1010.assignment.IfiCollectionTest.assertCompareToEqualsNoOrder(IfiCollectionTest.java:100)
    at inf1010.assignment.IfiCollectionTest.toArray(IfiCollectionTest.java:202)
protected void assertCompareToEquals(TestPerson actual,
        TestPerson expected, String msg) {
            assertTrue(actual.compareTo(expected) == 0, String.format( // l:74
            "%s: %s.compareTo(%s) == 0", msg, actual, expected));
}

    [...]

protected void assertCompareToEquals(TestPerson[] actual,
        TestPerson[] expected, String msg) {
    for (int i = 0; i < actual.length; i++) {
        TestPerson a = actual[i];
        TestPerson e = expected[i];
        assertCompareToEquals(a, e, msg); // l:83
    }
}

    [...]

protected void assertCompareToEqualsNoOrder(TestPerson[] actual,
        TestPerson[] expected, String msg) {
    assertEquals(actual.length, expected.length, msg);

    TestPerson[] actualElements = new TestPerson[actual.length];
    System.arraycopy(actual, 0, actualElements, 0, actual.length);

    TestPerson[] expectedElements = new TestPerson[expected.length];
    System.arraycopy(expected, 0, expectedElements, 0, expected.length);

    Arrays.sort(expectedElements);
    Arrays.sort(actualElements);

    assertCompareToEquals(actualElements, expectedElements, msg); // l:100
}

    [...]

@Test(dependsOnGroups = { "collection-core" },
    description="Tests if method toArray yields all the elements inserted in the collection in sorted order with smallest item first.")
public void toArray() {
    TestPerson[] actualElements = c.toArray(new TestPerson[c.size()]);

    for (int i = 0; i < actualElements.length; i++) {
        assertNotNull(actualElements[i],
                "toArray() - array element at index " + i + " is null");
    }

    TestPerson[] expectedElements = allElementsAsArray();
    assertCompareToEqualsNoOrder(actualElements, expectedElements, // l:202
            "toArray() does not return all the elements in the collection.");

    Arrays.sort(expectedElements);
    assertCompareToEquals(actualElements, expectedElements,
            "toArray() does not return the elements in sorted order with "
                    + "the smallest elements first.");

    TestPerson[] inArr = new TestPerson[NAMES.length + 1];
    inArr[NAMES.length] = new TestPerson("TEMP");
    actualElements = c.toArray(inArr);
    assertNull(actualElements[NAMES.length],
            "The the element in the array immediately following the "
            + "end of the list is not set to null");
}

I don't know if I should post more of the test code, it's quite extensive, and it might be a little too much for one post?

A: I see you have the code
if (n.left != null) {
        current = n.left;
        sort(current, a);
  }

but I can't seem to find at which point you set current back at the current node so that when you do
a[i] = current.obj;

you get the correct result. That's probably why you're not getting all the results. In any case I don't see (at least from the code fragments you have posted) why current needs to be a class variable and not just declared in the sort method. In general you shouldn't be using class variables if you don't really need them.
Edit:
You can either set current back to the node you are processing after calling sort on the left child like this
current = n;
a[i] = current.obj;
i++;

Or not use current at all in which case you'd have something like
if (n.left != null)
    sort(n.left, a);
a[i] = n.obj;
i++;
if (n.right != null)
    sort(n.right, a);

A: Ok, I think the problem is your use of the "global" variable current. The way it is set, doesn't make much sense. You don't need to anyway, because the "current" Node is the one that is provided in the parameters.
Also you should consider renaming your function. You aren't sorting anything here, just collecting the contents of the tree, so a name such as collect would be more suitable.
public E[] toArray(E[] a) {
  Node n = root;
  a = collect(n, a);
  return a;
}

public E[] collect(Node n, E[] a) {

  if (n.left != null) {
    // If there is a left (smaller) value, we go there first
    collect(n.left, a);
  }

  // Once we've got all left (smaller) values we can
  // collect the value of out current Node.
  a[i] = n.obj;
  i++;

  if (n.right != null) {
    // And if there is a right (larger) value we get it next
    collect(n.right, a);
  }

  return a;
}

(Disclaimer: I haven't tested this)

Alternative implementation without the global index:
public E[] toArray(E[] a) {
  Node n = root;
  collect(n, a, 0);
  return a;
}

public int collect(Node n, E[] a, int i) {

  if (n.left != null) {
    // If there is a left (smaller) value, we go there first
    i = collect(n.left, a, i);
  }

  // Once we've got all left (smaller) values we can
  // collect the value of out current Node.
  a[i] = n.obj;
  i++;

  if (n.right != null) {
    // And if there is a right (larger) value we get it next
    i = collect(n.right, a, i);
  }

  return i;
}

A: I think where you are confused is that if you check out how a binary search tree works, is that it is always sorted. You start at your root node, and then as you insert a new node, it inserts it into the appropriate position (i.e. to the left or the right) depending on the values. So you should not have to call sort to begin with. So I would start there, and read up on binary search trees. For example wikipedia has a decent article.
Update: Ignore my comment you should not need to do that either. Say you insert 8, 3, 7, 9, 12, 2, 10, 1 into the tree in that order. It should end up looking like this:
      8
     / \
    3   9
   / \   \
  2   7   12
 /       /
1       10

If you look at it that means to get them in order, start at the root, then if it has a node to the left got to the left, if not, return itself, and go to the right if it has a value. Repeating this for each node you encounter.

A: http://cs.armstrong.edu/liang/intro8e/html/BinaryTree.html
The easiest way to do what you are looking for is to traverse the tree inorder and append to an ArrayList. To get the array you can call the .toArray() method of the arrayList.
If you can't use an arraylist, declare an index and an array outside the inordertraversal and increment, you will need to know how many elements are in the tree to declare your array.
pseudo code:
variables:
arraysize = root.count()
E[] inOrderNodeArray = new E[arraysize]
int index = 0

inorder traversal:
void inorder(Node n) {
    if (n) {
        inorder(n.left)
        inOrderNodeArray[index] = n
        index++
        inorder(n.right)
    }
}


text:
Q: ios uiAutomation tapWithOptions not working properly I have to run UIAutomation for touch and hold..
I am using tapWithoptions(offset,duration)..but the problem is i want to vary the cordinates
on which it will tap..but thats not happening..its always taking center cordinate for some
weird reason.
The same command works properly if i remove the duration parameter..but i want duration in it..following is the line i am using for it:-
target.frontMostApp().mainWindow().scrollViews()[0].scrollViews()[0].tapWithOptions({tapOffset:{x:xPos, y:yPos},duration:1.2});
Any help in this regard shall be highly appreciated

A: I had almost same issue. You ca try target.frontMostApp().mainWindow().scrollViews()[0].scrollViews()[0].tapWithOptions({x: 27.0, y: 949.0}, {duration:3});
If you see the documentation, tapOffset is not the exact x and y positions. It is just relatives values between 0 and 1. You have to calculate these relative values according to x, y positions.

A: Tapping scrollviews is not working very well with UI Automation. The best solution is to recalculate the position into window position and tap mainWindow.


text:
Q: Marklogic fail to create element range index Fail to create element range index.
Error Invalid coercion range-element-index xmlns="http://marklogic.com/xdmp/database">...... as element(configuration)
I have over 100 million documents in database need to index "tr:ModifiedDate".
 <?xml  version="1.0" encoding="UTF-8"?>
 <mdra:Record Type="TR" xmlns:mdra="http://dvtech.com/mdra/record">
 <tr:Raw xmlns:tr="http://dvtech.com/mdra/record/tr">
        <tr:History>
           <tr:ModifiedDate>2009-03-18T09:07:23.000-04:00</tr:ModifiedDate>
           <tr:DrolsNdxDate>2002-07-05T18:33:26.000-04:00</tr:DrolsNdxDate>
        </tr:History>

        <tr:TrlType>
           <tr:Code>0</tr:Code>
       </tr:TrlType>
</tr:Raw>
</mdr:Record>

I create element-range-index on tr:ModifiedDate but fail to create it. An error shows Invalid coercion. I couldn't figure out  what cause it.
xquery version "1.0-ml";

import module namespace admin = "http://marklogic.com/xdmp/admin"
      at "/MarkLogic/admin.xqy";

let $config := admin:get-configuration()
let $dbid := xdmp:database("IAD")

let $rangespec := admin:database-range-element-index("dateTime",
          "http://dvtech.com/mdra/record/tr",
          "ModifiedDate",
          "http://marklogic.com/collation/",
          fn:false() )

 return
 admin:save-configuration($rangespec)

A: The admin library revolves around $config. You need to update that config, and then save the config, not just one index definition. You would use admin:database-add-range-element-index to do this. The correct way of doing it is like this:
xquery version "1.0-ml";

import module namespace admin = "http://marklogic.com/xdmp/admin"
      at "/MarkLogic/admin.xqy";

let $config := admin:get-configuration()
let $dbid := xdmp:database("IAD")

let $rangespec := admin:database-range-element-index(
  "dateTime",
  "http://dvtech.com/mdra/record/tr",
  "ModifiedDate",
  "http://marklogic.com/collation/",
  fn:false()
)

let $config := admin:database-add-range-element-index($config, $dbid, $rangespec)
return
  admin:save-configuration($config)

You can add multiple range indexes with one call to that function.
I'd also like to mention that there are deployment tools that can help with deploying range indexes into MarkLogic. A good example is ml-gradle.
HTH!


text:
Q: Orientation type of the sensor What data are used by orientation sensor in the android Samsung Galaxy S 2. Gyroscope's data or accelerometer's data?

A: I have recently answered a similar question (you can have a look here). The brief answer is this:
"The methods included in the Android APIs to get the orientation does not include readings from the gyroscope sensor. Gyroscope does not provide information about orientation, since it only has information about rotation speed".

A: Samsung Galaxy S2 has a boatload of sensors, a magnetic/orientation one from Asahi Kasei Microdevices and also a gyroscope one from STMicroelectronics. Could you use Market apps AndroSensor and Sensor List to verify and let us know?


text:
Q: Node.js mongoDB Issue with pushing new elements to already existing object How do i make it so when i submit to my database it adds it to a object that has the same name? I want it so that when i submit an array on the same date they go under the same object. When I try it automatically adds an object between the parent element and the element I'm adding.
MongoDB adds this object between the elements I want.
I tried looking everywhere but could find any help.
My code:
   app.post('/add-submit', (req,res) => {
    var query = { username: req.body.username };
    db.collection("users").find(query).toArray((err, result) => {
        if (err) throw err;
        console.log(result);
    });

    let postDate = new Date();
    let dd = String(postDate.getDate()).padStart(2, '0');
    let mm = String(postDate.getMonth() + 1).padStart(2, '0');
    let yyyy = postDate.getFullYear();

    postDate = mm + '/' + dd + '/' + yyyy;

    subject = req.body.subject

    pushValue = {"submits": {[postDate]: { [subject] : [ time = req.body.time, description = req.body.description, date = postDate ]}}}

    console.log(pushValue)

    let myquery = { username: req.body.username};
    let newvalues = { $push: pushValue }
    db.collection("users").updateOne(myquery, newvalues, (err, response) => {
        if (err) throw err;
        console.log("1 document updated");
        res.redirect('/users/'+req.body.id)
    });
})

What I'm trying to do:

Thanks.

A: I try to give a few pointers. Since OP mentioned he is not experienced in that matter, I recommend using the library mongoose. For me, it's the go-to library when working with NodeJS and MongoDB. It's easy to setup and use even for beginners.
Now, to the problem :
Work with multiple Models
Try not to fit everything into one document model. There is a term called 'One-To-Many'-Relationship. And your usecase would be a perfect example for it :

*

*A user can me mapped to multiple submits, but one submit can only be mapped to one specific user.

*Speaking in MongoDB Terms, this would mean, a user has multiple submit entities, and

*and a submit document has one reference to one user.

How would that look like (using Mongoose) in simplified models

const UserSchema = new Schema ({
  username : String,
  email : String,
  password : String,
  submits: [{ type: Schema.Types.ObjectId, ref: 'Submit', 'default' : [] }],
});

const SubmitSchema = new Schema ({
  date : Date,
  subject : String,
  description : String,
  user : { type: Schema.Types.ObjectId, ref: 'User', 'default' : null }
});

This would result in data looking like this (if using populate)
// retrieve user and all its submits
let user = await User.findById(userid).populate('submits').exec();
console.log( user.submits );

{
  date : "Mon Oct 18 2020 11:36:49",
  subject : "This is the subject",
  description : "This is the description",
  user : "595919bdbcb1b19",
  _id : "5482193857cbc818bc1912"
},
{
  date : "Mon Oct 18 2020 11:50:23",
  subject : "This is the subject",
  description : "This is the description",
  user : "595919bdbcb1b19",
  _id : "29299cbca9192bdcabbb"
},
{
  date : "Mon Oct 19 2020 17:24:11",
  subject : "This is the subject",
  description : "This is the description"
  user : "595919bdbcb1b19",
  _id : "5521545b5c5b5aa5125"
},
{
  date : "Mon Oct 20 2020 20:11:57",
  subject : "This is the subject",
  description : "This is the description"
  user : "595919bdbcb1b19",
  _id : "51525235cbba51b15522"
}

These "submit" documents can then be easily sorted by date and or time for example, even client side. This actually also simplifies the structure, you don't need date and time seperate. Also this way it is easier to modify or delete single submits.
You can also query submits directly, like this (simplified)
Something like this would give you all posts for a specific date and specific user :

let submits = await Submit.find({
  user : userid,
  date : new Date('2020-10-19')
}).exec();


text:
Q: How do I add transition to the effect of hide() and show() on these elements? In the following SSCCE, how can I animate the appearance of .items using show() and their disappearance using hide(), such that it looks like the item5, item6, item7, item8 have flown into the viewport?
That is, what I want is that when the .next-arrow is clicked, for example for the first time, the hiding of item1, item2, item3, item4, and the showing of item5, item6, item7, item8, is "transitioned" - just like new pages flow into the viewport in this website.
How can I do that?

$(document).ready(function() {
  //alert('ready');//check

  var numberOfItems = $('.item').length;
  //alert('numberOfItems => ' + numberOfItems);//check

  displayNextArrowOnCondition();
  displayPreviousArrowOnCondition();

  /**
   *
   **/
  $('a.next-arrow').click(function(event) {
    event.preventDefault();

    var currentFirstItem = getCurrentFirstItem(); // Difference between var and no var SO: If you're in the global scope then there's no difference. If you're in a function then var will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

    $('div.item' + currentFirstItem).hide(); //We don't need to have the condition of checking this element's existence because the next-arrow whose handler this method is, appears only if the numberOfItems is greater than the id of the item with the greatest id among the elements currently visible on the screen.
    if (('div.item' + (currentFirstItem + 1)).length) { //SO: How can I check the existence of an element in jQuery?? In JavaScript, everything is truthy or falsy and for numbers, 0 means false, everything else true. So you could write: "if ($(selector).length)" - and you don't need that > 0 part.
      $('div.item' + (currentFirstItem + 1)).hide();
    }
    if (('div.item' + (currentFirstItem + 2)).length) {
      $('div.item' + (currentFirstItem + 2)).hide();
    }
    if (('div.item' + (currentFirstItem + 3)).length) {
      $('div.item' + (currentFirstItem + 3)).hide();
    }

    hidePreviousArrow();
    hideNextArrow();

    displayPreviousArrowOnCondition();
    displayNextArrowOnCondition();
  });

  /**
   *
   **/
  $('a.previous-arrow').click(function(event) {
    event.preventDefault();

    var currentFirstItem = getCurrentFirstItem();

    $('div.item' + (currentFirstItem - 1)).show();

    if (('div.item' + (currentFirstItem - 2)).length) {
      $('div.item' + (currentFirstItem - 2)).show();
    }
    if (('div.item' + (currentFirstItem - 3)).length) {
      $('div.item' + (currentFirstItem - 3)).show();
    }
    if (('div.item' + (currentFirstItem - 4)).length) {
      $('div.item' + (currentFirstItem - 4)).show();
    }

    hidePreviousArrow();
    hideNextArrow();

    displayPreviousArrowOnCondition();
    displayNextArrowOnCondition();
  });

  /**
   * DISPLAY NEXT ARROW WHEN
   * 1. NUMBER OF ITEMS IS GREATER THAN THE id OF THE LAST ITEM DISPLAYED IN THE CURRENT VIEWPORT
   **/
  function displayNextArrowOnCondition() {
    //alert('displayNextArrowOnCondition called');//check
    //Iterate through items in OPPOSTIE order, and when found the first one which is not hidden by hide() or display:none, assign it to currentLastItem (because this is the first item in the viewport), and break out from the loop.
    var currentLastItem = getCurrentLastItem();
    //alert('currentLastItem -> ' + currentLastItem);//check
    if (currentLastItem < numberOfItems) {
      $('a.next-arrow').css('display', 'block');
      $('.wrapper').mouseover(function() {
        //$('a.next-arrow').css('visibility', 'visible');
      });
      $('.wrapper').mouseleave(function() {
        //$('a.next-arrow').css('visibility', 'hidden');
      });
    }
  }

  /**
   * DISPLAY PREVIOUS ARROW WHEN
   * 1. THE id OF THE FIRST DISPLAYED ITEM IS GREATER THAN 4
   **/
  function displayPreviousArrowOnCondition() {
    //Iterate through items in order, and when found the first one which is not hidden by hide() or display:none, assign it to currentFirstItem (because this is the first item in the viewport), and break out from the loop.
    var currentFirstItem = getCurrentFirstItem();
    if (currentFirstItem > 4) {
      $('a.previous-arrow').css('display', 'block');
      $('.wrapper').mouseover(function() {
        $('a.previous-arrow').css('visibility', 'visible');
      });
      $('.wrapper').mouseleave(function() {
        $('a.previous-arrow').css('visibility', 'hidden');
      });
    }
  }

  /**
   * DISPLAY:NONE NEXT ARROW IF IT IS VISIBLE
   **/
  function hideNextArrow() {
    //alert('hideNextArrow called');//check
    if ($('a.next-arrow').css('display').toLowerCase() == 'block') { //The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false.| Just in case anyone was wondering in 2012: === is way faster than ==. jsperf.com/comparison-of-comparisons.
      //alert('YES if ($(\'a.next-arrow\').attr(\'display\').toLowerCase() == \'block\'). SO I AM CHANGING IT TO none.');//check
      $('a.next-arrow').css('display', 'none');
    } //else { alert('NO  if ($(\'a.next-arrow\').attr(\'display\').toLowerCase() == \'block\').'); } //check
  }

  /**
   * DISPLAY:NONE PREVIOUS ARROW IF IT IS VISIBLE
   **/
  function hidePreviousArrow() {
    //alert('hidePreviousArrow called');//check
    //alert($('a.previous-arrow').css('display'));//check
    if ($('a.previous-arrow').css('display') == 'block') {
      //alert('YES if ($(\'a.previous-arrow\').attr(\'display\').toLowerCase() == \'block\'). SO I AM CHANGING IT TO none.');//check
      $('a.previous-arrow').css('display', 'none');
    } //else { alert('NO  if ($(\'a.previous-arrow\').attr(\'display\').toLowerCase() == \'block\').'); } //check
  }

  /**
   *
   **/
  function getCurrentFirstItem() {
    for (i = 1; i <= numberOfItems; i++) {
      if ($("#" + i).visible(true, true)) {
        //alert('YES if (  $("#"+i).visible(true, true)  )');//check
        currentFirstItem = i;
        break;
      } //else { //alert('NO if (  $("#"+i).visible(true, true)  )'); }//check
    }
    //alert('currentFirstItem -> ' + currentFirstItem);//check
    return currentFirstItem;
  }

  /**
   *
   **/
  function getCurrentLastItem() {
    for (j = numberOfItems; j >= 1; j--) {
      if ($("#" + j).visible(true, true)) {
        //alert("YES if (  $(\"#\"+j).visible(true, true) ) ");//check
        currentLastItem = j;
        break;
      } //else { //alert('NO if (  $("#"+j).visible(true, true) )'); } //check
    }
    //alert('currentLastItem -> ' + currentLastItem);//check
    return currentLastItem;
  }

});
html,
body,
body div,
span,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
abbr,
address,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
samp,
small,
strong,
sub,
sup,
var,
b,
i,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
figure,
footer,
header,
hgroup,
menu,
nav,
section,
time,
mark,
audio,
video,
details,
summary {
  margin: 0px;
  padding: 0px;
  border: 0px none;
  background: transparent none repeat scroll 0% 0%;
  font-size: 100%;
  vertical-align: baseline;
}
.wrapper {
  position: relative;
  white-space: nowrap;
  overflow: hidden;
}
div.item {
  /*position:absolute;*/
  display: inline-block;
  width: 25%;
  height: 25vw;
}
.item1 {
  left: 0%;
  background-color: wheat;
}
.item2 {
  left: 25%;
  background-color: pink;
}
.item3 {
  left: 50%;
  background-color: beige;
}
.item4 {
  left: 75%;
  background-color: gainsboro;
}
.item5 {
  left: 100%;
  background-color: coral;
}
.item6 {
  left: 125%;
  background-color: crimson;
}
.item7 {
  left: 150%;
  background-color: aquamarine;
}
.item8 {
  left: 175%;
  background-color: darkgoldenrod;
}
.item9 {
  left: 200%;
  background-color: khaki;
}
.item10 {
  left: 225%;
  background-color: indianred;
}
.item11 {
  left: 250%;
  background-color: mediumspringgreen;
}
.previous-arrow,
.next-arrow {
  width: 30px;
  height: 50%;
  top: 50%;
  position: absolute;
  opacity: 0.7;
  color: white;
  background-repeat: no-repeat;
  margin-top: -30px;
  display: none;
}
.previous-arrow {
  background-image: url(a2.png);
  left: 0px;
}
.next-arrow {
  background-image: url(b2.png);
  right: 0px;
}
.previous-arrow,
.next-arrow {
  opacity: 1;
}
body {
  background-color: black;
}

  >-->

a.

a.

a.

a.

a.

a.

a.

a.

a.

a.

a.

  <

A: If you want use show() and hide() only, you can use show('slow') and hide('slow'), etc. Other than that there are many ways and effects you can use.
Please follow this link to get to know how many ways were there to do this.
jQuery Effects

A: You can use css transitions or css animations. Animations like:

*

*Define css class rules and assign class name to the elements you want to animate

.doFadeIn {
    -webkit-animation:fadeInSlide forwards ease-in 150ms;
    animation:fadeInSlide forwards ease-in 150ms;
}
.doFadeOut {
    -webkit-animation:fadeOutSlideDown forwards ease-out 150ms;
    animation:fadeOutSlideDown forwards ease-out 150ms;
}

*Define keyframes for the animations

    @keyframes fadeInSlide
    {
         0% { opactity:0; transform: translateX(-100px); }
         100% { opactity:1; transform: translateX(0); }
    }

When assigning doFadeIn to the class name of elements, they will:
Fade in - opacity:0 to 1 (0% visible to 100% visible)
Moves along the horizontal axis (X) 100px left of the elements original position to it's original position.
It will do this spanning the duration of 150 milli-seconds

A: You can pass a parameter for show() function like .show('slow') that will do the animation like fadeIn() function.
Check the documentation with examples

A: You can use .hide(), fadeOut(), show(), fadeIn()
Sample Codes
You can use .show() to Display the matched elements.
Sample code for when user type something on an input text show a list.
    $("#search-guide").focusin(function () {
      $("#list-user-guides").show();
    });

You can use .hide() to Hide the matched elements.
Sample code for when user click somewhere else on the screen hide the list.
    $("#search-guide").focusin(function () {
      $("#list-user-guides").hide();
    });

But i personally use .fadeIn() and fadeOut() because those two method come with a smooth animation.
You can check the official doc as mentioned above answers.


text:
Q: Exporting a single feature out of featureCollection as shapefile in Google Earth Engine Does any one know, how to export a single feature out of featureCollection in Google Earth Engine?
I am using below code to export every features separately. The fetureCollection has 33 different features which represents different 33 geometry of regions. I want to get those geometry separately as shapefile.
The blow code gives me an error in task section: Error: Invalid argument: 'collection' must be a FeatureCollection. So, tried to get the sub_region(in the code) as ee.FeatureCollection instead of ee.Feature , but I am still getting same error.
var refReg = ee.FeatureCollection("users/username/referenceRegions");

var referenceRegions={
  0:'NTP',1:'STP',2:'ETP',3:'WIO',4:'CAR',5:'NAU',6:'NEB',7:'NEU',8:'SAF',
  9:'SAH',10:'SAU',11:'SSA',12:'TIB',13:'WAF',14:'WAS',15:'WNA',16:'WSA',
  17:'ALA',18:'AMZ',19:'CAM',20:'CAS',21:'CEU',22:'CGI',23:'CNA',24:'EAF',
  25:'EAS',26:'ENA',27:'MED',28:'NAS',29:'ARC',30:'SAS',31:'SEA',32:'ANT'
};

var region_list = refReg.toList(refReg.size());

var reg_size = refReg.size().getInfo();

for (var i = 0; i<reg_size;i++){
   var sub_region = ee.Feature(region_list.get(i));

   Export.table.toDrive({
   collection: sub_region,
   description:referenceRegions[i],
   folder:"GEE_Features",
   fileFormat: "SHP",
   })
}

If you see the below image, the FeatureCollection refReg has all these 33 regions, I want these regions to export individually.

Thanks for the help!! :)

A: Your asset ID doesn't look correct, so I cannot try it. But just by looking at it, everything look OK except for when you pass sub_region as your Export.table.toDrive() collection. That property must be a feature collection. Try with this:
Export.table.toDrive({
  collection: ee.FeatureCollection([sub_region]),
  description: referenceRegions[i],
  folder: "GEE_Features",
  fileFormat: "SHP",
})


text:
Q: Map and unordered_map My question is more for learning purpose than for debugging purpose:
I'm currently optimising a code for a little game of mine, and I wanted to know:
I'm using a map for dispatching some value inside my programme, so is a unordered_map faster in use than a map?
(btw sorry for my english, it's not my native language!)

A: A std::unordered_map is a "hash_map", which means that searching it is O(1), where a std::map is a red-black tree, searching that is O(log2(n)). So, if you have 1000 elements, the difference is looking at 10 keys in the std::map before finding the "right" one, vs. looking at one. With 1 million elements, we look at 20 keys in the std::map before getting to the "right" one - still only one in a std::unordered_map.
However, you need to hash the "key", which means doing some form of calculation to make it a number.
It also depends on how often you insert/remove elements, compared to how often you just look up the elements.
For larger data-sets, the size and locality can also have a big impact, and searching through the "first few layers" is often quick because it's in the cache [if you are searching through the same map several times], where unordered map is taking up more space (have to have some "spare" slots, because it's very unlikely that all 10000 elements generate hash values that are exactly 10000 elements, so typically, the hash map is far from "full"). Because "recent" hash searches are unlikely to match current ones, cache probably doesn't help much either.
And of course, the std::unordered_map is, as the name implies, unordered - if you iterate through it, the keys are in hash-order (modulo bucket-count, so even if you know the hash, it's typically hard to know what order it is), not in "sorted" order. This can be important in some cases.
So whether that gives you any noticeable performance benefit is something you will have to figure out by measuring the performance.

A: The difference here is that a map internally uses a red black tree and a unordered map is s hash table. The unordermap is very fast compared to the map because putting elements into the map required just 1 (O(1)) "actions" where the map needs to find the correct position in the tree to store the value which was put into the map (O(log n)). You can also read the C++ doc for map and unordermap


text:
Q: Python-driven Bulk API 2.0 hardDelete yields "errorMessage": "InvalidBatch : InvalidBatch : The 'delete' batch must contain only ids" I am trying to write a bit of python code to permanently delete some records using the Salesforce.com Bulk API v2.
Using curl, I have success.  I:

*

*create an Bulk API 2 hardDelete job

*PUT the file to .../jobs/ingest/7501E00000BlHU6QAN/batches

*set the job status to UploadComplete

*check the job at .../jobs/ingest/7501E00000BlHU6QAN
Commands:
curl -X POST -H 'Authorization: Bearer XXXXX' -H 'Content-Type: application/json; charset=UTF-8' -H 'Accept: application/json' -d '{"object" : "SBQQ__Quote__c", "contentType" : "CSV", "operation" : "hardDelete", "lineEnding" : "CRLF"}' https://instance.my.salesforce.com/services/data/v45.0/jobs/ingest/ | python -m json.tool
{
    "id": "7501E00000BlHU6QAN",
    "operation": "hardDelete",
    "object": "MyObject",
    "createdById": "MyID",
    "createdDate": "2019-04-05T05:51:10.000+0000",
    "systemModstamp": "2019-04-05T05:51:10.000+0000",
    "state": "Open",
    "concurrencyMode": "Parallel",
    "contentType": "CSV",
    "apiVersion": 45.0,
    "contentUrl": "services/data/v45.0/jobs/ingest/7501E00000BlHU6QAN/batches",
    "lineEnding": "CRLF",
    "columnDelimiter": "COMMA"
}

curl -X PUT -H 'Authorization: Bearer XXXXX' -H 'Content-Type: text/csv' -H 'Accept: application/json' --upload-file /cygdrive/c/Users/kurtb/Desktop/RecordsToDelete.csv https://instance.my.salesforce.com/services/data/v45.0/jobs/ingest/7501E00000BlHU6QAN/batches

curl -X PATCH -H 'Authorization: Bearer XXXXX' -H 'Content-Type: application/json; charset=UTF-8' -H 'Accept: application/json' -d '{"state" : "UploadComplete" }' https://instance.my.salesforce.com/services/data/v45.0/jobs/ingest/7501E00000BlHU6QAN | python -m json.tool
{
    "id": "7501E00000BlHU6QAN",
    "operation": "hardDelete",
    "object": "MyObject",
    "createdById": "MyID",
    "createdDate": "2019-04-05T05:51:10.000+0000",
    "systemModstamp": "2019-04-05T05:51:10.000+0000",
    "state": "UploadComplete",
    "concurrencyMode": "Parallel",
    "contentType": "CSV",
    "apiVersion": 45.0
}

curl -X GET -H 'Authorization: Bearer XXXXX' -H 'Accept: application/json' https://instance.my.salesforce.com/services/data/v45.0/jobs/ingest/7501E00000BlHU6QAN | python -m json.tool
{
    "id": "7501E00000BlHU6QAN",
    "operation": "hardDelete",
    "object": "MyObject",
    "createdById": "MyID",
    "createdDate": "2019-04-05T05:51:10.000+0000",
    "systemModstamp": "2019-04-05T06:01:04.000+0000",
    "state": "JobComplete",
    "concurrencyMode": "Parallel",
    "contentType": "CSV",
    "apiVersion": 45.0,
    "jobType": "V2Ingest",
    "lineEnding": "CRLF",
    "columnDelimiter": "COMMA",
    "numberRecordsProcessed": 42,
    "numberRecordsFailed": 0,
    "retries": 0,
    "totalProcessingTime": 1272,
    "apiActiveProcessingTime": 1201,
    "apexProcessingTime": 302
}

SUCCESS!!!!!
In python, if I attempt to send the same file referenced above using:
Salesforce_API_Call('/%s' % Dictionary_AddedSalesforceBulkAPI2HardDeleteJob['contentUrl'], method = "PUT", files={'file': open('c:/users/Kurtb/Desktop/ItemsToDelete.csv', 'rb')})

Debug: headers: {'Content-type': 'text/csv', 'Accept': 'application/json', 'Authorization': 'Bearer XXXXX'}
Debug: API PUT call: https://instance.my.salesforce.com/services/data/v45.0/jobs/ingest/7501E00000BlHNjQAN/batches

and subsequently close the job manually:
curl -X PATCH -H 'Authorization: Bearer XXXXX' -H 'Content-Type: application/json; charset=UTF-8' -H 'Accept: application/json' -d '{"state" : "UploadComplete" }' https://instance.my.salesforce.com/services/data/v45.0/jobs/ingest/7501E00000BlHNjQAN | python -m json.tool

    "id": "7501E00000BlHNjQAN",
    "operation": "hardDelete",
    "object": "MyObject",
    "createdById": "MyID",
    "createdDate": "2019-04-05T05:09:57.000+0000",
    "systemModstamp": "2019-04-05T05:09:57.000+0000",
    "state": "UploadComplete",
    "concurrencyMode": "Parallel",
    "contentType": "CSV",
    "apiVersion": 45.0
}

and subsequently query the job to inquire on its disposition:
curl -X GET -H 'Authorization: Bearer XXXXX' -H 'Accept: application/json' https://instance.my.salesforce.com/services/data/v45.0/jobs/ingest/7501E00000BlHNjQAN | python -m json.tool
{
    "id": "7501E00000BlHNjQAN",
    "operation": "hardDelete",
    "object": "MyObject",
    "createdById": "MyID",
    "createdDate": "2019-04-05T05:09:57.000+0000",
    "systemModstamp": "2019-04-05T05:10:32.000+0000",
    "state": "Failed",
    "concurrencyMode": "Parallel",
    "contentType": "CSV",
    "apiVersion": 45.0,
    "jobType": "V2Ingest",
    "lineEnding": "CRLF",
    "columnDelimiter": "COMMA",
    "numberRecordsProcessed": 0,
    "numberRecordsFailed": 0,
    "retries": 0,
    "totalProcessingTime": 0,
    "apiActiveProcessingTime": 0,
    "apexProcessingTime": 0,
    "errorMessage": "InvalidBatch : InvalidBatch : The 'delete' batch must contain only ids"
}

FAILED!!!!
Here are first few lines of the RecordsToDelete.csv file:
Id
a3A1E000001AWTdUAO
a3A1E000001AWTcUAO
Each line, including the last line, of the RecordsToDelete.csv file is terminated with CRLF.

Any thoughts as to why the same file PUT with curl works, but yet using python, it does not?  Any thoughts as to where to look and/or how to configure Salesforce to debug what's happening when I'm using the python version?


text:
Q: Python SciPy ODE solver not converging I'm trying to use scipy's ode solver to plot the interaction between a 2D system of equations. I'm attempting to alter the parameters passed to the solver by the following block of code:
# define maximum number of iteration steps for ode solver iteration
m = 1 #power of iteration
N = 2**m #number of steps

# setup a try-catch formulation to increase the number of steps as needed for solution to converge
while True:
    try:
        z = ode(stateEq).set_integrator("vode",nsteps=N,method='bdf',max_step=5e5)
        z.set_initial_value(x0, t0)
        for i in range(1, t.size):
            if i%1e3 == 0:
                print 'still integrating...'
            x[i, :] = z.integrate(t[i]) # get one more value, add it to the array
            if not z.successful():
                raise RuntimeError("Could not integrate")
        break
    except:
        m += 1
        N = 2**m
        if m%2 == 0:
            print 'increasing nsteps...'
            print 'nsteps = ', N

Running this never breaks the while loop. It keeps increasing the nsteps forever and the system never gets solved. If I don't put it in the while loop, the system gets solved, I think, because the solution gets plotted. Is the while loop necessary? Am I formulating the solver incorrectly?

A: The parameter nsteps regulates how many integration steps can be maximally performed during one sampling step (i.e., a call of z.integrate). Its default value is okay if your sampling step is sufficiently small to capture the dynamics. If you want to integrate over a huge time span in one large sampling step (e.g., to get rid of transient dynamics), the value can easily be too small.
The point of this parameter is to avoid problems arising from unexpectedly very long integrations. For example, if you want to perform a given integration for 100 values of a control parameter in a loop over night, you do not want to see on the next morning that the No. 14 was pathological and is still running.
If this is not relevant to you, just set nsteps to a very high value and stop worrying about it. There is certainly no point to successively increase nsteps, you are just performing the same calculations all over again.

Running this never breaks the while loop. It keeps increasing the nsteps forever and the system never gets solved.

This suggests that you have a different problem than nsteps being exceeded, most likely that the problem is not well posed. Carefully read the error message produced by the integrator. I also recommend that you check your differential equations. It may help to look at the solutions until the integration fails to see what is going wrong, i.e., plot x after running this:
z = ode(stateEq)
z.set_integrator("vode",nsteps=1e10,method='bdf',max_step=5e5)
z.set_initial_value(x0, t0)

for i,time in enumerate(t):
    x[i,:] = z.integrate(time)
    if not z.successful():
        break

Your value for max_step is very high (this should not be higher than the time scale of your dynamics). Depending on your application, this may very well be reasonable, but then it suggests that you are working with large numbers. This in turn may mean that the default values of the parameters atol and first_step are not suited for your situation and you need to adjust them.


text:
Q: tmutil compare fails on APFS if issued from Java app This has been driving me nuts for several days!!!
Wrote a utility to compare some TM backups, written in Scala/Java. Works perfectly for sparsebundles in HFS format but fails if the sparsebundle is APFS format.
Program runs under 'root', started at boot by a /Library/LaunchDaemon
All of the commands below are issued from within the app by the Java Runtime.getRuntime().exec(cmd) call -- which starts a separate process to execute the given command in parallel.
Program mounts the volume via: hdiutil attach /Volumes/UltraA/JDCMacBook.sparsebundle -readonly -noverify -noautofsck
and is mounted successfully at /Volumes/Time\ Machine\ Backups
The command: tmutil listbackups -d /Volumes/Time\ Machine\ Backups
produces (trimmed list):

2022-03-26-200531.backup
2022-04-02-090801.backup
2022-04-09-165527.backup
2022-04-16-180524.backup
....

The same command with the -m option appended produces:

/Volumes/.timemachine/2CF10664-1123-4075-91ED-FE3660C2D661/2022-03-26-200531.backup/2022-03-26-200531.backup
/Volumes/.timemachine/2CF10664-1123-4075-91ED-FE3660C2D661/2022-04-02-090801.backup/2022-04-02-090801.backup
/Volumes/.timemachine/2CF10664-1123-4075-91ED-FE3660C2D661/2022-04-09-165527.backup/2022-04-09-165527.backup
....

NOTE: All of the above work from either within the app or on the command line.
But that's when things fall apart. Issuing the command:
tmutil compare -@gmstuX /Volumes/.timemachine/2CF10664-1123-4075-91ED-FE3660C2D661/2022-04-02-090801.backup/2022-04-02-090801.backup /Volumes/.timemachine/2CF10664-1123-4075-91ED-FE3660C2D661/2022-03-26-200531.backup/2022-03-26-200531.backup
from the command line works -- but issuing the same command from within the app fails -- get:

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
<dict>
    <key>Changes</key>
    <array>
    </array>
</dict>
</plist>
Usage: tmutil compare [-@acdefghlmnstuEX] [-D depth] [-I name]
       tmutil compare [-@acdefghlmnstuEX] [-D depth] [-I name] snapshot_path
       tmutil compare [-@acdefghlmnstuEUX] [-D depth] [-I name] path1 path2

08:35:27.877  0:00.313 ERROR: TMUtil parse failure on 2022-04-02-090801-2022-03-26-200531 -- javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,1]
Message: Content is not allowed in trailing section.

(last line is issued by the app picking up an exception from the XML parser.)
Thought that it might be some type of special character translation problem with the exec(cmd) processing so tried double-quotes around the paths. Finally, also changed so that instead of invoking tmutil directly it invokes a Bash script and passes the paths to that script -- which then invokes tmutil.
Same results - tmutil compare fails.
Would appreciate any help or suggestions!!!!
Thanks


text:
Q: Installing Laravel with WAMP - Routers not working I installed Laravel with Composer, under wampserver.
My directory is: C:/wamp/www/laravel/firstProject
public file : C:/wamp/www/laravel/firstProject/public
SO when I try to go localhost/laravel/firstProject/public/projects
I get this error: "The requested URL /laravel/index.php was not found on this server."
I can access when I type: localhost/laravel/firstProject/public/index.php/projects
I edited httpd.conf and uncommented mod_rewrite.
Changed the AllowOverride none to AllowOverride all.
Also added RewriteBase /laravel/ to .htaccess then restarted all but still having the same issue.
This is my routes.php file:
<?php

// show a static view for the home page (app/views/pages/home.blade.php)

Route::get('/', function() {
return View::make('pages.home');
});

Route::get('about', function() {
return View::make('pages.about');
});

Route::get('projects', function() {
return View::make('pages.projects');
});

Route::get('contact', function() {
return View::make('pages.contact');
});

This is my htaccess:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On
RewriteBase /laravel/
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

I know the question was asked many times, yet I tried lots of the solutions provided, still the same..
Thanks for any help or advice.

A: Did you try this .htaccess?
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

it's the one from http://laravel.com/docs/4.2/installation#pretty-urls

A: I added following line in .htaccess file and its works fine.
RewriteEngine On
RewriteBase /learn/


text:
Q: Mathematical description of a random sample Mathematical description of a random sample: which one is it and why?

*

*$X_1(\omega), X_2(\omega), ..., X_n(\omega)$, where $X_1, ..., X_n$ are different but i.i.d. random variables.

*$X(\omega_1), X(\omega_2), ..., X(\omega_n)$, where $X$ is a (single) random variable.

A: Let's say that the result of an experiment is a n-tuple of real numbers. When we accept 1. as a model of our experiment, we have a probability space $\Omega$ and a random variable
$$
X: \Omega \to \mathbb{R}^n
$$
The outcome of an experiment corresponds to a $\omega \in \Omega$ and therefore to an n-tuple $(X_1(\omega), ..., X_n(\omega))$. This model allows us to ask if the elements of this n-tuple are independent and if not, what their joint distribution is.
If we accept 2. as a model, we have a probability space $\Omega$ and a tuple of random variables
$$
X_i: \Omega \to \mathbb{R}
$$
so that the n-tuple is a random variable of the probability space $\Omega^n$ (Cartesian product). So, in this case, the independence of the elements of the tuple is built into the model. If the elements of the tuple are supposed to be independent, it does not matter.
Note that in the first case we can set $X_i = X_j$, either strict or modulo a null set; in this case we will have a tuple of identically distributed random variables. Choice no.1 does not necessarily imply that the elements of the n-tuple are different random variables (either strictly different or modulo a null set).

A: Thanks to the stimulating discussion with @Didier, I've clarified something for myself. From the technical standpoint, we have $n$ random variables in the option 1, and $n$ numbers in the option 2. The problem with this may be illustrated by the following example. Consider 3 different people producing their own random samples of size 5 by throwing a die. Here is what they get:
1 person: 1, 3, 1, 4, 2 $\;\;\;\rightarrow$ $X_1(\omega'), X_2(\omega'), ..., X_5(\omega')$
  2 person: 2, 2, 1, 6, 3 $\;\;\;\rightarrow$ $X_1(\omega''), X_2(\omega''), ..., X_5(\omega'')$
  3 person: 1, 4, 2, 1, 3 $\;\;\;\rightarrow$ $X_1(\omega'''), X_2(\omega'''), ..., X_5(\omega''')$
On the right side, I used option 1 to code these outcomes. How to code them using option 2? We can try this:
1 person: 1, 3, 1, 4, 2 $\;\;\;\rightarrow$ $X(t_1), X(t_2), ..., X(t_5)$
  2 person: 2, 2, 1, 6, 3 $\;\;\;\rightarrow$ $X(t_1), X(t_2), ..., X(t_5)$
  3 person: 1, 4, 2, 1, 3 $\;\;\;\rightarrow$ $X(t_1), X(t_2), ..., X(t_5)$
($t$ is for "trial number"). Well, this clearly doesn't work. What about this:
1 person: 1, 3, 1, 4, 2 $\;\;\;\rightarrow$ $X(\omega_1), X(\omega_3), ..., X(\omega_2)$
  2 person: 2, 2, 1, 6, 3 $\;\;\;\rightarrow$ $X(\omega_2), X(\omega_2), ..., X(\omega_3)$
  3 person: 1, 4, 2, 1, 3 $\;\;\;\rightarrow$ $X(\omega_1), X(\omega_4), ..., X(\omega_3)$
This seems to work, but how to write it in a general manner?
person ?: ?, ?, ?, ?, ? $\;\;\;\rightarrow$ $X(?), X(?), X(?), X(?), X(?)$
I think it is this point at which we arrive to an appropriate general notation specified in the option 1.

A: The first line is a notation for "$n$ given functions $X_i$, all computed on the same input (which was randomly chosen) $\omega$".   For example, $\sin(t), \cos(t), \exp(t), \dots$ where $t$ is a randomly chosen integer between 1 and 128.  Total information in this set of random numbers is 7 bits no matter how large $n$ is.  The sine, cosine, and exponential of $t$ are not independent.
The second line describes: "one function $X$ computed on $n$ different random inputs $\omega_i$".  For example, $X(t)$ is the $t^{\rm th}$ user in the math.SE userlist where $t$ is an integer from 1 to 128.  If you make $n$ random choices of $t_i$ the amount of information in the list $X(t_1), \dots, X(t_n)$ is $7n$ bits; each $X(t_i)$ is independent of the others.
Only the second corresponds to an i.i.d random sample of $n$ objects.  To describe such a sample in the notation used in (1), $\omega$ must depend on $n$, such as $\omega = (\omega_1, \dots, \omega_n)$.  The notation as given in the question does not explicitly include any such dependence.

[added in light of the comments discussion]
The original question did not specify precisely what $X$ and $\omega$ mean:

Mathematical description of a random sample: which one is it and why?

*

*$X_1(\omega), X_2(\omega), ..., X_n(\omega)$, where $X_1, ..., X_n$ are different but i.i.d. random variables.

*$X(\omega_1), X(\omega_2), ..., X(\omega_n)$, where $X$ is a (single) random variable.

I think the trouble is that (1) should be written as:
"  0. $X_1, X_2, \dots X_n$ where the $X_i$ are different but i.i.d random variables."  (Each $X_i$ is a selection from the distribution of one sample.)
In the original schemes 1-2, writing both "$X$" and "$\omega$" expressions has the implication that they play different roles: that $\omega$ are the random choices made in constructing the samples, and the $X$ or $X_i$ are deterministic functions describing how to convert the random choices into particular samples.  For example, if the random samples are single random bits generated using dice, $\omega$ or $\omega_i$ can denote random throws of dice and $X$ a method of converting 1/2/3/4/5/6 outcomes into 0/1 bits.  Then $\omega_i$ is itself a sequence of i.i.d random variables, and as a
result, so is $X(\omega_i)$, as in formulation (2).
The standard mathematical descriptions are (0), if the details of the sample-generation process are suppressed, and (2), if they are made more explicit.  It would be interesting to examine the literature on this but I think (1) is much less common, and where used it may involve strange conventions such as a "prophetic" $\omega$ that includes all future randomness that is used in generating other random variables that are combined with the $X_i$ in subsequent calculations.   Be that as it may, there is also a notational or conceptual inconsistency in scheme (1), where the sampling results $X$ are individuated into particular $X_i$ but the underlying sequence of i.i.d random choices is aggregated into one collective $\omega$.  The definition of $\omega$ is either left nebulous ("all randomness used to generate the samples") or, if it is made more explicit using the sequence $\omega_i$, then $\omega$ itself is superfluous and the situation would normally be expressed using scheme (2).
The conclusion (or mine at least) is that (1) is defective but (2) or (0) make sense.

A: The reason why the answer might be (2) rather than (1) is as follows -
To start with we have sample space $\varOmega$ with unspecified event space and probability measure. And we have random variable $X:\varOmega\rightarrow\mathbb{R}$.
For any $n$ we can define a product space and use our random variable to define $X^{n}:\varOmega^{n}\rightarrow\mathbb{R}^{n}$ Then a sample $\overline{\omega}=(\omega_{1},...,\omega_{n})$ is an element of product sample space $\varOmega^{n}$. Here we pinned down all moving parts, there are no unspecified processes or hidden distributions lurking beneath.
However if we assume that n i.i.d. variables are being picked to generate a new sample from the same element $\omega$ we don't really pin the definition of the sample because we don't say anything about where those variables came from and how they were picked. It's like saying that we have random variable $X$, which we would like to study so postulate n more random variables distributed using same distribution, which we don't know... In general we should try explaining things using a minimal number of existing building blocks and without postulating new building blocks if we can help it.
Another piece of evidence in favour of (2) is that the samples $X_i$ are not just distributed identically to $X$ but have exactly same values as $X$. Sampling means picking values that $X$ takes. If $X_i$ were only distributed in the same way we could expect them to be able to take values that $X$ does not take on null events. But it does not seem to be the case. This suggests that samples are drawn from the sample space rather than returned by n additional i.i.d. random variables working on same $\omega$ elements.
There is a puzzling issue with all this, which I am currently struggling with - the samples defined in this way must be equally probable. Does it mean that each $\omega_i$ must have same probability? Does it mean that $\varOmega$ must be finite and the probability measure on it must be uniform? Or it can be finite and not uniform but we would use weights to equalise chances of all $\omega_i$. What about infinite sample spaces? Are they not samplable in a meaningful way?


text:
Q: Please verify that the package.json has a valid "main" entry Installed bootstrap via npm on my react project
Importing bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';
but it outputs an error: Cannot find module 'D:\project\my-app\node_modules\schema-utils\src\index.js'. Please verify that the package.json has a valid "main" entry

A: I had to delete both my package-lock.json and node_modules, then
run npm i. (this was in my react app)

A: Try deleting package-lock.json and run npm install
Verify that in your package.json file there is an entry for main, usually something like "main": "dist/cjs"

A: If you're using yarn try deleting yarn.lock and run yarn again.

A: Try to use "npm update --force" which resolves my issue

A: I went for another approach. As deleting package-lock.json & running npm install didn't work for me, I deleted my project and created another one with npx create-react-app my-react-activities.
Once the project was created, I cd into it and ran npm start.
I can't tell you why it worked, but it runs well. If anyone has an explanation for it, I would gladly read it.


text:
Q: Calculating variable in math equation I am not good with math, I have this equation (very simple to most) but I need help on how to get the value of x
10 = x - (1.29 + 4.99% of x)

my question is how to calculate x IOW what is the formula used to get the value of x, if that makes sense?
Thank you.

A: $4.99 \% = \dfrac{4.99\%}{100\%} = 0.0499$.
So your equation becomes:
$$10=x-(1.29+0.0499x) \iff 10 = x - 1.29 - 0.0499x$$
Combining "like terms"
$$\iff 10 = (1 - 0.0499)x - 1.29 = 0.9501x - 1.29$$
Now add $1.29$ to both sides of the above equation to get:
$$10 + 1.29 = 0.9501 x \iff 11.29 = 0.9501 x$$
Then divide both sides by $0.9501$ to obtain $x$:
$$\dfrac{11.29}{0.9501} = x$$


text:
Q: Difference between Earth's magnetic field and Earth's gravitational field I have a misconception about this. Are these really different? If so then how?
And one more problem is that, whether satellites orbit around the Earth because of  Earth's Magnetic Field or  Earth's Gravitational Field?

A: Your question is too broad and too basic to answer it directly in any way. But I will try to answer it by using some very important checkpoints you will have to pay attention if you decide to study physics and in particular classical mechanics.
Gravity and magnetism. These two are completely different phenomena of physics. Gravity acts as a force between two masses while magnetism acts as a force between magnetic poles (which is just an idealization of a region of space where magnetic flux seems to get higher, but it really is a force that acts upon moving electric charges). Electric charges are influenced by magnetic forces in very complicated ways (see Maxwell's equations) while gravity can't influence electric charges at all. The "gravitational charge" (the mass), comes in just one flavour (positive mass), while magnetic poles can be positive or negative, creating much more varied consequences. In fact, magnetism can be attractive and repulsive at the same time, while gravity is just attractive. Magnetic poles always come in pairs, north and south, while a gravitational mass is independent of whatever is going on in the rest of the universe and can be conceptually isolated entirely without the need of another mass.
However, some attempts have been made to compare the two concepts since the inception of modern science. Renaissance revolutionary scientists like William Gilbert speculated about the Moon been bounded to Earth by some influence that could be related to magnetism. Later, Newton showed that the force acting on the Moon (or any satellite) was in fact gravity. The force of gravity between two masses, $m_1$ and $m_2$, separated a distance $r$ can be expressed by Newton's universal Law of gravitation:
$F = -G \frac{m_1m_2}{r^2}$
And the force between two magnetic poles of two different magnets follows an equation of the similar form
$F = \frac{\mu}{4\pi} \frac{q_{m_1}q_{m_2}}{r^2}$
While the expression for gravity is in the universal form (to which understand it completely) the expression for the magnetic poles, $q_{m_1}$ and $q_{m_2}$, is a particularized form of a much more general set of laws that involve electric charges and currents. But this it is an interesting way to compare both forces (even if they are in general totally diferent): In this situation both forces operate following the inverse of the square of the distance.
One striking difference between the two formulas is the proportionality constant they include. For gravity this constant is $G = 6.674\cdot 10^{-11} \; N\cdot m^2/kg^2$ and for the magnetic force the constant is $\mu/4\pi = 10^{-7} \; N/A^2$. Without any smart analysis of this we can tell that gravity can be said to be much weaker than magnetism: like $10^4$ times weaker. That would kind of suggest that magnetism is the force operating between planets but is not. The forces here also depend on the magnitude of the charges involved; Earth has a huge "gravitational charge", a.k.a. a huge mass, while its magnetic field is as strong as a loosely held magnet in a fridge. Also the fact that magnetism has a way larger constant for the force formula means that it decays with distance to nothing and it is only powerful enough at close ranges. Satellites, the Moon or everything that falls into Earth is strongly influenced by gravity. Galaxies, which also have magnetic fields, attract one another by gravitational interaction even if gravity is still "the weaker force", because of the extreme amounts of mass they have and the ridiculously small intensity of the magnetic fields involved.
Another interesting relation between the two is the one you can make using relativity, for certain regimes. Gravitomagnetism tries to create a Maxwellian system of equations for gravity with some success, but still is not a very usefull way of describing the physics of both, rather than an elegant mathematical detour with interesting points.
Many theoretical physicists devote their entire life to the concept of unification of forces, so resemblances and links between the two are often made in the most sofisitcated levels of physics, using Einstein's relativity or Quantum Mechanics. We are far away from the ideas of classical mechanics here but just so you know there are efforts to reconcile the two in a unified framework of understanding. That said, our current understanding of physics separates both completely and all the efforts to merge these forces have been failed in some way or another (for now), so they have to be quite different in nature (at least in first approximation) if decades of scrutiny and weird speculation (such as extra physical dimensions) have not completely succeded in merging the two.


text:
Q: Front end for C++ console program I am currently in the end stages of development of a console program in C++. The issue I am having is my program requires that the user be able indicate where they want to perform function on a large, dynamic grid (aprox 50x50). The console implementation I have designed is very clunky, and difficult to use. It would also be nice for the user if I had a drop down box  or similar functionality for IO.
It was recommended to me that I design the front end in C# or HTML5. I have limited, basic experience with C#, and no experience with HTML5. I am also still relatively new to C++. I would appreciate being pointed in the right direction.

A: If your program is written in a style like most source code management systems, your front-end can use the system function or process pipelines (alternatively good old popen) to issue commands and deal with them. If you cannot do something like this you can have a look at your code and check out how tied the actual logic is with the representation of things on the command line. If it deeply tied together (e.g. your compute() function pads strings to the correct length for printing), you need to refactor. If it isn't your probably can just build a GUI with any GUI tool-kit on top of the already existing code.

A: I will recommend you simple GUI. Creating GUI in the QT is very easy, there is a lot of basic tutorials. after download and install : http://qt.nokia.com/products/ there is directory called "example".
Other solution for me is another application which will save data in some reasonable format like .xml and there you can load it in your program like ./MyComplicatedApplication MyData.xml
I would not mess up with C#, why two different languages? It will be harder in the maintenance. Be aware that writing GUI in the QT is not really harder than in C# and it will be cross-platform code.

A: You could use a DataGridView in managed C++, the .NET API it's identical (for practical purpose) among languages. DataGridView exposes a large array of methods/objects, just because it's a very useful/used interface. So you could find it somewhat difficult, but the basic usage can be very simple.


text:
Q: Is there a regular expression that will ignore words that are surronded by quotes I am trying to create a regular expression that will not match words in quotes but will match words without quotes e.g
-"Welcome" - false
 -Welcome - true

A: You could match only those words that are followed by an even number of double quotes, which means they themselves are not within quotes (assuming your quotes are always paired):
\w+(?=[^"]*("[^"]*"[^"]*)*$)

function getWord(txt) {
  txt = txt.match(/\w+(?=[^"]*("[^"]*"[^"]*)*$)/);
  return txt && txt[0];
}

var input = document.querySelector('input');
var output = document.querySelector('span');

input.oninput = function () {
  output.textContent = getWord(input.value);
}

input.oninput();
Word: <input value='"two" words'>

First non-quoted:

A: (?=([^"]*"[^"]*")*[^"]*$) will exclude all double quotes in the string and all text within those double quotes.
This will also remove all newline characters if you have any
Here is my source


text:
Q: Loading tiles of EXTENT in OpenLayers locally (localStorage)? I have created a simple openlayers 3 map HERE , the map initialization code looks like so:
var styles = [
    'Road',
    'Aerial',
    'AerialWithLabels',
    'collinsBart',
    'ordnanceSurvey'];
var layers = [];
var i, ii;

var coordinate1, coordinate2;
coordinate1 = ol.proj.fromLonLat([77.6013, 12.9044]);
coordinate2 = ol.proj.fromLonLat([77.6885, 12.9536]);

for (i = 0, ii = styles.length; i < ii; ++i) {
    layers.push(new ol.layer.Tile({
        visible: false,
        preload: Infinity,
        extent: [coordinate1[0], coordinate1[1], coordinate2[0], coordinate2[1]],
        myattribute: styles[i],
        source: new ol.source.BingMaps({
            key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
            imagerySet: styles[i]
            // use maxZoom 19 to see stretched tiles instead of the BingMaps
            // "no photos at this zoom level" tiles
            // maxZoom: 19
        })
    }));
}
var map = new ol.Map({
    layers: layers,
    // Improve user experience by loading tiles while dragging/zooming. Will make
    // zooming choppy on mobile or slow devices.
    loadTilesWhileInteracting: true,
    target: 'map',
    view: new ol.View({
        center: ol.proj.fromLonLat([77.6244159, 12.9370699]),
        maxZoom: 20,
        minZoom: 13,
        zoom: 13
    })
});

var select = document.getElementById('layer-select');

function onChange() {
    var style = select.value;
    for (var i = 0, ii = layers.length; i < ii; ++i) {
        layers[i].setVisible(styles[i] === style);
        console.log(layers[i].get('extent'));
    }
}
select.addEventListener('change', onChange);
onChange();

Now my map has a special feature if you noticed , I.E. it has an extent set , I.E. tiles beyond a certain extent won't load, now what i really want to acomplish is, i want the tiles for this extent to be loaded from locally I.E. when the user visits my website the second time around , the tiles sound load form his localstorage , How can this be accomplished ? or can this be accomplished at all , this is a requirement for my project and i have been stuck for some days now on this , can anybody shed some light on this as to how is this possible?


text:
Q: ClickHouse - CollapsingMergeTree Table Engine - Records are not merged even if they have same column values and different signs(+1/-1) We have a ClickHouse table with CollapsingMergeTree engine. We want to update the records as and when data is imported from source(May be frequent). Initially all the records are inserted with +1 sign column. What we do to update a record is we insert the record to be updated with same values with -1 sign and then insert an updated record with +1 sign expecting that the same records with opposite signs will be collapsed by ClickHouse when data parts are merged in background.
The problem is 'It never happens'
I am aware of the fact that ClickHouse will merge data asynchronously but its been months and no merge is performed by ClickHouse.
I queried SELECT * FROM system.merges to know if any merges are in progress. Query result was 0. Also updated ClickHouse to its latest version. But no luck!
Would appreicate your help if anyone can point out what's the issue? Am I missing on any server level settings? When ClickHouse merges such records?
Or any other approach I should be taking to update ClickHouse data?

A: eventually -- could be never.
You should not rely on merge process. It has own complicated algorithm to balance number of parts.
Merge has no goal to do final merge -- to make 1 part because it's not efficient.
optimize does / forces unnplaned merge, and you'll get for example 4 parts from 22
optimize final does / forces unnplaned merges for all parts until only one part in partition
The only problem with final that it rewrites even 1 part to a new 1 part. Because sometimes it needed to collapse rows over a single part.
So for some tables we run optimize table x partition final (by crond)  for partitions which have more than one part.
select  concat('optimize table ',database, '.','\`', table, '\` partition ',  ((groupUniqArray(partition)) as partition_count)[1], ' final')
    from system.parts
    where (database = 'xxx' or database like 'zzzz\_%') and (database,table) in (select database, table from system.replicas where engine='ReplicatedReplacingMergeTree' and is_leader)
          and table not like '.inner%'
    group by database,table having   length(partition_count)>1 and sum(rows) < 5000000

https://stackoverflow.com/a/60154073/11644308


text:
Q: Postgres sql select result based on a ranking derived from a text column Scratching my head here. I have a very simple postgres table from which I need to select a unique row per day, based solely on a text column which updates as follows.
First update= 'AA1', 2nd update=  'AB', 3rd update= 'D4'
    id  item      date         run    value
    ---------------------------------------
    23  apple     01/01/16      AA1    232
    25  apple     01/01/16      AB     254
    26  apple     01/01/16      D4     212

Depending on the time of day, running a query based on the date ('01/01/2016') would return 1, 2 or 3 rows. However I only need the latest row e.g. Run = D4 above.
How can I write a simple select query that always returns just the latest row based of a text based column? I presume i need to create a ranking based on the 'run' column but Im not sure how to do this.
regards

A: Using the handy distinct on:
select distinct on (date) *
from t
order by date, run desc


text:
Q: Confusion about $\{f\in C[0,1]|f(0)=0\}$ being closed in $(C[0,1],||\cdot||_\infty)$ but not closed in $(C[0,1],||\cdot||_1) $. I am not sure as to why $Y=\{f\in C[0,1]|f(0)=0\}$ is closed with respect to the infinity norm but not the $L^1$ norm. I tried to use a counter example $f_n(t)=1-e^{-nt}$, by trying to show that the limit function is not in $Y$ but isn't the fact that $f(0)\neq 0$ mean that the limit is not in $Y$ even though $f_n\in Y$?
I have probably contradicted myself, but I have no idea as to how to attempt this any other way and would be grateful for any help!


text:
Q: Change font size on each browser zoom out level I want change font-size on each browser zoom out level,
for example:
@media screen and (-webkit-max-device-pixel-ratio: 0.25) {
    div {
        font-size: 10px;
    }
}

@media screen and (-webkit-max-device-pixel-ratio: 0.50) {
    div {
        font-size: 20px;
    }
}

@media screen and (-webkit-max-device-pixel-ratio: 100) {
    div {
        font-size: 50px;
    }
}

above codes not working..

A: The problem is that you have set -webkit-text-size-adjust: none; for the body in layout.css. Changing it to -webkit-text-size-adjust: auto; allows the zooming of the fonts along with the page.


text:
Q: Checklist for starting an open-source project To start an open-source project is not just to throw up the source code on some public repository and then being happy with that. You should have technical (besides user) documentation, information on how to contribute etc.
If creating a checklist over important things to do, what would you include on it?

A: The most important thing is:

*

*use the project yourself and get it into a useful state where you enjoy using it. be sure the project works and is useful.

Things I'd put in the early priorities are:

*

*have a simple "what is it?" web site with links to some discussion forum (whether email or chat) and to the source code repository

*be sure the code compiles and usually works, don't commit work-in-progress or half-ass patches on the main branch that break things, because then other people's work would be disrupted

*put a license file in the code repository with a well-known license, and mark the copyright owner (probably you, or your company). don't omit the license, make up a license, or use an obscure license.

*have instructions for how to contribute, say in a HACKING file or include in your README. This should include where to send patches, how to format patches, code indentation rules, any other important conventions of the project

*have instructions on how to report a bug

*be helpful on the mailing list or whatever your forums are

After those priorities I'd say:

*

*documentation (this saves you work on the mailing list... make a FAQ from your list posts is a simple start)

*try to do things in a "normal" way (don't invent your own build system or use some weird one, don't use 1-space indentation, don't be annoyingly quirky in general because it adds learning curve)

*promote your project. marketing marketing marketing. You need some blogs and news sites and stuff like that to cover you, and then when people show up interested, you need to talk to them and be sure they get it working and look at their patches. Maybe mention your project in the forums for related projects.

*always review and accept patches as quickly as humanly possible. Immediately is perfect. More than a couple days and you are losing lots of people.

*always reply to email about the project as quickly as humanly possible.

*create a welcoming/positive/fun atmosphere. don't be a jerk. say please and thank you and hand out praise. chase off any jackasses that turn up and start to poison the community. try to meet people in person when you can and form bonds.

A: For starters, Lower the barrier to entry, this means:

*

*make it easy to install,

*make it easy to modify,

*make it easy to find your project,

*just make everything you'd want to do easy.

How?

*

*Give an answer to every question you can think of in your documentation,

*Create an easy to use build system,

*Clean up your code, nobody likes working on spaghetti code,

*Make something that people have a need for.


text:
Q: Squeezebox show custom content (no iframe) I'd like to show some custom (HTML) content on a squeezebox (within Joomla).
To show an iFrame I'm using this code:
window.addEvent('domready', function() {
    SqueezeBox.open('https://whatever.com', {handler: 'iframe'});
});

Thats working fine. But how can I display whatever I want?!


text:
Q: CSS flex last incomplete row items take the width of complete row items I'm creating a flexbox; a container has a max-width, say max-width = 500px, and child items each has min-width: 130px and flex-grow: 1 to fill the whole row space.
Here's the fiddle: https://jsfiddle.net/7wroxkhj/6/
What I want to achieve is, for the last row items to take the same width of preceding items. i.e.: item #7 and item #8 to have the same width of items from 1 to 6.
How can I achieve that?
UPDATE:
JS solutions are welcomed!

A: You may want to consider something along the lines of invisible flex items at the end of the list.
HTML

1

2

3

4

5

6

7

8

9
  /* new */

10
 /* new */

CSS
.hidden {
    visibility: hidden;
    height: 0;
    font-size: 0;
    margin: 0 10px;
}

DEMO

A: Give top the pseudo element the same properties that you are giving the elements, but a height very low.
But if more than 2 pseudo element are needed, you need another technique

.parent {
  background: red;
  max-width: 500px;
  height: 400px;
  display: flex;
  flex-wrap: wrap;
}
.parent::after {
  content: '';
  flex: 130px 1;
  margin: 10px;
  background-color: yellow;
  height: 10px;
}
.child {
  background: blue;
  margin: 10px;
  flex: 130px 1;
  color: #FFFFFF;
  text-align: center;
  line-height: 50px;
  font-size: 60px;
}

1

2

3

4

5

6

7

8

Note that the real height for the pseudo would be 0px, and the background yellow wouldn't be there...
Those are just for demo purposes
Edit: FF handles different the situation where the minimun height comes from min-height and the situation where it comes from flex-basis. But Chrome handles those just the same. So my previous solution worked only for Chrome. (Don't know for sure which is "standard".
I changed the min-height of .child and moved it to flex-basis, now it works ok both in Chrome and FF.

A: UPDATE
Ok, I finally figured out why OPs was seeing everything so differently than I was. I was using Chrome and OP was using Firefox. The following is the newest demo that should be compatible with Chrome and Firefox.

*

*The major changes include wrapping the whole layout in a flex-column container.

*Removed the margins: 10px; because flexbox with box-sizing doesn't handle margins or borders as expected.

*Used a plethora of min and max height and width properties.

*Used justify-content: space-between and align-items: space-between on column and row directions which made a tight yet flexible grid.

https://jsfiddle.net/zer00ne/fkczpggy/

.case {
  background: red;
  display: flex;
  flex-flow: column wrap;
  justify-content: space-between;
  align-items: space-around;
  margin: auto 0;
  max-width: 500px;
  overflow-y: auto;
}

.parent {
  background: red;
  height: 99vh;
  min-height: 100%;
  max-width: 500px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: space-between;
  flex: 0 1 auto;
  overflow-y: auto;
}

.child {
  background: blue;
  min-width: 130px;
  min-height: 130px;
  border: 1% solid transparent;
  color: #FFFFFF;
  height: auto;
  text-align: center;
  font-size: 60px;
  flex: 1 0 10%;
  margin: 1%;
}

.child:last-of-type {
  visibility: hidden;
}

1

2

3

4

5

6

7

8

9

OLD

Here's a lazy but effective way:

Updated to reflect dynamic variable number of divs
Use nth-of-type(n+9)
or this would be better:
last-of-type

*

*Add the 9th div

*Then add this single line to your CSS:
.child:nth-of-type(n+9) {
  visibility: hidden;
}

or
.child:last-of-type {
  visibility: hidden;
}

https://jsfiddle.net/zer00ne/4fp88arh/

.parent {
  background: red;
  max-width: 500px;
  height: 400px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
/*.parent:after {
  content: '';
  flex-grow: 1000000000;
}*/

.child {
  background: blue;
  min-width: 130px;
  margin: 10px;
  flex-grow: 1;
  color: #FFFFFF;
  text-align: center;
  line-height: 50px;
  font-size: 60px;
}

/*.child:nth-of-type(n+9) {
  visibility: hidden;
}*/

 .child:last-of-type {
   visibility: hidden;
 }

1

2

3

4

5

6

7

8


text:
Q: Liferay portlet doView() back button issue I have a portlet in Liferay 6.0 (GenericPortlet) with a redirect to a jsp page in the doView() method, problem is that with Chrome and Firefox if the user click the back button it seems the doView() method is not called at all.
Anyone had this problem? Any help would be really appreciated


text:
Q: Pointwise limit of $f$ If we let $f_n(x)= 1,$ if $x\in\{1,\frac{1}{2},...,\frac{1}{n}\}$ and $0$, otherwise. How can I find the pointwise limit $f$ of this sequence?

A: Argue by cases.
If $x$ is of the form $\frac1k$ for some $k$, then convince yourself that $x\in\{1,\frac12,\ldots,\frac1n\}$ for all sufficiently large $n$, which means $f_n(x)=1$ for all sufficiently large $n$. Thus $f_n(x)\to1$.
If $x$ is not of the form $\frac1k$ for any $k$, then argue that $x$ is never a member of the set $\{1,\frac12,\ldots,\frac1n\}$ and therefore $f_n(x)=0$ for all $n$. Thus $f_n(x)\to0$.


text:
Q: Position(t) on cubic bezier curve The only equation to calculate this that I can find involves t in the range [0, 1], but I have no idea how long it will take to travel the entire path, so I can't calculate (1 - t).
I know the speed at which I'm traveling, but it seems to be a heavy idea to calculate the total time beforehand (nor do I actually know how to do that calculation). What is an equation to figure out the position without knowing the total time?
Edit To clarify on the cubic bezier curve: I have four control points (P0 to P1), and to get a value on the curve with t, I need to use the four points as such:
B(t) = (1-t)^3P0 + 3t(1-t)^2P1 + 3t^2(1-t)P2 + t^3P3
I am not using a parametric equation to define the curve. The control points are what define the curve. What I need is an equation that does not require the use of knowing the range of t.

A: I think there is a misunderstanding here. The 't' in the cubic Bezier curve's definition does not refer to 'time'. It is parameter that the x, y or even z functions based on. Unlike the traditional way of representing y as a function of x, such as y=f(x), an alternative way of representing a curve is by the parametric form that represents x, y and z as functions of an additional parameter t, C(t)=(x(t), y(t), z(t)). Typically the t value will range from 0 to 1, but this is not a must. The common representation for a circle as x=cos(t) and y=sin(t) is an example of parametric representation. So, if you have the parametric representation of a curve, you can evaluate the position on the curve for any given t value. It has nothing to do with the time it takes to travel the entire path.

A: You have the given curve and you have your speed. To calculate what you're asking for you need to divide the total distance by the speed you traveled given that time. That will give you the parametric (t) you need. So if the total curve has a distance of 72.2 units and your speed is 1 unit then your t is 1/72.2.
Your only missing bit is calculating the length of a given curve. This is typically done by subdividing it into line segments small enough that you don't care, and then adding up the total distance of those line segments. You could likely combine those two steps as well if you were so inclined. If you have your given speed, just iteration like 1000th of the curve add the line segment between the start and point 1000th of the way through the curve, and subtract that from how far you need to travel (given that you have speed and time, you have distance you need to travel), and keep that up until you've gone as far as you need to go.
The range for t is between 0 and 1.
        x = (1-t)*(1-t)*(1-t)*p0x + 3*(1-t)*(1-t)*t*p1x + 3*(1-t)*t*t*p2x + t*t*t*p3x;
        y = (1-t)*(1-t)*(1-t)*p0y + 3*(1-t)*(1-t)*t*p1y + 3*(1-t)*t*t*p2y + t*t*t*p3y;